source: node_modules/vite/dist/node/module-runner.js

Last change on this file was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

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