forked from cloudflare/html-rewriter-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
65 lines (57 loc) · 1.8 KB
/
index.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
import {
default as init,
HTMLRewriter as RawHTMLRewriter,
} from "../html_rewriter.js";
import type {
DocumentHandlers,
ElementHandlers,
HTMLRewriterOptions as RawHTMLRewriterOptions,
} from "../html_rewriter.d.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export class HTMLRewriter {
private elementHandlers: [selector: string, handlers: ElementHandlers][] = [];
private documentHandlers: DocumentHandlers[] = [];
private promise: Promise<WebAssembly.Exports>;
constructor(private readonly options?: RawHTMLRewriterOptions) {
this.promise = init((async () => {
const x = await Deno.open(new URL('../html_rewriter_bg.wasm', import.meta.url), { read: true })
const r = new Response(x.readable, {
headers: {
'content-type': 'application/wasm',
// 'content-length': '' + (await x.stat()).size,
},
});
return r;
})())
}
on(selector: string, handlers: ElementHandlers): this {
this.elementHandlers.push([selector, handlers]);
return this;
}
onDocument(handlers: DocumentHandlers): this {
this.documentHandlers.push(handlers);
return this;
}
async transform(input: string): Promise<string> {
await this.promise;
let output = "";
const rewriter = new RawHTMLRewriter((chunk: any) => {
output += decoder.decode(chunk);
}, this.options);
for (const [selector, handlers] of this.elementHandlers) {
rewriter.on(selector, handlers);
}
for (const handlers of this.documentHandlers) {
rewriter.onDocument(handlers);
}
try {
await rewriter.write(encoder.encode(input));
await rewriter.end();
return output;
} finally {
rewriter.free();
}
}
}
export const timeout = (t: number) => new Promise(r => setTimeout(r, t));