-
-
Notifications
You must be signed in to change notification settings - Fork 882
Expand file tree
/
Copy pathdev-worker.mjs
More file actions
269 lines (237 loc) · 7.63 KB
/
Copy pathdev-worker.mjs
File metadata and controls
269 lines (237 loc) · 7.63 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { ModuleRunner, ESModulesEvaluator } from "vite/module-runner";
import { createViteTransport } from "env-runner/vite";
// Custom evaluator for workerd where `new AsyncFunction()` is disallowed.
// Uses the unsafeEvalBinding exposed by the env-runner miniflare wrapper.
class WorkerdModuleEvaluator {
startOffset = 0;
async runInlinedModule(context, code) {
const unsafeEval = globalThis.__ENV_RUNNER_UNSAFE_EVAL__;
const keys = Object.keys(context);
const fn = unsafeEval.newAsyncFunction('"use strict";' + code, "runInlinedModule", ...keys);
await fn(...keys.map((k) => context[k]));
Object.seal(context[Object.keys(context)[0]]);
}
runExternalModule(filepath) {
return import(filepath);
}
}
// ----- IPC -----
let sendMessage;
const messageListeners = new Set();
// ----- Environment runners -----
const envs = (globalThis.__nitro_vite_envs__ ??= {
nitro: undefined,
ssr: undefined,
});
class ViteEnvRunner {
constructor({ name, entry }) {
this.name = name;
this.entryPath = entry;
this.entry = undefined;
this.entryError = undefined;
// Create Vite Module Runner
// https://vite.dev/guide/api-environment-runtimes.html#modulerunner
const onMessage = (listener) => messageListeners.add(listener);
const transport = createViteTransport((data) => sendMessage?.(data), onMessage, name);
const evaluator = globalThis.__ENV_RUNNER_UNSAFE_EVAL__
? new WorkerdModuleEvaluator()
: new ESModulesEvaluator();
const debug =
typeof process !== "undefined" && process.env?.NITRO_DEBUG ? console.debug : undefined;
this.runner = new ModuleRunner({ transport }, evaluator, debug);
this.reload();
}
async reload() {
try {
// Drop stale evaluations so the re-import walks the whole graph.
// Without this, any module whose transform is already populated on the
// Vite side is answered with `{cache: true}` and its old evaluation is
// reused. Vite's own full-reload handler clears the cache the same way.
this.runner.evaluatedModules.clear();
this.entry = await this.runner.import(this.entryPath);
this.entryError = undefined;
} catch (error) {
console.error(error);
this.entryError = error;
}
}
// Errors are intentionally not caught here: like production services,
// they propagate to the caller (the nitro app's error handler or the
// env-runner fetch boundary below).
async fetch(req, init) {
for (let i = 0; i < 5 && !(this.entry || this.entryError); i++) {
await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i)));
}
if (this.entryError) {
throw this.entryError;
}
if (!this.entry) {
throw httpError(503, `Vite environment "${this.name}" is unavailable`);
}
const entryFetch = this.entry.fetch || this.entry.default?.fetch;
if (!entryFetch) {
throw httpError(500, `No fetch handler exported from ${this.entryPath}`);
}
return entryFetch(req, init);
}
}
// ----- RPC -----
const rpcRequests = new Map();
function rpc(name, data, timeout = 3000) {
const id = Math.random().toString(36).slice(2);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
rpcRequests.delete(id);
reject(new Error(`RPC "${name}" timed out`));
}, timeout);
rpcRequests.set(id, { resolve, reject, timer });
sendMessage?.({ __rpc: name, __rpc_id: id, data });
});
}
// Trap unhandled errors to avoid worker crash
if (typeof process !== "undefined" && typeof process.on === "function") {
process.on("unhandledRejection", (error) => console.error(error));
process.on("uncaughtException", (error) => console.error(error));
}
// ----- RSC Support -----
// define __VITE_ENVIRONMENT_RUNNER_IMPORT__ for RSC support
// https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-rsc/README.md#__vite_environment_runner_import__
globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async function (environmentName, id) {
const env = envs[environmentName];
if (!env) {
throw new Error(`Vite environment "${environmentName}" is not registered`);
}
return env.runner.import(id);
};
// ----- Reload -----
async function reload() {
try {
await Promise.all(Object.values(envs).map((env) => env?.reload()));
} catch (error) {
console.error(error);
}
}
// eslint-disable-next-line unicorn/prefer-top-level-await
reload();
// ----- HTML Transform -----
globalThis.__transform_html__ = async function (html) {
html = await rpc("transformHTML", html).catch((error) => {
console.warn("Failed to transform HTML via Vite:", error);
return html;
});
return html;
};
// ----- Exports (env-runner AppEntry) -----
export async function fetch(req) {
const viteEnv = req?.headers.get("x-vite-env") || "nitro";
const env = envs[viteEnv];
if (!env) {
return renderError(req, httpError(500, `Unknown vite environment "${viteEnv}"`));
}
try {
return await env.fetch(req);
} catch (error) {
return renderError(req, error);
}
}
export function upgrade(context) {
const handleUpgrade = envs.nitro?.entry?.handleUpgrade;
if (handleUpgrade) {
handleUpgrade(context.node.req, context.node.socket, context.node.head);
}
}
export const ipc = {
onOpen(ctx) {
sendMessage = ctx.sendMessage;
},
onMessage(message) {
if (message?.__rpc_id) {
const req = rpcRequests.get(message.__rpc_id);
if (req) {
clearTimeout(req.timer);
rpcRequests.delete(message.__rpc_id);
if (message.error) {
req.reject(typeof message.error === "string" ? new Error(message.error) : message.error);
} else {
req.resolve(message.data);
}
}
return;
}
if (message?.type === "custom") {
if (message.event === "nitro:vite-env") {
const { name, entry } = message.data;
if (!envs[name]) {
envs[name] = new ViteEnvRunner({ name, entry });
}
return;
}
}
if (message?.type === "full-reload") {
reload();
return;
}
for (const listener of messageListeners) {
listener(message);
}
},
onClose() {},
};
// ----- Error handling -----
function httpError(status, message) {
const error = new Error(message || `HTTP Error ${status}`);
error.status = status;
error.name = "NitroViteError";
return error;
}
async function renderError(req, error) {
if (req.headers.get("accept")?.includes("application/json")) {
return new Response(
JSON.stringify(
{
status: error.status || 500,
name: error.name || "Error",
message: error.message,
stack: (error.stack || "")
.split("\n")
.splice(1)
.map((l) => l.trim()),
},
null,
2
),
{
status: error.status || 500,
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, max-age=0, must-revalidate",
Pragma: "no-cache",
Expires: "0",
},
}
);
}
try {
const { Youch } = await import("youch");
const youch = new Youch();
return new Response(await youch.toHTML(error), {
status: error.status || 500,
headers: {
"Content-Type": "text/html",
"Cache-Control": "no-store, max-age=0, must-revalidate",
Pragma: "no-cache",
Expires: "0",
},
});
} catch {
return new Response(`<pre>${error.stack || error.message || error}</pre>`, {
status: error.status || 500,
headers: {
"Content-Type": "text/html",
"Cache-Control": "no-store, max-age=0, must-revalidate",
Pragma: "no-cache",
Expires: "0",
},
});
}
}