@cloudflare/vite-plugin 1.13.10 → 1.13.11

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