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