-
Notifications
You must be signed in to change notification settings - Fork 42
/
wpt-runner.ts
69 lines (60 loc) · 1.78 KB
/
wpt-runner.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
import { assertEquals } from "https://deno.land/std@0.75.0/testing/asserts.ts";
import {
basename,
dirname,
join,
} from "https://deno.land/std@0.75.0/path/mod.ts";
import { DOMParser, Element } from "../deno-dom-wasm.ts";
const parser = new DOMParser();
const cachedScripts: { [script: string]: string } = {};
export type Backend = "wasm" | "native";
export async function run(path: string, root: string, backend: Backend) {
const html = await Deno.readTextFile(path);
const doc = parser.parseFromString(html, "text/html")!;
let scripts = Array.from(doc.querySelectorAll("script")).map((scriptNode) => {
const scriptElement = scriptNode as Element;
let script = scriptElement.getAttribute("src")!;
let scriptContents: string;
if (script) {
if (script[0] === "/") {
script = root + script;
} else {
script = join(dirname(path), script);
}
if (cachedScripts[script]) {
scriptContents = cachedScripts[script];
} else {
scriptContents = cachedScripts[script] = Deno.readTextFileSync(script);
}
} else {
scriptContents = scriptElement.textContent;
}
return scriptContents;
});
const workerOptions = { type: "module" } as const;
if (backend === "native") {
(workerOptions as any).deno = {
namespace: true,
};
}
const worker = new Worker(
new URL("./wpt-runner-worker.ts", import.meta.url).href,
workerOptions,
);
worker.postMessage({
backend,
html,
scripts,
});
await new Promise<void>((resolve, reject) => {
worker.addEventListener("error", (event) => {
event.preventDefault();
worker.terminate();
reject(event);
});
worker.addEventListener("message", (event) => {
worker.terminate();
resolve();
});
});
}