-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffmark.ts
94 lines (50 loc) · 1.59 KB
/
offmark.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { TextLineStream } from 'jsr:@std/streams@^1.0.0/text-line-stream';
const TOGGLE = '`'.repeat(3);
const INDENT_LEN = 4;
const INDENT = ' '.repeat(INDENT_LEN);
export class OffmarkStream extends TransformStream<string, string> {
constructor ({
toggle = (str: string) => str.startsWith(TOGGLE),
indent = {
check: (str: string) => str.startsWith(INDENT),
remove: (str: string) => str.slice(INDENT_LEN),
},
} = {}) {
let on = false;
super({
transform (data, ctrl) {
if (toggle(data)) {
on = !on;
return;
}
if (on) {
return ctrl.enqueue(data);
}
if (indent.check(data)) {
return ctrl.enqueue(indent.remove(data));
}
},
});
}
}
export function pipe (
readable: ReadableStream<Uint8Array>,
): ReadableStream<Uint8Array> {
return readable
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream())
.pipeThrough(new OffmarkStream())
.pipeThrough(new TransformStream({
transform (data, ctrl) {
ctrl.enqueue(data.concat('\n'));
},
}))
.pipeThrough(new TextEncoderStream())
;
}
export async function main (
readable: ReadableStream<Uint8Array>,
writable: WritableStream<Uint8Array>,
): Promise<void> {
await pipe(readable).pipeTo(writable);
}