@cloudflare/vite-plugin 1.13.10 → 1.13.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1648 @@
1
+ import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
2
+
3
+ //#region src/shared.ts
4
+ const UNKNOWN_HOST = "http://localhost";
5
+ const INIT_PATH = "/__vite_plugin_cloudflare_init__";
6
+ const WORKER_ENTRY_PATH_HEADER = "__VITE_WORKER_ENTRY_PATH__";
7
+ const IS_ENTRY_WORKER_HEADER = "__VITE_IS_ENTRY_WORKER__";
8
+
9
+ //#endregion
10
+ //#region src/workers/runner-worker/env.ts
11
+ /**
12
+ * Strips internal properties from the `env` object, returning only the user-defined properties.
13
+ * @param internalEnv - The full wrapper env, including internal properties
14
+ * @returns The user-defined env
15
+ */
16
+ function stripInternalEnv(internalEnv) {
17
+ const { __VITE_RUNNER_OBJECT__: __VITE_RUNNER_OBJECT__$1, __VITE_INVOKE_MODULE__, __VITE_UNSAFE_EVAL__,...userEnv } = internalEnv;
18
+ return userEnv;
19
+ }
20
+
21
+ //#endregion
22
+ //#region src/workers/runner-worker/errors.ts
23
+ /**
24
+ * Converts an error to an object that can be be serialized and revived by Miniflare.
25
+ * Copied from `packages/wrangler/templates/middleware/middleware-miniflare3-json-error.ts`
26
+ */
27
+ function reduceError(e) {
28
+ return {
29
+ name: e?.name,
30
+ message: e?.message ?? String(e),
31
+ stack: e?.stack,
32
+ cause: e?.cause === void 0 ? void 0 : reduceError(e.cause)
33
+ };
34
+ }
35
+ /**
36
+ * Captures errors in the `fetch` handler of the default export of the entry Worker.
37
+ * These are returned as a JSON response that is revived by Miniflare.
38
+ * See comment in `/packages/wrangler/src/deployment-bundle/bundle.ts` for more info.
39
+ */
40
+ async function maybeCaptureError(options, fn) {
41
+ if (!options.isEntryWorker || options.exportName !== "default" || options.key !== "fetch") return fn();
42
+ try {
43
+ return await fn();
44
+ } catch (error) {
45
+ return Response.json(reduceError(error), {
46
+ status: 500,
47
+ headers: { "MF-Experimental-Error-Stack": "true" }
48
+ });
49
+ }
50
+ }
51
+
52
+ //#endregion
53
+ //#region ../../node_modules/.pnpm/vite@7.0.0_@types+node@20.19.9_jiti@2.6.0_lightningcss@1.29.2_yaml@2.8.1/node_modules/vite/dist/node/module-runner.js
54
+ /**
55
+ * Prefix for resolved Ids that are not valid browser import specifiers
56
+ */
57
+ const VALID_ID_PREFIX = "/@id/", NULL_BYTE_PLACEHOLDER = "__x00__";
58
+ let SOURCEMAPPING_URL = "sourceMa";
59
+ SOURCEMAPPING_URL += "ppingURL";
60
+ const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP", isWindows = typeof process < "u" && process.platform === "win32";
61
+ /**
62
+ * Undo {@link wrapId}'s `/@id/` and null byte replacements.
63
+ */
64
+ function unwrapId(id) {
65
+ return id.startsWith(VALID_ID_PREFIX) ? id.slice(5).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
66
+ }
67
+ const windowsSlashRE = /\\/g;
68
+ function slash(p) {
69
+ return p.replace(windowsSlashRE, "/");
70
+ }
71
+ const postfixRE = /[?#].*$/;
72
+ function cleanUrl(url) {
73
+ return url.replace(postfixRE, "");
74
+ }
75
+ function isPrimitive(value) {
76
+ return !value || typeof value != "object" && typeof value != "function";
77
+ }
78
+ const AsyncFunction = async function() {}.constructor;
79
+ let asyncFunctionDeclarationPaddingLineCount;
80
+ function getAsyncFunctionDeclarationPaddingLineCount() {
81
+ if (asyncFunctionDeclarationPaddingLineCount === void 0) {
82
+ let body = "/*code*/", source = new AsyncFunction("a", "b", body).toString();
83
+ asyncFunctionDeclarationPaddingLineCount = source.slice(0, source.indexOf(body)).split("\n").length - 1;
84
+ }
85
+ return asyncFunctionDeclarationPaddingLineCount;
86
+ }
87
+ function promiseWithResolvers() {
88
+ let resolve$1, reject;
89
+ return {
90
+ promise: new Promise((_resolve, _reject) => {
91
+ resolve$1 = _resolve, reject = _reject;
92
+ }),
93
+ resolve: resolve$1,
94
+ reject
95
+ };
96
+ }
97
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
98
+ function normalizeWindowsPath(input = "") {
99
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
100
+ }
101
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
102
+ function cwd() {
103
+ return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
104
+ }
105
+ const resolve = function(...arguments_) {
106
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
107
+ let resolvedPath = "", resolvedAbsolute = !1;
108
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
109
+ let path = index >= 0 ? arguments_[index] : cwd();
110
+ !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
111
+ }
112
+ return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
113
+ };
114
+ function normalizeString(path, allowAboveRoot) {
115
+ let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
116
+ for (let index = 0; index <= path.length; ++index) {
117
+ if (index < path.length) char = path[index];
118
+ else if (char === "/") break;
119
+ else char = "/";
120
+ if (char === "/") {
121
+ if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
122
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
123
+ if (res.length > 2) {
124
+ let lastSlashIndex = res.lastIndexOf("/");
125
+ lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
126
+ continue;
127
+ } else if (res.length > 0) {
128
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
129
+ continue;
130
+ }
131
+ }
132
+ allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
133
+ } else res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
134
+ lastSlash = index, dots = 0;
135
+ } else char === "." && dots !== -1 ? ++dots : dots = -1;
136
+ }
137
+ return res;
138
+ }
139
+ const isAbsolute = function(p) {
140
+ return _IS_ABSOLUTE_RE.test(p);
141
+ }, dirname = function(p) {
142
+ let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
143
+ return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
144
+ }, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), CHAR_FORWARD_SLASH = 47, CHAR_BACKWARD_SLASH = 92, percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
145
+ function encodePathChars(filepath) {
146
+ return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf("\n") !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
147
+ }
148
+ const posixDirname = dirname, posixResolve = resolve;
149
+ function posixPathToFileHref(posixPath) {
150
+ let resolved = posixResolve(posixPath), filePathLast = posixPath.charCodeAt(posixPath.length - 1);
151
+ return (filePathLast === CHAR_FORWARD_SLASH || isWindows && filePathLast === CHAR_BACKWARD_SLASH) && resolved[resolved.length - 1] !== "/" && (resolved += "/"), resolved = encodePathChars(resolved), resolved.indexOf("?") !== -1 && (resolved = resolved.replace(questionRegex, "%3F")), resolved.indexOf("#") !== -1 && (resolved = resolved.replace(hashRegex, "%23")), new URL(`file://${resolved}`).href;
152
+ }
153
+ function toWindowsPath(path) {
154
+ return path.replace(/\//g, "\\");
155
+ }
156
+ const comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
157
+ for (let i = 0; i < 64; i++) {
158
+ let c = chars.charCodeAt(i);
159
+ intToChar[i] = c, charToInt[c] = i;
160
+ }
161
+ function decodeInteger(reader, relative) {
162
+ let value = 0, shift = 0, integer = 0;
163
+ do
164
+ integer = charToInt[reader.next()], value |= (integer & 31) << shift, shift += 5;
165
+ while (integer & 32);
166
+ let shouldNegate = value & 1;
167
+ return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
168
+ }
169
+ function hasMoreVlq(reader, max) {
170
+ return reader.pos >= max ? !1 : reader.peek() !== comma;
171
+ }
172
+ var StringReader = class {
173
+ constructor(buffer) {
174
+ this.pos = 0, this.buffer = buffer;
175
+ }
176
+ next() {
177
+ return this.buffer.charCodeAt(this.pos++);
178
+ }
179
+ peek() {
180
+ return this.buffer.charCodeAt(this.pos);
181
+ }
182
+ indexOf(char) {
183
+ let { buffer, pos } = this, idx = buffer.indexOf(char, pos);
184
+ return idx === -1 ? buffer.length : idx;
185
+ }
186
+ };
187
+ function decode(mappings) {
188
+ let { length } = mappings, reader = new StringReader(mappings), decoded = [], genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
189
+ do {
190
+ let semi = reader.indexOf(";"), line = [], sorted = !0, lastCol = 0;
191
+ for (genColumn = 0; reader.pos < semi;) {
192
+ let seg;
193
+ genColumn = decodeInteger(reader, genColumn), genColumn < lastCol && (sorted = !1), lastCol = genColumn, hasMoreVlq(reader, semi) ? (sourcesIndex = decodeInteger(reader, sourcesIndex), sourceLine = decodeInteger(reader, sourceLine), sourceColumn = decodeInteger(reader, sourceColumn), hasMoreVlq(reader, semi) ? (namesIndex = decodeInteger(reader, namesIndex), seg = [
194
+ genColumn,
195
+ sourcesIndex,
196
+ sourceLine,
197
+ sourceColumn,
198
+ namesIndex
199
+ ]) : seg = [
200
+ genColumn,
201
+ sourcesIndex,
202
+ sourceLine,
203
+ sourceColumn
204
+ ]) : seg = [genColumn], line.push(seg), reader.pos++;
205
+ }
206
+ sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
207
+ } while (reader.pos <= length);
208
+ return decoded;
209
+ }
210
+ function sort(line) {
211
+ line.sort(sortComparator);
212
+ }
213
+ function sortComparator(a, b) {
214
+ return a[0] - b[0];
215
+ }
216
+ const COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4;
217
+ let found = !1;
218
+ /**
219
+ * A binary search implementation that returns the index if a match is found.
220
+ * If no match is found, then the left-index (the index associated with the item that comes just
221
+ * before the desired index) is returned. To maintain proper sort order, a splice would happen at
222
+ * the next index:
223
+ *
224
+ * ```js
225
+ * const array = [1, 3];
226
+ * const needle = 2;
227
+ * const index = binarySearch(array, needle, (item, needle) => item - needle);
228
+ *
229
+ * assert.equal(index, 0);
230
+ * array.splice(index + 1, 0, needle);
231
+ * assert.deepEqual(array, [1, 2, 3]);
232
+ * ```
233
+ */
234
+ function binarySearch(haystack, needle, low, high) {
235
+ for (; low <= high;) {
236
+ let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
237
+ if (cmp === 0) return found = !0, mid;
238
+ cmp < 0 ? low = mid + 1 : high = mid - 1;
239
+ }
240
+ return found = !1, low - 1;
241
+ }
242
+ function upperBound(haystack, needle, index) {
243
+ for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++);
244
+ return index;
245
+ }
246
+ function lowerBound(haystack, needle, index) {
247
+ for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--);
248
+ return index;
249
+ }
250
+ /**
251
+ * This overly complicated beast is just to record the last tested line/column and the resulting
252
+ * index, allowing us to skip a few tests if mappings are monotonically increasing.
253
+ */
254
+ function memoizedBinarySearch(haystack, needle, state, key) {
255
+ let { lastKey, lastNeedle, lastIndex } = state, low = 0, high = haystack.length - 1;
256
+ if (key === lastKey) {
257
+ if (needle === lastNeedle) return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
258
+ needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
259
+ }
260
+ return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
261
+ }
262
+ const LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
263
+ /**
264
+ * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
265
+ * with public access modifiers.
266
+ */
267
+ function cast(map) {
268
+ return map;
269
+ }
270
+ /**
271
+ * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
272
+ */
273
+ function decodedMappings(map) {
274
+ var _a;
275
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
276
+ }
277
+ /**
278
+ * A higher-level API to find the source/line/column associated with a generated line/column
279
+ * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
280
+ * `source-map` library.
281
+ */
282
+ function originalPositionFor(map, needle) {
283
+ let { line, column, bias } = needle;
284
+ if (line--, line < 0) throw Error(LINE_GTR_ZERO);
285
+ if (column < 0) throw Error(COL_GTR_EQ_ZERO);
286
+ let decoded = decodedMappings(map);
287
+ if (line >= decoded.length) return OMapping(null, null, null, null);
288
+ let segments = decoded[line], index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
289
+ if (index === -1) return OMapping(null, null, null, null);
290
+ let segment = segments[index];
291
+ if (segment.length === 1) return OMapping(null, null, null, null);
292
+ let { names, resolvedSources } = map;
293
+ return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
294
+ }
295
+ function OMapping(source, line, column, name) {
296
+ return {
297
+ source,
298
+ line,
299
+ column,
300
+ name
301
+ };
302
+ }
303
+ function traceSegmentInternal(segments, memo, line, column, bias) {
304
+ let index = memoizedBinarySearch(segments, column, memo, line);
305
+ return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
306
+ }
307
+ var DecodedMap = class {
308
+ _encoded;
309
+ _decoded;
310
+ _decodedMemo;
311
+ url;
312
+ version;
313
+ names = [];
314
+ resolvedSources;
315
+ constructor(map, from) {
316
+ this.map = map;
317
+ let { mappings, names, sources } = map;
318
+ this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map((s) => posixResolve(s || "", from));
319
+ }
320
+ };
321
+ function memoizedState() {
322
+ return {
323
+ lastKey: -1,
324
+ lastNeedle: -1,
325
+ lastIndex: -1
326
+ };
327
+ }
328
+ function getOriginalPosition(map, needle) {
329
+ let result = originalPositionFor(map, needle);
330
+ return result.column == null ? null : result;
331
+ }
332
+ const MODULE_RUNNER_SOURCEMAPPING_REGEXP = /* @__PURE__ */ RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
333
+ var EvaluatedModuleNode = class {
334
+ importers = /* @__PURE__ */ new Set();
335
+ imports = /* @__PURE__ */ new Set();
336
+ evaluated = !1;
337
+ meta;
338
+ promise;
339
+ exports;
340
+ file;
341
+ map;
342
+ constructor(id, url) {
343
+ this.id = id, this.url = url, this.file = cleanUrl(id);
344
+ }
345
+ }, EvaluatedModules = class {
346
+ idToModuleMap = /* @__PURE__ */ new Map();
347
+ fileToModulesMap = /* @__PURE__ */ new Map();
348
+ urlToIdModuleMap = /* @__PURE__ */ new Map();
349
+ /**
350
+ * Returns the module node by the resolved module ID. Usually, module ID is
351
+ * the file system path with query and/or hash. It can also be a virtual module.
352
+ *
353
+ * Module runner graph will have 1 to 1 mapping with the server module graph.
354
+ * @param id Resolved module ID
355
+ */
356
+ getModuleById(id) {
357
+ return this.idToModuleMap.get(id);
358
+ }
359
+ /**
360
+ * Returns all modules related to the file system path. Different modules
361
+ * might have different query parameters or hash, so it's possible to have
362
+ * multiple modules for the same file.
363
+ * @param file The file system path of the module
364
+ */
365
+ getModulesByFile(file) {
366
+ return this.fileToModulesMap.get(file);
367
+ }
368
+ /**
369
+ * Returns the module node by the URL that was used in the import statement.
370
+ * Unlike module graph on the server, the URL is not resolved and is used as is.
371
+ * @param url Server URL that was used in the import statement
372
+ */
373
+ getModuleByUrl(url) {
374
+ return this.urlToIdModuleMap.get(unwrapId(url));
375
+ }
376
+ /**
377
+ * Ensure that module is in the graph. If the module is already in the graph,
378
+ * it will return the existing module node. Otherwise, it will create a new
379
+ * module node and add it to the graph.
380
+ * @param id Resolved module ID
381
+ * @param url URL that was used in the import statement
382
+ */
383
+ ensureModule(id, url) {
384
+ if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
385
+ let moduleNode$1 = this.idToModuleMap.get(id);
386
+ return this.urlToIdModuleMap.set(url, moduleNode$1), moduleNode$1;
387
+ }
388
+ let moduleNode = new EvaluatedModuleNode(id, url);
389
+ this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
390
+ let fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
391
+ return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
392
+ }
393
+ invalidateModule(node) {
394
+ node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
395
+ }
396
+ /**
397
+ * Extracts the inlined source map from the module code and returns the decoded
398
+ * source map. If the source map is not inlined, it will return null.
399
+ * @param id Resolved module ID
400
+ */
401
+ getModuleSourceMapById(id) {
402
+ let mod = this.getModuleById(id);
403
+ if (!mod) return null;
404
+ if (mod.map) return mod.map;
405
+ if (!mod.meta || !("code" in mod.meta)) return null;
406
+ let mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(mod.meta.code)?.[1];
407
+ return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
408
+ }
409
+ clear() {
410
+ this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
411
+ }
412
+ };
413
+ const prefixedBuiltins = new Set([
414
+ "node:sea",
415
+ "node:sqlite",
416
+ "node:test",
417
+ "node:test/reporters"
418
+ ]);
419
+ function normalizeModuleId(file) {
420
+ if (prefixedBuiltins.has(file)) return file;
421
+ return slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
422
+ }
423
+ var HMRContext = class {
424
+ newListeners;
425
+ constructor(hmrClient, ownerPath) {
426
+ this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
427
+ let mod = hmrClient.hotModulesMap.get(ownerPath);
428
+ mod && (mod.callbacks = []);
429
+ let staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
430
+ if (staleListeners) for (let [event, staleFns] of staleListeners) {
431
+ let listeners = hmrClient.customListenersMap.get(event);
432
+ listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
433
+ }
434
+ this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
435
+ }
436
+ get data() {
437
+ return this.hmrClient.dataMap.get(this.ownerPath);
438
+ }
439
+ accept(deps, callback) {
440
+ if (typeof deps == "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
441
+ else if (typeof deps == "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
442
+ else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
443
+ else throw Error("invalid hot.accept() usage.");
444
+ }
445
+ acceptExports(_, callback) {
446
+ this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
447
+ }
448
+ dispose(cb) {
449
+ this.hmrClient.disposeMap.set(this.ownerPath, cb);
450
+ }
451
+ prune(cb) {
452
+ this.hmrClient.pruneMap.set(this.ownerPath, cb);
453
+ }
454
+ decline() {}
455
+ invalidate(message) {
456
+ let firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
457
+ this.hmrClient.notifyListeners("vite:invalidate", {
458
+ path: this.ownerPath,
459
+ message,
460
+ firstInvalidatedBy
461
+ }), this.send("vite:invalidate", {
462
+ path: this.ownerPath,
463
+ message,
464
+ firstInvalidatedBy
465
+ }), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
466
+ }
467
+ on(event, cb) {
468
+ let addToMap = (map) => {
469
+ let existing = map.get(event) || [];
470
+ existing.push(cb), map.set(event, existing);
471
+ };
472
+ addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
473
+ }
474
+ off(event, cb) {
475
+ let removeFromMap = (map) => {
476
+ let existing = map.get(event);
477
+ if (existing === void 0) return;
478
+ let pruned = existing.filter((l) => l !== cb);
479
+ if (pruned.length === 0) {
480
+ map.delete(event);
481
+ return;
482
+ }
483
+ map.set(event, pruned);
484
+ };
485
+ removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
486
+ }
487
+ send(event, data) {
488
+ this.hmrClient.send({
489
+ type: "custom",
490
+ event,
491
+ data
492
+ });
493
+ }
494
+ acceptDeps(deps, callback = () => {}) {
495
+ let mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
496
+ id: this.ownerPath,
497
+ callbacks: []
498
+ };
499
+ mod.callbacks.push({
500
+ deps,
501
+ fn: callback
502
+ }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
503
+ }
504
+ }, HMRClient = class {
505
+ hotModulesMap = /* @__PURE__ */ new Map();
506
+ disposeMap = /* @__PURE__ */ new Map();
507
+ pruneMap = /* @__PURE__ */ new Map();
508
+ dataMap = /* @__PURE__ */ new Map();
509
+ customListenersMap = /* @__PURE__ */ new Map();
510
+ ctxToListenersMap = /* @__PURE__ */ new Map();
511
+ currentFirstInvalidatedBy;
512
+ constructor(logger, transport, importUpdatedModule) {
513
+ this.logger = logger, this.transport = transport, this.importUpdatedModule = importUpdatedModule;
514
+ }
515
+ async notifyListeners(event, data) {
516
+ let cbs = this.customListenersMap.get(event);
517
+ cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
518
+ }
519
+ send(payload) {
520
+ this.transport.send(payload).catch((err) => {
521
+ this.logger.error(err);
522
+ });
523
+ }
524
+ clear() {
525
+ this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
526
+ }
527
+ async prunePaths(paths) {
528
+ await Promise.all(paths.map((path) => {
529
+ let disposer = this.disposeMap.get(path);
530
+ if (disposer) return disposer(this.dataMap.get(path));
531
+ })), paths.forEach((path) => {
532
+ let fn = this.pruneMap.get(path);
533
+ fn && fn(this.dataMap.get(path));
534
+ });
535
+ }
536
+ warnFailedUpdate(err, path) {
537
+ (!(err instanceof Error) || !err.message.includes("fetch")) && this.logger.error(err), this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
538
+ }
539
+ updateQueue = [];
540
+ pendingUpdateQueue = !1;
541
+ /**
542
+ * buffer multiple hot updates triggered by the same src change
543
+ * so that they are invoked in the same order they were sent.
544
+ * (otherwise the order may be inconsistent because of the http request round trip)
545
+ */
546
+ async queueUpdate(payload) {
547
+ if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
548
+ this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
549
+ let loading = [...this.updateQueue];
550
+ this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
551
+ }
552
+ }
553
+ async fetchUpdate(update) {
554
+ let { path, acceptedPath, firstInvalidatedBy } = update, mod = this.hotModulesMap.get(path);
555
+ if (!mod) return;
556
+ let fetchedModule, isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
557
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
558
+ let disposer = this.disposeMap.get(acceptedPath);
559
+ disposer && await disposer(this.dataMap.get(acceptedPath));
560
+ try {
561
+ fetchedModule = await this.importUpdatedModule(update);
562
+ } catch (e) {
563
+ this.warnFailedUpdate(e, acceptedPath);
564
+ }
565
+ }
566
+ return () => {
567
+ try {
568
+ this.currentFirstInvalidatedBy = firstInvalidatedBy;
569
+ for (let { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
570
+ let loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
571
+ this.logger.debug(`hot updated: ${loggedPath}`);
572
+ } finally {
573
+ this.currentFirstInvalidatedBy = void 0;
574
+ }
575
+ };
576
+ }
577
+ };
578
+ /**
579
+ * Vite converts `import { } from 'foo'` to `const _ = __vite_ssr_import__('foo')`.
580
+ * Top-level imports and dynamic imports work slightly differently in Node.js.
581
+ * This function normalizes the differences so it matches prod behaviour.
582
+ */
583
+ function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
584
+ if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
585
+ let missingBindings = metadata.importedNames.filter((s) => !(s in mod));
586
+ if (missingBindings.length) {
587
+ let lastBinding = missingBindings[missingBindings.length - 1];
588
+ throw moduleType === "module" ? SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`) : SyntaxError(`\
589
+ [vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
590
+ CommonJS modules can always be imported via the default export, for example using:
591
+
592
+ import pkg from '${rawId}';
593
+ const {${missingBindings.join(", ")}} = pkg;
594
+ `);
595
+ }
596
+ }
597
+ }
598
+ let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict", nanoid = (size = 21) => {
599
+ let id = "", i = size | 0;
600
+ for (; i--;) id += urlAlphabet[Math.random() * 64 | 0];
601
+ return id;
602
+ };
603
+ function reviveInvokeError(e) {
604
+ let error = Error(e.message || "Unknown invoke error");
605
+ return Object.assign(error, e, { runnerError: /* @__PURE__ */ Error("RunnerError") }), error;
606
+ }
607
+ const createInvokeableTransport = (transport) => {
608
+ if (transport.invoke) return {
609
+ ...transport,
610
+ async invoke(name, data) {
611
+ let result = await transport.invoke({
612
+ type: "custom",
613
+ event: "vite:invoke",
614
+ data: {
615
+ id: "send",
616
+ name,
617
+ data
618
+ }
619
+ });
620
+ if ("error" in result) throw reviveInvokeError(result.error);
621
+ return result.result;
622
+ }
623
+ };
624
+ if (!transport.send || !transport.connect) throw Error("transport must implement send and connect when invoke is not implemented");
625
+ let rpcPromises = /* @__PURE__ */ new Map();
626
+ return {
627
+ ...transport,
628
+ connect({ onMessage, onDisconnection }) {
629
+ return transport.connect({
630
+ onMessage(payload) {
631
+ if (payload.type === "custom" && payload.event === "vite:invoke") {
632
+ let data = payload.data;
633
+ if (data.id.startsWith("response:")) {
634
+ let invokeId = data.id.slice(9), promise = rpcPromises.get(invokeId);
635
+ if (!promise) return;
636
+ promise.timeoutId && clearTimeout(promise.timeoutId), rpcPromises.delete(invokeId);
637
+ let { error, result } = data.data;
638
+ error ? promise.reject(error) : promise.resolve(result);
639
+ return;
640
+ }
641
+ }
642
+ onMessage(payload);
643
+ },
644
+ onDisconnection
645
+ });
646
+ },
647
+ disconnect() {
648
+ return rpcPromises.forEach((promise) => {
649
+ promise.reject(/* @__PURE__ */ Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
650
+ }), rpcPromises.clear(), transport.disconnect?.();
651
+ },
652
+ send(data) {
653
+ return transport.send(data);
654
+ },
655
+ async invoke(name, data) {
656
+ let promiseId = nanoid(), wrappedData = {
657
+ type: "custom",
658
+ event: "vite:invoke",
659
+ data: {
660
+ name,
661
+ id: `send:${promiseId}`,
662
+ data
663
+ }
664
+ }, sendPromise = transport.send(wrappedData), { promise, resolve: resolve$1, reject } = promiseWithResolvers(), timeout = transport.timeout ?? 6e4, timeoutId;
665
+ timeout > 0 && (timeoutId = setTimeout(() => {
666
+ rpcPromises.delete(promiseId), reject(/* @__PURE__ */ Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
667
+ }, timeout), timeoutId?.unref?.()), rpcPromises.set(promiseId, {
668
+ resolve: resolve$1,
669
+ reject,
670
+ name,
671
+ timeoutId
672
+ }), sendPromise && sendPromise.catch((err) => {
673
+ clearTimeout(timeoutId), rpcPromises.delete(promiseId), reject(err);
674
+ });
675
+ try {
676
+ return await promise;
677
+ } catch (err) {
678
+ throw reviveInvokeError(err);
679
+ }
680
+ }
681
+ };
682
+ }, normalizeModuleRunnerTransport = (transport) => {
683
+ let invokeableTransport = createInvokeableTransport(transport), isConnected = !invokeableTransport.connect, connectingPromise;
684
+ return {
685
+ ...transport,
686
+ ...invokeableTransport.connect ? { async connect(onMessage) {
687
+ if (isConnected) return;
688
+ if (connectingPromise) {
689
+ await connectingPromise;
690
+ return;
691
+ }
692
+ let maybePromise = invokeableTransport.connect({
693
+ onMessage: onMessage ?? (() => {}),
694
+ onDisconnection() {
695
+ isConnected = !1;
696
+ }
697
+ });
698
+ maybePromise && (connectingPromise = maybePromise, await connectingPromise, connectingPromise = void 0), isConnected = !0;
699
+ } } : {},
700
+ ...invokeableTransport.disconnect ? { async disconnect() {
701
+ isConnected && (connectingPromise && await connectingPromise, isConnected = !1, await invokeableTransport.disconnect());
702
+ } } : {},
703
+ async send(data) {
704
+ if (invokeableTransport.send) {
705
+ if (!isConnected) if (connectingPromise) await connectingPromise;
706
+ else throw Error("send was called before connect");
707
+ await invokeableTransport.send(data);
708
+ }
709
+ },
710
+ async invoke(name, data) {
711
+ if (!isConnected) if (connectingPromise) await connectingPromise;
712
+ else throw Error("invoke was called before connect");
713
+ return invokeableTransport.invoke(name, data);
714
+ }
715
+ };
716
+ }, createWebSocketModuleRunnerTransport = (options) => {
717
+ let pingInterval = options.pingInterval ?? 3e4, ws, pingIntervalId;
718
+ return {
719
+ async connect({ onMessage, onDisconnection }) {
720
+ let socket = options.createConnection();
721
+ socket.addEventListener("message", async ({ data }) => {
722
+ onMessage(JSON.parse(data));
723
+ });
724
+ let isOpened = socket.readyState === socket.OPEN;
725
+ isOpened || await new Promise((resolve$1, reject) => {
726
+ socket.addEventListener("open", () => {
727
+ isOpened = !0, resolve$1();
728
+ }, { once: !0 }), socket.addEventListener("close", async () => {
729
+ if (!isOpened) {
730
+ reject(/* @__PURE__ */ Error("WebSocket closed without opened."));
731
+ return;
732
+ }
733
+ onMessage({
734
+ type: "custom",
735
+ event: "vite:ws:disconnect",
736
+ data: { webSocket: socket }
737
+ }), onDisconnection();
738
+ });
739
+ }), onMessage({
740
+ type: "custom",
741
+ event: "vite:ws:connect",
742
+ data: { webSocket: socket }
743
+ }), ws = socket, pingIntervalId = setInterval(() => {
744
+ socket.readyState === socket.OPEN && socket.send(JSON.stringify({ type: "ping" }));
745
+ }, pingInterval);
746
+ },
747
+ disconnect() {
748
+ clearInterval(pingIntervalId), ws?.close();
749
+ },
750
+ send(data) {
751
+ ws.send(JSON.stringify(data));
752
+ }
753
+ };
754
+ }, ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrExportNameKey = "__vite_ssr_exportName__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {}, silentConsole = {
755
+ debug: noop,
756
+ error: noop
757
+ }, hmrLogger = {
758
+ debug: (...msg) => console.log("[vite]", ...msg),
759
+ error: (error) => console.log("[vite]", error)
760
+ };
761
+ function createHMRHandler(handler) {
762
+ let queue = new Queue();
763
+ return (payload) => queue.enqueue(() => handler(payload));
764
+ }
765
+ var Queue = class {
766
+ queue = [];
767
+ pending = !1;
768
+ enqueue(promise) {
769
+ return new Promise((resolve$1, reject) => {
770
+ this.queue.push({
771
+ promise,
772
+ resolve: resolve$1,
773
+ reject
774
+ }), this.dequeue();
775
+ });
776
+ }
777
+ dequeue() {
778
+ if (this.pending) return !1;
779
+ let item = this.queue.shift();
780
+ return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
781
+ this.pending = !1, this.dequeue();
782
+ }), !0) : !1;
783
+ }
784
+ };
785
+ function createHMRHandlerForRunner(runner) {
786
+ return createHMRHandler(async (payload) => {
787
+ let hmrClient = runner.hmrClient;
788
+ if (!(!hmrClient || runner.isClosed())) switch (payload.type) {
789
+ case "connected":
790
+ hmrClient.logger.debug("connected.");
791
+ break;
792
+ case "update":
793
+ await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
794
+ if (update.type === "js-update") return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
795
+ hmrClient.logger.error("css hmr is not supported in runner mode.");
796
+ })), await hmrClient.notifyListeners("vite:afterUpdate", payload);
797
+ break;
798
+ case "custom":
799
+ await hmrClient.notifyListeners(payload.event, payload.data);
800
+ break;
801
+ case "full-reload": {
802
+ let { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
803
+ if (!clearEntrypointUrls.size) break;
804
+ hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
805
+ for (let url of clearEntrypointUrls) try {
806
+ await runner.import(url);
807
+ } catch (err) {
808
+ err.code !== ERR_OUTDATED_OPTIMIZED_DEP && hmrClient.logger.error(`An error happened during full reload\n${err.message}\n${err.stack}`);
809
+ }
810
+ break;
811
+ }
812
+ case "prune":
813
+ await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
814
+ break;
815
+ case "error": {
816
+ await hmrClient.notifyListeners("vite:error", payload);
817
+ let err = payload.err;
818
+ hmrClient.logger.error(`Internal Server Error\n${err.message}\n${err.stack}`);
819
+ break;
820
+ }
821
+ case "ping": break;
822
+ default: return payload;
823
+ }
824
+ });
825
+ }
826
+ function getModulesByFile(runner, file) {
827
+ let nodes = runner.evaluatedModules.getModulesByFile(file);
828
+ return nodes ? [...nodes].map((node) => node.id) : [];
829
+ }
830
+ function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
831
+ for (let moduleId of modules) {
832
+ if (visited.has(moduleId)) continue;
833
+ visited.add(moduleId);
834
+ let module = runner.evaluatedModules.getModuleById(moduleId);
835
+ if (!module) continue;
836
+ if (!module.importers.size) {
837
+ entrypoints.add(module.url);
838
+ continue;
839
+ }
840
+ for (let importer of module.importers) getModulesEntrypoints(runner, [importer], visited, entrypoints);
841
+ }
842
+ return entrypoints;
843
+ }
844
+ function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
845
+ for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
846
+ return entrypoints;
847
+ }
848
+ const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
849
+ for (let handler of handlers) {
850
+ let result = handler(...args);
851
+ if (result) return result;
852
+ }
853
+ return null;
854
+ }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
855
+ let overridden = !1;
856
+ const originalPrepare = Error.prepareStackTrace;
857
+ function resetInterceptor(runner, options) {
858
+ evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
859
+ }
860
+ function interceptStackTrace(runner, options = {}) {
861
+ return overridden || (Error.prepareStackTrace = prepareStackTrace, overridden = !0), evaluatedModulesCache.add(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runner, options);
862
+ }
863
+ function supportRelativeURL(file, url) {
864
+ if (!file) return url;
865
+ let dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir), protocol = match ? match[0] : "", startPath = dir.slice(protocol.length);
866
+ return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
867
+ }
868
+ function getRunnerSourceMap(position) {
869
+ for (let moduleGraph of evaluatedModulesCache) {
870
+ let sourceMap = moduleGraph.getModuleSourceMapById(position.source);
871
+ if (sourceMap) return {
872
+ url: position.source,
873
+ map: sourceMap,
874
+ vite: !0
875
+ };
876
+ }
877
+ return null;
878
+ }
879
+ function retrieveFile(path) {
880
+ if (path in fileContentsCache) return fileContentsCache[path];
881
+ let content = retrieveFileFromHandlers(path);
882
+ return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
883
+ }
884
+ function retrieveSourceMapURL(source) {
885
+ let fileData = retrieveFile(source);
886
+ if (!fileData) return null;
887
+ let re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm, lastMatch, match;
888
+ for (; match = re.exec(fileData);) lastMatch = match;
889
+ return lastMatch ? lastMatch[1] : null;
890
+ }
891
+ const reSourceMap = /^data:application\/json[^,]+base64,/;
892
+ function retrieveSourceMap(source) {
893
+ let urlAndMap = retrieveSourceMapFromHandlers(source);
894
+ if (urlAndMap) return urlAndMap;
895
+ let sourceMappingURL = retrieveSourceMapURL(source);
896
+ if (!sourceMappingURL) return null;
897
+ let sourceMapData;
898
+ if (reSourceMap.test(sourceMappingURL)) {
899
+ let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
900
+ sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
901
+ } else sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
902
+ return sourceMapData ? {
903
+ url: sourceMappingURL,
904
+ map: sourceMapData
905
+ } : null;
906
+ }
907
+ function mapSourcePosition(position) {
908
+ if (!position.source) return position;
909
+ let sourceMap = getRunnerSourceMap(position);
910
+ if (sourceMap ||= sourceMapCache[position.source], !sourceMap) {
911
+ let urlAndMap = retrieveSourceMap(position.source);
912
+ if (urlAndMap && urlAndMap.map) {
913
+ let url = urlAndMap.url;
914
+ sourceMap = sourceMapCache[position.source] = {
915
+ url,
916
+ map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
917
+ };
918
+ let contents = sourceMap.map?.map.sourcesContent;
919
+ sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
920
+ let content = contents[i];
921
+ if (content && source && url) {
922
+ let contentUrl = supportRelativeURL(url, source);
923
+ fileContentsCache[contentUrl] = content;
924
+ }
925
+ });
926
+ } else sourceMap = sourceMapCache[position.source] = {
927
+ url: null,
928
+ map: null
929
+ };
930
+ }
931
+ if (sourceMap.map && sourceMap.url) {
932
+ let originalPosition = getOriginalPosition(sourceMap.map, position);
933
+ if (originalPosition && originalPosition.source != null) return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
934
+ }
935
+ return position;
936
+ }
937
+ function mapEvalOrigin(origin) {
938
+ let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
939
+ if (match) {
940
+ let position = mapSourcePosition({
941
+ name: null,
942
+ source: match[2],
943
+ line: +match[3],
944
+ column: match[4] - 1
945
+ });
946
+ return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
947
+ }
948
+ return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
949
+ }
950
+ function CallSiteToString() {
951
+ let fileName, fileLocation = "";
952
+ if (this.isNative()) fileLocation = "native";
953
+ else {
954
+ fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
955
+ let lineNumber = this.getLineNumber();
956
+ if (lineNumber != null) {
957
+ fileLocation += `:${lineNumber}`;
958
+ let columnNumber = this.getColumnNumber();
959
+ columnNumber && (fileLocation += `:${columnNumber}`);
960
+ }
961
+ }
962
+ let line = "", functionName = this.getFunctionName(), addSuffix = !0, isConstructor = this.isConstructor();
963
+ if (!(this.isToplevel() || isConstructor)) {
964
+ let typeName = this.getTypeName();
965
+ typeName === "[object Object]" && (typeName = "null");
966
+ let methodName = this.getMethodName();
967
+ functionName ? (typeName && functionName.indexOf(typeName) !== 0 && (line += `${typeName}.`), line += functionName, methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1 && (line += ` [as ${methodName}]`)) : line += `${typeName}.${methodName || "<anonymous>"}`;
968
+ } else isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
969
+ return addSuffix && (line += ` (${fileLocation})`), line;
970
+ }
971
+ function cloneCallSite(frame) {
972
+ let object = {};
973
+ return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
974
+ let key = name;
975
+ object[key] = /^(?:is|get)/.test(name) ? function() {
976
+ return frame[key].call(frame);
977
+ } : frame[key];
978
+ }), object.toString = CallSiteToString, object;
979
+ }
980
+ function wrapCallSite(frame, state) {
981
+ if (state === void 0 && (state = {
982
+ nextPosition: null,
983
+ curPosition: null
984
+ }), frame.isNative()) return state.curPosition = null, frame;
985
+ let source = frame.getFileName() || frame.getScriptNameOrSourceURL();
986
+ if (source) {
987
+ let line = frame.getLineNumber(), column = frame.getColumnNumber() - 1, headerLength = 62;
988
+ line === 1 && column > headerLength && !frame.isEval() && (column -= headerLength);
989
+ let position = mapSourcePosition({
990
+ name: null,
991
+ source,
992
+ line,
993
+ column
994
+ });
995
+ state.curPosition = position, frame = cloneCallSite(frame);
996
+ let originalFunctionName = frame.getFunctionName;
997
+ return frame.getFunctionName = function() {
998
+ let name = (() => state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName())();
999
+ return name === "eval" && "_vite" in position ? null : name;
1000
+ }, frame.getFileName = function() {
1001
+ return position.source ?? null;
1002
+ }, frame.getLineNumber = function() {
1003
+ return position.line;
1004
+ }, frame.getColumnNumber = function() {
1005
+ return position.column + 1;
1006
+ }, frame.getScriptNameOrSourceURL = function() {
1007
+ return position.source;
1008
+ }, frame;
1009
+ }
1010
+ let origin = frame.isEval() && frame.getEvalOrigin();
1011
+ return origin ? (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
1012
+ return origin || void 0;
1013
+ }, frame) : frame;
1014
+ }
1015
+ function prepareStackTrace(error, stack) {
1016
+ let errorString = `${error.name || "Error"}: ${error.message || ""}`, state = {
1017
+ nextPosition: null,
1018
+ curPosition: null
1019
+ }, processedStack = [];
1020
+ for (let i = stack.length - 1; i >= 0; i--) processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
1021
+ return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
1022
+ }
1023
+ function enableSourceMapSupport(runner) {
1024
+ if (runner.options.sourcemapInterceptor === "node") {
1025
+ if (typeof process > "u") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because global \"process\" variable is not available.");
1026
+ if (typeof process.setSourceMapsEnabled != "function") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because \"process.setSourceMapsEnabled\" function is not available. Please use Node >= 16.6.0.");
1027
+ let isEnabledAlready = process.sourceMapsEnabled ?? !1;
1028
+ return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
1029
+ }
1030
+ return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
1031
+ }
1032
+ var ESModulesEvaluator = class {
1033
+ startOffset = getAsyncFunctionDeclarationPaddingLineCount();
1034
+ async runInlinedModule(context, code) {
1035
+ await new AsyncFunction(ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, "\"use strict\";" + code)(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey], context[ssrExportNameKey]), Object.seal(context[ssrModuleExportsKey]);
1036
+ }
1037
+ runExternalModule(filepath) {
1038
+ return import(filepath);
1039
+ }
1040
+ }, ModuleRunner = class {
1041
+ evaluatedModules;
1042
+ hmrClient;
1043
+ envProxy = new Proxy({}, { get(_, p) {
1044
+ throw Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
1045
+ } });
1046
+ transport;
1047
+ resetSourceMapSupport;
1048
+ concurrentModuleNodePromises = /* @__PURE__ */ new Map();
1049
+ closed = !1;
1050
+ constructor(options, evaluator = new ESModulesEvaluator(), debug) {
1051
+ if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
1052
+ let optionsHmr = options.hmr ?? !0;
1053
+ if (this.hmrClient = new HMRClient(optionsHmr === !0 || optionsHmr.logger === void 0 ? hmrLogger : optionsHmr.logger === !1 ? silentConsole : optionsHmr.logger, this.transport, ({ acceptedPath }) => this.import(acceptedPath)), !this.transport.connect) throw Error("HMR is not supported by this runner transport, but `hmr` option was set to true");
1054
+ this.transport.connect(createHMRHandlerForRunner(this));
1055
+ } else this.transport.connect?.();
1056
+ options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
1057
+ }
1058
+ /**
1059
+ * URL to execute. Accepts file path, server path or id relative to the root.
1060
+ */
1061
+ async import(url) {
1062
+ let fetchedModule = await this.cachedModule(url);
1063
+ return await this.cachedRequest(url, fetchedModule);
1064
+ }
1065
+ /**
1066
+ * Clear all caches including HMR listeners.
1067
+ */
1068
+ clearCache() {
1069
+ this.evaluatedModules.clear(), this.hmrClient?.clear();
1070
+ }
1071
+ /**
1072
+ * Clears all caches, removes all HMR listeners, and resets source map support.
1073
+ * This method doesn't stop the HMR connection.
1074
+ */
1075
+ async close() {
1076
+ this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
1077
+ }
1078
+ /**
1079
+ * Returns `true` if the runtime has been closed by calling `close()` method.
1080
+ */
1081
+ isClosed() {
1082
+ return this.closed;
1083
+ }
1084
+ processImport(exports, fetchResult, metadata) {
1085
+ if (!("externalize" in fetchResult)) return exports;
1086
+ let { url, type } = fetchResult;
1087
+ return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
1088
+ }
1089
+ isCircularModule(mod) {
1090
+ for (let importedFile of mod.imports) if (mod.importers.has(importedFile)) return !0;
1091
+ return !1;
1092
+ }
1093
+ isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
1094
+ for (let importer of importers) {
1095
+ if (visited.has(importer)) continue;
1096
+ if (visited.add(importer), importer === moduleUrl) return !0;
1097
+ let mod = this.evaluatedModules.getModuleById(importer);
1098
+ if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited)) return !0;
1099
+ }
1100
+ return !1;
1101
+ }
1102
+ async cachedRequest(url, mod, callstack = [], metadata) {
1103
+ let meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
1104
+ if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports) return this.processImport(mod.exports, meta, metadata);
1105
+ let debugTimer;
1106
+ this.debug && (debugTimer = setTimeout(() => {
1107
+ let getStack = () => `stack:\n${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join("\n")}`;
1108
+ this.debug(`[module runner] module ${moduleId} takes over 2s to load.\n${getStack()}`);
1109
+ }, 2e3));
1110
+ try {
1111
+ if (mod.promise) return this.processImport(await mod.promise, meta, metadata);
1112
+ let promise = this.directRequest(url, mod, callstack);
1113
+ return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
1114
+ } finally {
1115
+ mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
1116
+ }
1117
+ }
1118
+ async cachedModule(url, importer) {
1119
+ let cached = this.concurrentModuleNodePromises.get(url);
1120
+ if (cached) this.debug?.("[module runner] using cached module info for", url);
1121
+ else {
1122
+ let cachedModule = this.evaluatedModules.getModuleByUrl(url);
1123
+ cached = this.getModuleInformation(url, importer, cachedModule).finally(() => {
1124
+ this.concurrentModuleNodePromises.delete(url);
1125
+ }), this.concurrentModuleNodePromises.set(url, cached);
1126
+ }
1127
+ return cached;
1128
+ }
1129
+ async getModuleInformation(url, importer, cachedModule) {
1130
+ if (this.closed) throw Error("Vite module runner has been closed.");
1131
+ this.debug?.("[module runner] fetching", url);
1132
+ let isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = url.startsWith("data:") ? {
1133
+ externalize: url,
1134
+ type: "builtin"
1135
+ } : await this.transport.invoke("fetchModule", [
1136
+ url,
1137
+ importer,
1138
+ {
1139
+ cached: isCached,
1140
+ startOffset: this.evaluator.startOffset
1141
+ }
1142
+ ]);
1143
+ if ("cache" in fetchedModule) {
1144
+ if (!cachedModule || !cachedModule.meta) throw Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
1145
+ return cachedModule;
1146
+ }
1147
+ let moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
1148
+ return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
1149
+ }
1150
+ async directRequest(url, mod, _callstack) {
1151
+ let fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
1152
+ let importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
1153
+ return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
1154
+ }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
1155
+ if ("externalize" in fetchResult) {
1156
+ let { externalize } = fetchResult;
1157
+ this.debug?.("[module runner] externalizing", externalize);
1158
+ let exports$1 = await this.evaluator.runExternalModule(externalize);
1159
+ return mod.exports = exports$1, exports$1;
1160
+ }
1161
+ let { code, file } = fetchResult;
1162
+ if (code == null) {
1163
+ let importer = callstack[callstack.length - 2];
1164
+ throw Error(`[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`);
1165
+ }
1166
+ let modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname$1 = posixDirname(modulePath), meta = {
1167
+ filename: isWindows ? toWindowsPath(filename) : filename,
1168
+ dirname: isWindows ? toWindowsPath(dirname$1) : dirname$1,
1169
+ url: href,
1170
+ env: this.envProxy,
1171
+ resolve(_id, _parent) {
1172
+ throw Error("[module runner] \"import.meta.resolve\" is not supported.");
1173
+ },
1174
+ glob() {
1175
+ throw Error("[module runner] \"import.meta.glob\" is statically replaced during file transformation. Make sure to reference it by the full name.");
1176
+ }
1177
+ }, exports = Object.create(null);
1178
+ Object.defineProperty(exports, Symbol.toStringTag, {
1179
+ value: "Module",
1180
+ enumerable: !1,
1181
+ configurable: !1
1182
+ }), mod.exports = exports;
1183
+ let hotContext;
1184
+ this.hmrClient && Object.defineProperty(meta, "hot", {
1185
+ enumerable: !0,
1186
+ get: () => {
1187
+ if (!this.hmrClient) throw Error("[module runner] HMR client was closed.");
1188
+ return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
1189
+ },
1190
+ set: (value) => {
1191
+ hotContext = value;
1192
+ }
1193
+ });
1194
+ let context = {
1195
+ [ssrImportKey]: request,
1196
+ [ssrDynamicImportKey]: dynamicRequest,
1197
+ [ssrModuleExportsKey]: exports,
1198
+ [ssrExportAllKey]: (obj) => exportAll(exports, obj),
1199
+ [ssrExportNameKey]: (name, getter) => Object.defineProperty(exports, name, {
1200
+ enumerable: !0,
1201
+ configurable: !0,
1202
+ get: getter
1203
+ }),
1204
+ [ssrImportMetaKey]: meta
1205
+ };
1206
+ return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
1207
+ }
1208
+ };
1209
+ function exportAll(exports, sourceModule) {
1210
+ if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
1211
+ for (let key in sourceModule) if (key !== "default" && key !== "__esModule" && !(key in exports)) try {
1212
+ Object.defineProperty(exports, key, {
1213
+ enumerable: !0,
1214
+ configurable: !0,
1215
+ get: () => sourceModule[key]
1216
+ });
1217
+ } catch {}
1218
+ }
1219
+ }
1220
+
1221
+ //#endregion
1222
+ //#region src/plugins/utils.ts
1223
+ function createPlugin(name, pluginFactory) {
1224
+ return (ctx) => {
1225
+ return {
1226
+ name: `vite-plugin-cloudflare:${name}`,
1227
+ sharedDuringBuild: true,
1228
+ ...pluginFactory(ctx)
1229
+ };
1230
+ };
1231
+ }
1232
+
1233
+ //#endregion
1234
+ //#region src/plugins/virtual-modules.ts
1235
+ const virtualPrefix = "virtual:cloudflare/";
1236
+ const VIRTUAL_USER_ENTRY = `${virtualPrefix}user-entry`;
1237
+ const VIRTUAL_WORKER_ENTRY = `${virtualPrefix}worker-entry`;
1238
+ const VIRTUAL_CLIENT_FALLBACK_ENTRY = `${virtualPrefix}client-fallback-entry`;
1239
+ /**
1240
+ * Plugin to provide virtual modules
1241
+ */
1242
+ const virtualModulesPlugin = createPlugin("virtual-modules", (ctx) => {
1243
+ return {
1244
+ applyToEnvironment(environment) {
1245
+ return ctx.getWorkerConfig(environment.name) !== void 0;
1246
+ },
1247
+ resolveId(source) {
1248
+ if (source === VIRTUAL_WORKER_ENTRY) return `\0${VIRTUAL_WORKER_ENTRY}`;
1249
+ if (source === VIRTUAL_USER_ENTRY) {
1250
+ const workerConfig = ctx.getWorkerConfig(this.environment.name);
1251
+ if (!workerConfig) return;
1252
+ return this.resolve(workerConfig.main);
1253
+ }
1254
+ },
1255
+ load(id) {
1256
+ if (id === `\0${VIRTUAL_WORKER_ENTRY}`) {
1257
+ const nodeJsCompat = ctx.getNodeJsCompat(this.environment.name);
1258
+ return `
1259
+ ${nodeJsCompat ? nodeJsCompat.injectGlobalCode() : ""}
1260
+ import * as mod from "${VIRTUAL_USER_ENTRY}";
1261
+ export * from "${VIRTUAL_USER_ENTRY}";
1262
+ export default mod.default ?? {};
1263
+ if (import.meta.hot) {
1264
+ import.meta.hot.accept();
1265
+ }
1266
+ `;
1267
+ }
1268
+ }
1269
+ };
1270
+ });
1271
+ /**
1272
+ * Plugin to provide a virtual fallback entry file for the `client` environment.
1273
+ * This is used as the entry file for the client build when only the `public` directory is present.
1274
+ */
1275
+ const virtualClientFallbackPlugin = createPlugin("virtual-client-fallback", () => {
1276
+ return {
1277
+ applyToEnvironment(environment) {
1278
+ return environment.name === "client";
1279
+ },
1280
+ resolveId(source) {
1281
+ if (source === VIRTUAL_CLIENT_FALLBACK_ENTRY) return `\0${VIRTUAL_CLIENT_FALLBACK_ENTRY}`;
1282
+ },
1283
+ load(id) {
1284
+ if (id === `\0${VIRTUAL_CLIENT_FALLBACK_ENTRY}`) return ``;
1285
+ }
1286
+ };
1287
+ });
1288
+
1289
+ //#endregion
1290
+ //#region src/workers/runner-worker/module-runner.ts
1291
+ /**
1292
+ * Custom `ModuleRunner`.
1293
+ * The `cachedModule` method is overriden to ensure compatibility with the Workers runtime.
1294
+ */
1295
+ var CustomModuleRunner = class extends ModuleRunner {
1296
+ #env;
1297
+ constructor(options, evaluator, env) {
1298
+ super(options, evaluator);
1299
+ this.#env = env;
1300
+ }
1301
+ async cachedModule(url, importer) {
1302
+ const moduleId = await this.#env.__VITE_RUNNER_OBJECT__.get("singleton").getFetchedModuleId(url, importer);
1303
+ const module = this.evaluatedModules.getModuleById(moduleId);
1304
+ if (!module) throw new Error(`Module "${moduleId}" is undefined`);
1305
+ return module;
1306
+ }
1307
+ };
1308
+ /** Module runner instance */
1309
+ let moduleRunner;
1310
+ /**
1311
+ * Durable Object that creates the module runner and handles WebSocket communication with the Vite dev server.
1312
+ */
1313
+ var __VITE_RUNNER_OBJECT__ = class extends DurableObject {
1314
+ /** WebSocket connection to the Vite dev server */
1315
+ #webSocket;
1316
+ #concurrentModuleNodePromises = /* @__PURE__ */ new Map();
1317
+ /**
1318
+ * Handles fetch requests to initialize the module runner.
1319
+ * Creates a WebSocket pair for communication with the Vite dev server and initializes the ModuleRunner.
1320
+ * @param request - The incoming fetch request
1321
+ * @returns Response with WebSocket
1322
+ * @throws Error if the path is invalid or the module runner is already initialized
1323
+ */
1324
+ async fetch(request) {
1325
+ const { pathname } = new URL(request.url);
1326
+ if (pathname !== INIT_PATH) throw new Error(`__VITE_RUNNER_OBJECT__ received invalid pathname: ${pathname}`);
1327
+ if (moduleRunner) throw new Error(`Module runner already initialized`);
1328
+ const { 0: client, 1: server } = new WebSocketPair();
1329
+ server.accept();
1330
+ this.#webSocket = server;
1331
+ moduleRunner = await createModuleRunner(this.env, this.#webSocket);
1332
+ return new Response(null, {
1333
+ status: 101,
1334
+ webSocket: client
1335
+ });
1336
+ }
1337
+ /**
1338
+ * Sends data to the Vite dev server via the WebSocket.
1339
+ * @param data - The data to send as a string
1340
+ * @throws Error if the WebSocket is not initialized
1341
+ */
1342
+ send(data) {
1343
+ if (!this.#webSocket) throw new Error(`Module runner WebSocket not initialized`);
1344
+ this.#webSocket.send(data);
1345
+ }
1346
+ /**
1347
+ * Based on the implementation of `cachedModule` from Vite's `ModuleRunner`.
1348
+ * Running this in the DO enables us to share promises across invocations.
1349
+ * @param url - The module URL
1350
+ * @param importer - The module's importer
1351
+ * @returns The ID of the fetched module
1352
+ */
1353
+ async getFetchedModuleId(url, importer) {
1354
+ if (!moduleRunner) throw new Error(`Module runner not initialized`);
1355
+ let cached = this.#concurrentModuleNodePromises.get(url);
1356
+ if (!cached) {
1357
+ const cachedModule = moduleRunner.evaluatedModules.getModuleByUrl(url);
1358
+ cached = moduleRunner.getModuleInformation(url, importer, cachedModule).finally(() => {
1359
+ this.#concurrentModuleNodePromises.delete(url);
1360
+ });
1361
+ this.#concurrentModuleNodePromises.set(url, cached);
1362
+ } else moduleRunner.debug?.("[module runner] using cached module info for", url);
1363
+ return (await cached).id;
1364
+ }
1365
+ };
1366
+ /**
1367
+ * Creates a new module runner instance with a WebSocket transport.
1368
+ * @param env - The wrapper env
1369
+ * @param webSocket - WebSocket connection for communication with Vite dev server
1370
+ * @returns Configured module runner instance
1371
+ */
1372
+ async function createModuleRunner(env, webSocket) {
1373
+ return new CustomModuleRunner({
1374
+ sourcemapInterceptor: "prepareStackTrace",
1375
+ transport: {
1376
+ connect({ onMessage }) {
1377
+ webSocket.addEventListener("message", async ({ data }) => {
1378
+ onMessage(JSON.parse(data.toString()));
1379
+ });
1380
+ onMessage({
1381
+ type: "custom",
1382
+ event: "vite:ws:connect",
1383
+ data: { webSocket }
1384
+ });
1385
+ },
1386
+ disconnect() {
1387
+ webSocket.close();
1388
+ },
1389
+ send(data) {
1390
+ env.__VITE_RUNNER_OBJECT__.get("singleton").send(JSON.stringify(data));
1391
+ },
1392
+ async invoke(data) {
1393
+ return await (await env.__VITE_INVOKE_MODULE__.fetch(new Request(UNKNOWN_HOST, {
1394
+ method: "POST",
1395
+ body: JSON.stringify(data)
1396
+ }))).json();
1397
+ }
1398
+ },
1399
+ hmr: true
1400
+ }, {
1401
+ async runInlinedModule(context, transformed, module) {
1402
+ const code = `"use strict";async (${Object.keys(context).join(",")})=>{${transformed}}`;
1403
+ await env.__VITE_UNSAFE_EVAL__.eval(code, module.id)(...Object.values(context));
1404
+ Object.seal(context[ssrModuleExportsKey]);
1405
+ },
1406
+ async runExternalModule(filepath) {
1407
+ if (filepath === "cloudflare:workers") {
1408
+ const originalCloudflareWorkersModule = await import("cloudflare:workers");
1409
+ return Object.seal({
1410
+ ...originalCloudflareWorkersModule,
1411
+ env: stripInternalEnv(originalCloudflareWorkersModule.env)
1412
+ });
1413
+ }
1414
+ return import(filepath);
1415
+ }
1416
+ }, env);
1417
+ }
1418
+ /**
1419
+ * Retrieves a specific export from a Worker entry module using the module runner.
1420
+ * @param workerEntryPath - Path to the Worker entry module
1421
+ * @param exportName - Name of the export to retrieve
1422
+ * @returns The requested export value
1423
+ * @throws Error if the module runner has not been initialized or the module does not define the requested export
1424
+ */
1425
+ async function getWorkerEntryExport(workerEntryPath$1, exportName) {
1426
+ if (!moduleRunner) throw new Error(`Module runner not initialized`);
1427
+ const module = await moduleRunner.import(VIRTUAL_WORKER_ENTRY);
1428
+ const exportValue = typeof module === "object" && module !== null && exportName in module && module[exportName];
1429
+ if (!exportValue) throw new Error(`"${workerEntryPath$1}" does not define a "${exportName}" export.`);
1430
+ return exportValue;
1431
+ }
1432
+
1433
+ //#endregion
1434
+ //#region src/workers/runner-worker/index.ts
1435
+ /** Keys that should be ignored during RPC property access */
1436
+ const IGNORED_KEYS = ["self", "tailStream"];
1437
+ /** Available methods for `WorkerEntrypoint` class */
1438
+ const WORKER_ENTRYPOINT_KEYS = [
1439
+ "fetch",
1440
+ "queue",
1441
+ "tail",
1442
+ "test",
1443
+ "trace",
1444
+ "scheduled"
1445
+ ];
1446
+ /** Available methods for `DurableObject` class */
1447
+ const DURABLE_OBJECT_KEYS = [
1448
+ "alarm",
1449
+ "fetch",
1450
+ "webSocketClose",
1451
+ "webSocketError",
1452
+ "webSocketMessage"
1453
+ ];
1454
+ /** Available methods for `WorkflowEntrypoint` classes */
1455
+ const WORKFLOW_ENTRYPOINT_KEYS = ["run"];
1456
+ /** The path to the Worker entry file. We store it in the module scope so that it is easily accessible in error messages etc.. */
1457
+ let workerEntryPath = "";
1458
+ let isEntryWorker = false;
1459
+ /**
1460
+ * Creates a callable thenable that is used to access the properties of an RPC target.
1461
+ * It can be both awaited and invoked as a function.
1462
+ * This enables RPC properties to be used both as promises and callable functions.
1463
+ * @param key - The property key name used for error messages
1464
+ * @param property - The promise that resolves to the property value
1465
+ * @returns A callable thenable that implements both Promise and function interfaces
1466
+ */
1467
+ function getRpcPropertyCallableThenable(key, property) {
1468
+ const fn = async function(...args) {
1469
+ const maybeFn = await property;
1470
+ if (typeof maybeFn !== "function") throw new TypeError(`"${key}" is not a function.`);
1471
+ return maybeFn(...args);
1472
+ };
1473
+ fn.then = (onFulfilled, onRejected) => property.then(onFulfilled, onRejected);
1474
+ fn.catch = (onRejected) => property.catch(onRejected);
1475
+ fn.finally = (onFinally) => property.finally(onFinally);
1476
+ return fn;
1477
+ }
1478
+ /**
1479
+ * Retrieves an RPC property from a constructor prototype, ensuring it exists on the prototype rather than the instance to maintain RPC compatibility.
1480
+ * @param ctor - The constructor function (`WorkerEntrypoint` or `DurableObject`)
1481
+ * @param instance - The instance to bind methods to
1482
+ * @param key - The property key to retrieve
1483
+ * @returns The property value from the prototype
1484
+ * @throws TypeError if the property doesn't exist on the prototype
1485
+ */
1486
+ function getRpcProperty(ctor, instance, key) {
1487
+ if (!Reflect.has(ctor.prototype, key)) {
1488
+ if (Reflect.has(instance, key)) throw new TypeError([
1489
+ `The RPC receiver's prototype does not implement "${key}", but the receiver instance does.`,
1490
+ "Only properties and methods defined on the prototype can be accessed over RPC.",
1491
+ `Ensure properties are declared as \`get ${key}() { ... }\` instead of \`${key} = ...\`,`,
1492
+ `and methods are declared as \`${key}() { ... }\` instead of \`${key} = () => { ... }\`.`
1493
+ ].join("\n"));
1494
+ throw new TypeError(`The RPC receiver does not implement "${key}".`);
1495
+ }
1496
+ return Reflect.get(ctor.prototype, key, instance);
1497
+ }
1498
+ /**
1499
+ * Retrieves an RPC property from a `WorkerEntrypoint` export, creating an instance and returning the bound method or property value.
1500
+ * @param exportName - The name of the `WorkerEntrypoint` export
1501
+ * @param key - The property key to access on the `WorkerEntrypoint` instance
1502
+ * @returns The property value, with methods bound to the instance
1503
+ * @throws TypeError if the export is not a `WorkerEntrypoint` subclass
1504
+ */
1505
+ async function getWorkerEntrypointRpcProperty(exportName, key) {
1506
+ const ctor = await getWorkerEntryExport(workerEntryPath, exportName);
1507
+ const userEnv = stripInternalEnv(this.env);
1508
+ const expectedWorkerEntrypointMessage = `Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`WorkerEntrypoint\` for RPC.`;
1509
+ if (typeof ctor !== "function") throw new TypeError(expectedWorkerEntrypointMessage);
1510
+ const instance = new ctor(this.ctx, userEnv);
1511
+ if (!(instance instanceof WorkerEntrypoint)) throw new TypeError(expectedWorkerEntrypointMessage);
1512
+ const value = getRpcProperty(ctor, instance, key);
1513
+ if (typeof value === "function") return value.bind(instance);
1514
+ return value;
1515
+ }
1516
+ /**
1517
+ * Creates a proxy wrapper for `WorkerEntrypoint` classes that enables RPC functionality.
1518
+ * The wrapper intercepts property access and delegates to the user code, handling both direct method calls and RPC property access.
1519
+ * @param exportName - The name of the `WorkerEntrypoint` export to wrap
1520
+ * @returns A `WorkerEntrypoint` constructor that acts as a proxy to the user code
1521
+ */
1522
+ function createWorkerEntrypointWrapper(exportName) {
1523
+ class Wrapper extends WorkerEntrypoint {
1524
+ constructor(ctx, env) {
1525
+ super(ctx, env);
1526
+ return new Proxy(this, { get(target, key, receiver) {
1527
+ const value = Reflect.get(target, key, receiver);
1528
+ if (value !== void 0) return value;
1529
+ if (typeof key === "symbol" || IGNORED_KEYS.includes(key) || DURABLE_OBJECT_KEYS.includes(key)) return;
1530
+ return getRpcPropertyCallableThenable(key, getWorkerEntrypointRpcProperty.call(receiver, exportName, key));
1531
+ } });
1532
+ }
1533
+ }
1534
+ for (const key of WORKER_ENTRYPOINT_KEYS) Wrapper.prototype[key] = async function(arg) {
1535
+ return maybeCaptureError({
1536
+ isEntryWorker,
1537
+ exportName,
1538
+ key
1539
+ }, async () => {
1540
+ if (key === "fetch") {
1541
+ const request = arg;
1542
+ if (new URL(request.url).pathname === INIT_PATH) {
1543
+ const workerEntryPathHeader = request.headers.get(WORKER_ENTRY_PATH_HEADER);
1544
+ if (!workerEntryPathHeader) throw new Error(`Unexpected error: "${WORKER_ENTRY_PATH_HEADER}" header not set.`);
1545
+ const isEntryWorkerHeader = request.headers.get(IS_ENTRY_WORKER_HEADER);
1546
+ if (!isEntryWorkerHeader) throw new Error(`Unexpected error: "${IS_ENTRY_WORKER_HEADER}" header not set.`);
1547
+ workerEntryPath = decodeURIComponent(workerEntryPathHeader);
1548
+ isEntryWorker = isEntryWorkerHeader === "true";
1549
+ return this.env.__VITE_RUNNER_OBJECT__.get("singleton").fetch(request);
1550
+ }
1551
+ }
1552
+ const exportValue = await getWorkerEntryExport(workerEntryPath, exportName);
1553
+ const userEnv = stripInternalEnv(this.env);
1554
+ if (typeof exportValue === "object" && exportValue !== null) {
1555
+ const maybeFn = exportValue[key];
1556
+ if (typeof maybeFn !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to define a \`${key}()\` function.`);
1557
+ return maybeFn.call(exportValue, arg, userEnv, this.ctx);
1558
+ } else if (typeof exportValue === "function") {
1559
+ const instance = new exportValue(this.ctx, userEnv);
1560
+ if (!(instance instanceof WorkerEntrypoint)) throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`WorkerEntrypoint\`.`);
1561
+ const maybeFn = instance[key];
1562
+ if (typeof maybeFn !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to define a \`${key}()\` method.`);
1563
+ return maybeFn.call(instance, arg);
1564
+ } else return /* @__PURE__ */ new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be an object or a class.`);
1565
+ });
1566
+ };
1567
+ return Wrapper;
1568
+ }
1569
+ /** Symbol key for storing the `DurableObject` instance */
1570
+ const kInstance = Symbol("kInstance");
1571
+ /** Symbol key for the instance initialization method */
1572
+ const kEnsureInstance = Symbol("kEnsureInstance");
1573
+ /**
1574
+ * Retrieves an RPC property from a `DurableObject` export, ensuring an instance is properly initialized and returning the bound method or property value.
1575
+ * @param exportName - The name of the `DurableObject` export
1576
+ * @param key - The property key to access on the `DurableObject` instance
1577
+ * @returns The property value, with methods bound to the instance
1578
+ * @throws TypeError if the export is not a `DurableObject` subclass
1579
+ */
1580
+ async function getDurableObjectRpcProperty(exportName, key) {
1581
+ const { ctor, instance } = await this[kEnsureInstance]();
1582
+ if (!(instance instanceof DurableObject)) throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`DurableObject\` for RPC.`);
1583
+ const value = getRpcProperty(ctor, instance, key);
1584
+ if (typeof value === "function") return value.bind(instance);
1585
+ return value;
1586
+ }
1587
+ /**
1588
+ * Creates a proxy wrapper for `DurableObject` classes that enables RPC functionality.
1589
+ * The wrapper manages instance lifecycle and delegates method calls to the user code, handling both direct method calls and RPC property access.
1590
+ * @param exportName - The name of the `DurableObject` export to wrap
1591
+ * @returns A `DurableObject` constructor that acts as a proxy to the user code
1592
+ */
1593
+ function createDurableObjectWrapper(exportName) {
1594
+ class Wrapper extends DurableObject {
1595
+ [kInstance];
1596
+ constructor(ctx, env) {
1597
+ super(ctx, env);
1598
+ return new Proxy(this, { get(target, key, receiver) {
1599
+ const value = Reflect.get(target, key, receiver);
1600
+ if (value !== void 0) return value;
1601
+ if (typeof key === "symbol" || IGNORED_KEYS.includes(key) || WORKER_ENTRYPOINT_KEYS.includes(key)) return;
1602
+ return getRpcPropertyCallableThenable(key, getDurableObjectRpcProperty.call(receiver, exportName, key));
1603
+ } });
1604
+ }
1605
+ async [kEnsureInstance]() {
1606
+ const ctor = await getWorkerEntryExport(workerEntryPath, exportName);
1607
+ if (typeof ctor !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`DurableObject\`.`);
1608
+ if (!this[kInstance] || this[kInstance].ctor !== ctor) {
1609
+ const userEnv = stripInternalEnv(this.env);
1610
+ this[kInstance] = {
1611
+ ctor,
1612
+ instance: new ctor(this.ctx, userEnv)
1613
+ };
1614
+ await this.ctx.blockConcurrencyWhile(async () => {});
1615
+ }
1616
+ return this[kInstance];
1617
+ }
1618
+ }
1619
+ for (const key of DURABLE_OBJECT_KEYS) Wrapper.prototype[key] = async function(...args) {
1620
+ const { instance } = await this[kEnsureInstance]();
1621
+ const maybeFn = instance[key];
1622
+ if (typeof maybeFn !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to define a \`${key}()\` function.`);
1623
+ return maybeFn.apply(instance, args);
1624
+ };
1625
+ return Wrapper;
1626
+ }
1627
+ /**
1628
+ * Creates a proxy wrapper for `WorkflowEntrypoint` classes.
1629
+ * The wrapper delegates method calls to the user code.
1630
+ * @param exportName - The name of the `WorkflowEntrypoint` export to wrap
1631
+ * @returns A `WorkflowEntrypoint` constructor that acts as a proxy to the user code
1632
+ */
1633
+ function createWorkflowEntrypointWrapper(exportName) {
1634
+ class Wrapper extends WorkflowEntrypoint {}
1635
+ for (const key of WORKFLOW_ENTRYPOINT_KEYS) Wrapper.prototype[key] = async function(...args) {
1636
+ const ctor = await getWorkerEntryExport(workerEntryPath, exportName);
1637
+ const userEnv = stripInternalEnv(this.env);
1638
+ const instance = new ctor(this.ctx, userEnv);
1639
+ if (!(instance instanceof WorkflowEntrypoint)) throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to be a subclass of \`WorkflowEntrypoint\`.`);
1640
+ const maybeFn = instance[key];
1641
+ if (typeof maybeFn !== "function") throw new TypeError(`Expected "${exportName}" export of "${workerEntryPath}" to define a \`${key}()\` function.`);
1642
+ return maybeFn.apply(instance, args);
1643
+ };
1644
+ return Wrapper;
1645
+ }
1646
+
1647
+ //#endregion
1648
+ export { __VITE_RUNNER_OBJECT__, createDurableObjectWrapper, createWorkerEntrypointWrapper, createWorkflowEntrypointWrapper };