-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.mjs
196 lines (175 loc) · 4.95 KB
/
main.mjs
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { dirname, join } from "node:path";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { fileURLToPath } from "node:url";
import workerd from "workerd";
// CLI args
const watchMode = process.argv.includes("--watch");
// Dirs
export const testsDir = fileURLToPath(new URL(".", import.meta.url));
export const rootDir = fileURLToPath(new URL("../..", import.meta.url));
export const srcDir = join(rootDir, "src");
/**
* Test runner main
*/
async function main() {
// Print info
console.log(
`Workerd: ${workerd.version} (compatibility date: ${workerd.compatibilityDate})`,
);
// Start module server
const server = await createModuleServer(8888);
server.unref();
// Run tests once
if (runTests() === false) {
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}
// Start watcher
if (watchMode) {
const watcher = await import("@parcel/watcher").then((r) => r.default);
const watchDirs = [srcDir, testsDir];
console.log(
`Watching for changes:\n${watchDirs.map((d) => ` - ${d}`).join("\n")}`,
);
for (const dir of watchDirs) {
watcher.subscribe(
dir,
() => {
console.clear();
runTests();
},
{ ignore: [".tmp"] },
);
}
}
}
/**
* Spawn workerd to run tests
*/
function runTests() {
try {
runTests.proc?.kill();
runTests.proc = undefined;
console.log(`Running tests...`);
const workerdBin = workerd.default;
runTests.proc = spawn(
workerdBin,
["test", "--experimental", "config.capnp"],
{
cwd: testsDir,
stdio: "inherit",
env: {
...process.env,
LLVM_SYMBOLIZER: findLLVMsymbolizer(),
},
},
).on("exit", (code) => {
if (code !== 0) {
throw new Error(`Test failure`);
}
});
} catch (error) {
if (error) {
console.error(error.stdout || error);
}
return false;
}
}
/**
* Try to llvm-symbolizer binary in common locations
*/
function findLLVMsymbolizer() {
if (process.env.LLVM_SYMBOLIZER) {
return process.env.LLVM_SYMBOLIZER;
}
const paths = [
"/opt/homebrew/opt/llvm/bin/llvm-symbolizer",
"/usr/bin/llvm-symbolizer",
];
for (const path of paths) {
if (existsSync(path)) {
return path;
}
}
return "llvm-symbolizer";
}
/**
* Create fallback module server
*
* Reference:
* https://github.com/cloudflare/workerd/pull/1423
* https://github.com/cloudflare/workerd/tree/main/samples/module_fallback
*/
async function createModuleServer(port = 8888) {
// Unenv preset
const { createJiti } = await import("jiti");
const jiti = createJiti(import.meta.url);
/** @type {import("../../src/index")} */
const unenv = await jiti.import("../../src/index.ts");
const preset = unenv.defineEnv({ nodeCompat: true });
const alias = Object.fromEntries(
Object.entries(preset.env.alias).map(([k, v]) => [
k,
v.replace("unenv/runtime", join(srcDir, "runtime")),
]),
);
// Use esbuild to bundle
const { build } = await import("esbuild");
const server = createServer(async (req, res) => {
try {
const resolveMethod = req.headers["x-resolve-method"];
const url = new URL(req.url, "http://localhost");
const referrer = url.searchParams.get("referrer");
const specifier = url.searchParams.get("specifier");
const rawSpecifier = url.searchParams.get("rawSpecifier");
console.log(
`[server] ${rawSpecifier} ${referrer ? `from ${referrer}` : ""}`,
);
// unenv/runtime/*
const unenvPath = /^unenv\/runtime\/(.*)$/.exec(rawSpecifier)?.[1];
if (!unenvPath) {
res.writeHead(404);
return res.end();
}
// Load node module
// prettier-ignore
const entryFile = join(srcDir, "runtime", unenvPath) + '.ts'
const transpiled = await build({
entryPoints: [entryFile],
banner: {
js: `/*\n * Raw specifier: ${rawSpecifier}\n * Source: ${entryFile}\n */\n`,
},
bundle: true,
write: false,
format: "esm",
target: "esnext",
platform: "node",
sourcemap: "inline",
alias,
});
const esModule = transpiled.outputFiles[0].text;
if (process.env.DUMP_MODULES) {
const dumpPath = join(testsDir, ".tmp", rawSpecifier + ".mjs");
await mkdir(dirname(dumpPath), { recursive: true });
await writeFile(dumpPath, esModule, "utf8");
}
res.end(JSON.stringify({ esModule }));
} catch (error) {
console.error("[server]", error);
res.writeHead(500);
res.end();
}
});
return new Promise((resolve) => {
server.listen({ port, host: "localhost" }, () => {
console.log(
`Module fallback server listening on http://localhost:${port}`,
);
resolve(server);
});
});
}
await main();