vite 6.0.0-alpha.17 → 6.0.0-alpha.19

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.
@@ -51,24 +51,22 @@ function normalizeString(path, allowAboveRoot) {
51
51
  char = "/";
52
52
  }
53
53
  if (char === "/") {
54
- if (!(lastSlash === index - 1 || dots === 1))
55
- if (dots === 2) {
56
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
57
- if (res.length > 2) {
58
- const lastSlashIndex = res.lastIndexOf("/");
59
- lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
60
- continue;
61
- } else if (res.length > 0) {
62
- res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
63
- continue;
64
- }
54
+ if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
55
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
56
+ if (res.length > 2) {
57
+ const lastSlashIndex = res.lastIndexOf("/");
58
+ lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
59
+ continue;
60
+ } else if (res.length > 0) {
61
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
62
+ continue;
65
63
  }
66
- allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
67
- } else
68
- res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
64
+ }
65
+ allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
66
+ } else
67
+ res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
69
68
  lastSlash = index, dots = 0;
70
- } else
71
- char === "." && dots !== -1 ? ++dots : dots = -1;
69
+ } else char === "." && dots !== -1 ? ++dots : dots = -1;
72
70
  }
73
71
  return res;
74
72
  }
@@ -77,15 +75,11 @@ const isAbsolute = function(p) {
77
75
  }, dirname = function(p) {
78
76
  const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
79
77
  return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
80
- }, 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, timestampRegex = /[?&]t=(\d{13})(&?)/;
81
- function parseUrl(url) {
82
- const idQuery = url.split("?")[1];
83
- let timestamp = 0;
84
- return {
85
- query: idQuery ? ("?" + idQuery).replace(timestampRegex, (substring, tsString, nextItem) => (timestamp = Number(tsString), substring[0] === "?" && nextItem === "&" ? "?" : "")) : "",
86
- timestamp
87
- };
78
+ };
79
+ function normalizeAbsoluteUrl(url, root) {
80
+ return url = slash(url), url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url.startsWith(root) && (url = url.slice(root.length - 1)), url;
88
81
  }
82
+ const 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;
89
83
  function encodePathChars(filepath) {
90
84
  return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf(`
91
85
  `) !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
@@ -208,7 +202,13 @@ function traceSegmentInternal(segments, memo, line, column, bias) {
208
202
  return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
209
203
  }
210
204
  class DecodedMap {
211
- map;
205
+ constructor(map, from) {
206
+ this.map = map;
207
+ const { mappings, names, sources } = map;
208
+ this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map(
209
+ (s) => posixResolve(s || "", from)
210
+ );
211
+ }
212
212
  _encoded;
213
213
  _decoded;
214
214
  _decodedMemo;
@@ -216,11 +216,6 @@ class DecodedMap {
216
216
  version;
217
217
  names = [];
218
218
  resolvedSources;
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((s) => posixResolve(s || "", from));
223
- }
224
219
  }
225
220
  function memoizedState() {
226
221
  return {
@@ -233,7 +228,9 @@ function getOriginalPosition(map, needle) {
233
228
  const result = originalPositionFor(map, needle);
234
229
  return result.column == null ? null : result;
235
230
  }
236
- const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
231
+ const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(
232
+ `//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
233
+ );
237
234
  class ModuleCacheMap extends Map {
238
235
  root;
239
236
  constructor(root, entries) {
@@ -285,8 +282,7 @@ class ModuleCacheMap extends Map {
285
282
  invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
286
283
  for (const _id of ids) {
287
284
  const id = this.normalize(_id);
288
- if (invalidated.has(id))
289
- continue;
285
+ if (invalidated.has(id)) continue;
290
286
  invalidated.add(id);
291
287
  const mod = super.get(id);
292
288
  mod?.importers && this.invalidateDepTree(mod.importers, invalidated), this.invalidateUrl(id);
@@ -299,8 +295,7 @@ class ModuleCacheMap extends Map {
299
295
  invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
300
296
  for (const _id of ids) {
301
297
  const id = this.normalize(_id);
302
- if (invalidated.has(id))
303
- continue;
298
+ if (invalidated.has(id)) continue;
304
299
  invalidated.add(id);
305
300
  const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
306
301
  subIds.length && this.invalidateSubDepTree(subIds, invalidated), super.delete(id);
@@ -309,28 +304,23 @@ class ModuleCacheMap extends Map {
309
304
  }
310
305
  getSourceMap(moduleId) {
311
306
  const mod = this.get(moduleId);
312
- if (mod.map)
313
- return mod.map;
314
- if (!mod.meta || !("code" in mod.meta))
315
- return null;
316
- const mapString = mod.meta.code.match(MODULE_RUNNER_SOURCEMAPPING_REGEXP)?.[1];
317
- if (!mapString)
318
- return null;
307
+ if (mod.map) return mod.map;
308
+ if (!mod.meta || !("code" in mod.meta)) return null;
309
+ const mapString = mod.meta.code.match(
310
+ MODULE_RUNNER_SOURCEMAPPING_REGEXP
311
+ )?.[1];
312
+ if (!mapString) return null;
319
313
  const baseFile = mod.meta.file || moduleId.split("?")[0];
320
314
  return mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), baseFile), mod.map;
321
315
  }
322
316
  }
323
- const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test"]);
317
+ const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test", "node:sqlite"]);
324
318
  function normalizeModuleId(file, root) {
325
- if (prefixedBuiltins.has(file))
326
- return file;
319
+ if (prefixedBuiltins.has(file)) return file;
327
320
  let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
328
321
  return unixFile.startsWith(root) && (unixFile = unixFile.slice(root.length - 1)), unixFile.replace(/^file:\//, "/");
329
322
  }
330
323
  class HMRContext {
331
- hmrClient;
332
- ownerPath;
333
- newListeners;
334
324
  constructor(hmrClient, ownerPath) {
335
325
  this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
336
326
  const mod = hmrClient.hotModulesMap.get(ownerPath);
@@ -339,10 +329,14 @@ class HMRContext {
339
329
  if (staleListeners)
340
330
  for (const [event, staleFns] of staleListeners) {
341
331
  const listeners = hmrClient.customListenersMap.get(event);
342
- listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
332
+ listeners && hmrClient.customListenersMap.set(
333
+ event,
334
+ listeners.filter((l) => !staleFns.includes(l))
335
+ );
343
336
  }
344
337
  this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
345
338
  }
339
+ newListeners;
346
340
  get data() {
347
341
  return this.hmrClient.dataMap.get(this.ownerPath);
348
342
  }
@@ -378,7 +372,9 @@ class HMRContext {
378
372
  }), this.send("vite:invalidate", {
379
373
  path: this.ownerPath,
380
374
  message
381
- }), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
375
+ }), this.hmrClient.logger.debug(
376
+ `invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
377
+ );
382
378
  }
383
379
  on(event, cb) {
384
380
  const addToMap = (map) => {
@@ -402,7 +398,9 @@ class HMRContext {
402
398
  removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
403
399
  }
404
400
  send(event, data) {
405
- this.hmrClient.messenger.send(JSON.stringify({ type: "custom", event, data }));
401
+ this.hmrClient.messenger.send(
402
+ JSON.stringify({ type: "custom", event, data })
403
+ );
406
404
  }
407
405
  acceptDeps(deps, callback = () => {
408
406
  }) {
@@ -417,7 +415,6 @@ class HMRContext {
417
415
  }
418
416
  }
419
417
  class HMRMessenger {
420
- connection;
421
418
  constructor(connection) {
422
419
  this.connection = connection;
423
420
  }
@@ -430,8 +427,9 @@ class HMRMessenger {
430
427
  }
431
428
  }
432
429
  class HMRClient {
433
- logger;
434
- importUpdatedModule;
430
+ constructor(logger, connection, importUpdatedModule) {
431
+ this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
432
+ }
435
433
  hotModulesMap = /* @__PURE__ */ new Map();
436
434
  disposeMap = /* @__PURE__ */ new Map();
437
435
  pruneMap = /* @__PURE__ */ new Map();
@@ -439,9 +437,6 @@ class HMRClient {
439
437
  customListenersMap = /* @__PURE__ */ new Map();
440
438
  ctxToListenersMap = /* @__PURE__ */ new Map();
441
439
  messenger;
442
- constructor(logger, connection, importUpdatedModule) {
443
- this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
444
- }
445
440
  async notifyListeners(event, data) {
446
441
  const cbs = this.customListenersMap.get(event);
447
442
  cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
@@ -453,17 +448,20 @@ class HMRClient {
453
448
  // but they may have left behind side effects that need to be cleaned up
454
449
  // (.e.g style injections)
455
450
  async prunePaths(paths) {
456
- await Promise.all(paths.map((path) => {
457
- const disposer = this.disposeMap.get(path);
458
- if (disposer)
459
- return disposer(this.dataMap.get(path));
460
- })), paths.forEach((path) => {
451
+ await Promise.all(
452
+ paths.map((path) => {
453
+ const disposer = this.disposeMap.get(path);
454
+ if (disposer) return disposer(this.dataMap.get(path));
455
+ })
456
+ ), paths.forEach((path) => {
461
457
  const fn = this.pruneMap.get(path);
462
458
  fn && fn(this.dataMap.get(path));
463
459
  });
464
460
  }
465
461
  warnFailedUpdate(err, path) {
466
- err.message.includes("fetch") || this.logger.error(err), this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
462
+ err.message.includes("fetch") || this.logger.error(err), this.logger.error(
463
+ `Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
464
+ );
467
465
  }
468
466
  updateQueue = [];
469
467
  pendingUpdateQueue = !1;
@@ -484,7 +482,9 @@ class HMRClient {
484
482
  if (!mod)
485
483
  return;
486
484
  let fetchedModule;
487
- const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
485
+ const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(
486
+ ({ deps }) => deps.includes(acceptedPath)
487
+ );
488
488
  if (isSelfUpdate || qualifiedCallbacks.length > 0) {
489
489
  const disposer = this.disposeMap.get(acceptedPath);
490
490
  disposer && await disposer(this.dataMap.get(acceptedPath));
@@ -496,18 +496,22 @@ class HMRClient {
496
496
  }
497
497
  return () => {
498
498
  for (const { deps, fn } of qualifiedCallbacks)
499
- fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
499
+ fn(
500
+ deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
501
+ );
500
502
  const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
501
503
  this.logger.debug(`hot updated: ${loggedPath}`);
502
504
  };
503
505
  }
504
506
  }
505
507
  function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
506
- if (!metadata?.isDynamicImport && moduleType !== "module" && metadata?.importedNames?.length) {
508
+ if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
507
509
  const missingBindings = metadata.importedNames.filter((s) => !(s in mod));
508
510
  if (missingBindings.length) {
509
511
  const lastBinding = missingBindings[missingBindings.length - 1];
510
- throw 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.
512
+ throw moduleType === "module" ? new SyntaxError(
513
+ `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
514
+ ) : 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.
511
515
  CommonJS modules can always be imported via the default export, for example using:
512
516
 
513
517
  import pkg from '${rawId}';
@@ -516,15 +520,6 @@ const {${missingBindings.join(", ")}} = pkg;
516
520
  }
517
521
  }
518
522
  }
519
- function proxyGuardOnlyEsm(mod, rawId, metadata) {
520
- return metadata?.importedNames?.length ? new Proxy(mod, {
521
- get(mod2, prop) {
522
- if (prop !== "then" && !(prop in mod2))
523
- throw new SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${prop.toString()}'`);
524
- return mod2[prop];
525
- }
526
- }) : mod;
527
- }
528
523
  const ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {
529
524
  }, silentConsole = {
530
525
  debug: noop,
@@ -545,20 +540,24 @@ async function handleHotPayload(runner, payload) {
545
540
  hmrClient.logger.debug("connected."), hmrClient.messenger.flush();
546
541
  break;
547
542
  case "update":
548
- await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
549
- if (update.type === "js-update")
550
- return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
551
- hmrClient.logger.error("css hmr is not supported in runner mode.");
552
- })), await hmrClient.notifyListeners("vite:afterUpdate", payload);
543
+ await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
544
+ payload.updates.map(async (update) => {
545
+ if (update.type === "js-update")
546
+ return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
547
+ hmrClient.logger.error("css hmr is not supported in runner mode.");
548
+ })
549
+ ), await hmrClient.notifyListeners("vite:afterUpdate", payload);
553
550
  break;
554
551
  case "custom": {
555
552
  await hmrClient.notifyListeners(payload.event, payload.data);
556
553
  break;
557
554
  }
558
555
  case "full-reload": {
559
- const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
560
- if (!clearEntrypoints.size)
561
- break;
556
+ const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? getModulesEntrypoints(
557
+ runner,
558
+ getModulesByFile(runner, slash(triggeredBy))
559
+ ) : findAllEntrypoints(runner);
560
+ if (!clearEntrypoints.size) break;
562
561
  hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.moduleCache.clear();
563
562
  for (const id of clearEntrypoints)
564
563
  await runner.import(id);
@@ -570,9 +569,11 @@ async function handleHotPayload(runner, payload) {
570
569
  case "error": {
571
570
  await hmrClient.notifyListeners("vite:error", payload);
572
571
  const err = payload.err;
573
- hmrClient.logger.error(`Internal Server Error
572
+ hmrClient.logger.error(
573
+ `Internal Server Error
574
574
  ${err.message}
575
- ${err.stack}`);
575
+ ${err.stack}`
576
+ );
576
577
  break;
577
578
  }
578
579
  default:
@@ -608,8 +609,7 @@ function getModulesByFile(runner, file) {
608
609
  }
609
610
  function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
610
611
  for (const moduleId of modules) {
611
- if (visited.has(moduleId))
612
- continue;
612
+ if (visited.has(moduleId)) continue;
613
613
  visited.add(moduleId);
614
614
  const module = runner.moduleCache.getByModuleId(moduleId);
615
615
  if (module.importers && !module.importers.size) {
@@ -629,11 +629,12 @@ function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
629
629
  const sourceMapCache = {}, fileContentsCache = {}, moduleGraphs = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
630
630
  for (const handler of handlers) {
631
631
  const result = handler(...args);
632
- if (result)
633
- return result;
632
+ if (result) return result;
634
633
  }
635
634
  return null;
636
- }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
635
+ }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
636
+ retrieveSourceMapHandlers
637
+ );
637
638
  let overridden = !1;
638
639
  const originalPrepare = Error.prepareStackTrace;
639
640
  function resetInterceptor(runner, options) {
@@ -643,8 +644,7 @@ function interceptStackTrace(runner, options = {}) {
643
644
  return overridden || (Error.prepareStackTrace = prepareStackTrace, overridden = !0), moduleGraphs.add(runner.moduleCache), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runner, options);
644
645
  }
645
646
  function supportRelativeURL(file, url) {
646
- if (!file)
647
- return url;
647
+ if (!file) return url;
648
648
  const dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir);
649
649
  let protocol = match ? match[0] : "";
650
650
  const startPath = dir.slice(protocol.length);
@@ -663,29 +663,24 @@ function getRunnerSourceMap(position) {
663
663
  return null;
664
664
  }
665
665
  function retrieveFile(path) {
666
- if (path in fileContentsCache)
667
- return fileContentsCache[path];
666
+ if (path in fileContentsCache) return fileContentsCache[path];
668
667
  const content = retrieveFileFromHandlers(path);
669
668
  return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
670
669
  }
671
670
  function retrieveSourceMapURL(source) {
672
671
  const fileData = retrieveFile(source);
673
- if (!fileData)
674
- return null;
672
+ if (!fileData) return null;
675
673
  const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
676
674
  let lastMatch, match;
677
- for (; match = re.exec(fileData); )
678
- lastMatch = match;
675
+ for (; match = re.exec(fileData); ) lastMatch = match;
679
676
  return lastMatch ? lastMatch[1] : null;
680
677
  }
681
678
  const reSourceMap = /^data:application\/json[^,]+base64,/;
682
679
  function retrieveSourceMap(source) {
683
680
  const urlAndMap = retrieveSourceMapFromHandlers(source);
684
- if (urlAndMap)
685
- return urlAndMap;
681
+ if (urlAndMap) return urlAndMap;
686
682
  let sourceMappingURL = retrieveSourceMapURL(source);
687
- if (!sourceMappingURL)
688
- return null;
683
+ if (!sourceMappingURL) return null;
689
684
  let sourceMapData;
690
685
  if (reSourceMap.test(sourceMappingURL)) {
691
686
  const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
@@ -698,8 +693,7 @@ function retrieveSourceMap(source) {
698
693
  } : null;
699
694
  }
700
695
  function mapSourcePosition(position) {
701
- if (!position.source)
702
- return position;
696
+ if (!position.source) return position;
703
697
  let sourceMap = getRunnerSourceMap(position);
704
698
  if (sourceMap || (sourceMap = sourceMapCache[position.source]), !sourceMap) {
705
699
  const urlAndMap = retrieveSourceMap(position.source);
@@ -707,7 +701,10 @@ function mapSourcePosition(position) {
707
701
  const url = urlAndMap.url;
708
702
  sourceMap = sourceMapCache[position.source] = {
709
703
  url,
710
- map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
704
+ map: new DecodedMap(
705
+ typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map,
706
+ url
707
+ )
711
708
  };
712
709
  const contents = sourceMap.map?.map.sourcesContent;
713
710
  sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
@@ -726,7 +723,10 @@ function mapSourcePosition(position) {
726
723
  if (sourceMap && sourceMap.map && sourceMap.url) {
727
724
  const originalPosition = getOriginalPosition(sourceMap.map, position);
728
725
  if (originalPosition && originalPosition.source != null)
729
- return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
726
+ return originalPosition.source = supportRelativeURL(
727
+ sourceMap.url,
728
+ originalPosition.source
729
+ ), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
730
730
  }
731
731
  return position;
732
732
  }
@@ -760,13 +760,14 @@ function CallSiteToString() {
760
760
  const functionName = this.getFunctionName();
761
761
  let addSuffix = !0;
762
762
  const isConstructor = this.isConstructor();
763
- if (!(this.isToplevel() || isConstructor)) {
763
+ if (this.isToplevel() || isConstructor)
764
+ isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
765
+ else {
764
766
  let typeName = this.getTypeName();
765
767
  typeName === "[object Object]" && (typeName = "null");
766
768
  const methodName = this.getMethodName();
767
769
  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>"}`;
768
- } else
769
- isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
770
+ }
770
771
  return addSuffix && (line += ` (${fileLocation})`), line;
771
772
  }
772
773
  function cloneCallSite(frame) {
@@ -823,18 +824,31 @@ function prepareStackTrace(error, stack) {
823
824
  function enableSourceMapSupport(runner) {
824
825
  if (runner.options.sourcemapInterceptor === "node") {
825
826
  if (typeof process > "u")
826
- throw new TypeError(`Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`);
827
+ throw new TypeError(
828
+ `Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`
829
+ );
827
830
  if (typeof process.setSourceMapsEnabled != "function")
828
- throw new TypeError(`Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`);
831
+ throw new TypeError(
832
+ `Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`
833
+ );
829
834
  const isEnabledAlready = process.sourceMapsEnabled ?? !1;
830
835
  return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
831
836
  }
832
- return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
837
+ return interceptStackTrace(
838
+ runner,
839
+ typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0
840
+ );
833
841
  }
834
842
  class ModuleRunner {
835
- options;
836
- evaluator;
837
- debug;
843
+ constructor(options, evaluator, debug) {
844
+ this.options = options, this.evaluator = evaluator, this.debug = debug;
845
+ const root = this.options.root;
846
+ this.root = root[root.length - 1] === "/" ? root : `${root}/`, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), this.transport = options.transport, typeof options.hmr == "object" && (this.hmrClient = new HMRClient(
847
+ options.hmr.logger === !1 ? silentConsole : options.hmr.logger || hmrLogger,
848
+ options.hmr.connection,
849
+ ({ acceptedPath }) => this.import(acceptedPath)
850
+ ), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
851
+ }
838
852
  /**
839
853
  * Holds the cache of modules
840
854
  * Keys of the map are ids
@@ -845,18 +859,15 @@ class ModuleRunner {
845
859
  fileToIdMap = /* @__PURE__ */ new Map();
846
860
  envProxy = new Proxy({}, {
847
861
  get(_, p) {
848
- throw new Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
862
+ throw new Error(
863
+ `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`
864
+ );
849
865
  }
850
866
  });
851
867
  transport;
852
868
  resetSourceMapSupport;
869
+ root;
853
870
  destroyed = !1;
854
- constructor(options, evaluator, debug) {
855
- this.options = options, this.evaluator = evaluator, this.debug = debug, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), this.transport = options.transport, typeof options.hmr == "object" && (this.hmrClient = new HMRClient(options.hmr.logger === !1 ? silentConsole : options.hmr.logger || hmrLogger, options.hmr.connection, ({ acceptedPath, explicitImportRequired, timestamp }) => {
856
- const [acceptedPathWithoutQuery, query] = acceptedPath.split("?"), url = acceptedPathWithoutQuery + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`;
857
- return this.import(url);
858
- }), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
859
- }
860
871
  /**
861
872
  * URL to execute. Accepts file path, server path or id relative to the root.
862
873
  */
@@ -888,29 +899,47 @@ class ModuleRunner {
888
899
  // this URL is something that user passes down manually, and is later resolved by fetchModule
889
900
  // moduleCache.normalize is used on resolved "file" property
890
901
  normalizeEntryUrl(url) {
891
- if (url[0] === ".")
892
- return url;
893
- url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url = slash(url);
894
- const _root = this.options.root, root = _root[_root.length - 1] === "/" ? _root : `${_root}/`;
895
- return url.startsWith(root) ? url.slice(root.length - 1) : url[0] === "/" ? url : wrapId(url);
902
+ return url[0] === "." ? url : (url = normalizeAbsoluteUrl(url, this.root), url[0] === "/" ? url : wrapId(url));
896
903
  }
897
904
  processImport(exports, fetchResult, metadata) {
898
905
  if (!("externalize" in fetchResult))
899
906
  return exports;
900
907
  const { id, type } = fetchResult;
901
- return type !== "module" && type !== "commonjs" ? exports : (analyzeImportedModDifference(exports, id, type, metadata), proxyGuardOnlyEsm(exports, id, metadata));
908
+ return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, id, type, metadata), exports;
909
+ }
910
+ isCircularModule(mod) {
911
+ for (const importedFile of mod.imports)
912
+ if (mod.importers.has(importedFile))
913
+ return !0;
914
+ return !1;
902
915
  }
903
- async cachedRequest(id, mod, callstack = [], metadata) {
904
- const meta = mod.meta, moduleId = meta.id, { imports, importers } = mod, importee = callstack[callstack.length - 1];
905
- if (importee && importers.add(importee), (callstack.includes(moduleId) || Array.from(imports.values()).some((i) => importers.has(i))) && mod.exports)
916
+ isCircularImport(importers, moduleId, visited = /* @__PURE__ */ new Set()) {
917
+ for (const importer of importers) {
918
+ if (visited.has(importer))
919
+ continue;
920
+ if (visited.add(importer), importer === moduleId)
921
+ return !0;
922
+ const mod = this.moduleCache.getByModuleId(
923
+ importer
924
+ );
925
+ if (mod.importers.size && this.isCircularImport(mod.importers, moduleId, visited))
926
+ return !0;
927
+ }
928
+ return !1;
929
+ }
930
+ async cachedRequest(id, mod_, callstack = [], metadata) {
931
+ const mod = mod_, meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
932
+ if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports)
906
933
  return this.processImport(mod.exports, meta, metadata);
907
934
  let debugTimer;
908
935
  this.debug && (debugTimer = setTimeout(() => {
909
936
  const getStack = () => `stack:
910
937
  ${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join(`
911
938
  `)}`;
912
- this.debug(`[module runner] module ${moduleId} takes over 2s to load.
913
- ${getStack()}`);
939
+ this.debug(
940
+ `[module runner] module ${moduleId} takes over 2s to load.
941
+ ${getStack()}`
942
+ );
914
943
  }, 2e3));
915
944
  try {
916
945
  if (mod.promise)
@@ -924,15 +953,25 @@ ${getStack()}`);
924
953
  async cachedModule(url, importer) {
925
954
  if (this.destroyed)
926
955
  throw new Error("Vite module runner has been destroyed.");
956
+ this.debug?.("[module runner] fetching", url), url = normalizeAbsoluteUrl(url, this.root);
927
957
  const normalized = this.urlToIdMap.get(url);
928
- if (normalized) {
929
- const mod2 = this.moduleCache.getByModuleId(normalized);
930
- if (mod2.meta)
931
- return mod2;
958
+ let cachedModule = normalized && this.moduleCache.getByModuleId(normalized);
959
+ cachedModule || (cachedModule = this.moduleCache.getByModuleId(url));
960
+ const isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = (
961
+ // fast return for established externalized pattern
962
+ url.startsWith("data:") ? { externalize: url, type: "builtin" } : await this.transport.fetchModule(url, importer, {
963
+ cached: isCached
964
+ })
965
+ );
966
+ if ("cache" in fetchedModule) {
967
+ if (!cachedModule || !cachedModule.meta)
968
+ throw new Error(
969
+ `Module "${url}" was mistakenly invalidated during fetch phase.`
970
+ );
971
+ return cachedModule;
932
972
  }
933
- this.debug?.("[module runner] fetching", url);
934
- const fetchedModule = url.startsWith("data:") ? { externalize: url, type: "builtin" } : await this.transport.fetchModule(url, importer), { query, timestamp } = parseUrl(url), file = "file" in fetchedModule ? fetchedModule.file : void 0, fileId = file ? `${file}${query}` : url, moduleId = this.moduleCache.normalize(fileId), mod = this.moduleCache.getByModuleId(moduleId);
935
- if (mod.timestamp != null && timestamp > 0 && mod.timestamp < timestamp && this.moduleCache.invalidateModule(mod), fetchedModule.id = moduleId, mod.meta = fetchedModule, mod.timestamp = timestamp, file) {
973
+ const idQuery = url.split("?")[1], query = idQuery ? `?${idQuery}` : "", file = "file" in fetchedModule ? fetchedModule.file : void 0, fileId = file ? `${file}${query}` : url, moduleId = this.moduleCache.normalize(fileId), mod = this.moduleCache.getByModuleId(moduleId);
974
+ if ("invalidate" in fetchedModule && fetchedModule.invalidate && this.moduleCache.invalidateModule(mod), fetchedModule.id = moduleId, mod.meta = fetchedModule, file) {
936
975
  const fileModules = this.fileToIdMap.get(file) || [];
937
976
  fileModules.push(moduleId), this.fileToIdMap.set(file, fileModules);
938
977
  }
@@ -953,7 +992,9 @@ ${getStack()}`);
953
992
  const { code, file } = fetchResult;
954
993
  if (code == null) {
955
994
  const importer = callstack[callstack.length - 2];
956
- throw new Error(`[module runner] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`);
995
+ throw new Error(
996
+ `[module runner] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`
997
+ );
957
998
  }
958
999
  const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
959
1000
  filename: isWindows ? toWindowsPath(filename) : filename,
@@ -961,7 +1002,9 @@ ${getStack()}`);
961
1002
  url: href,
962
1003
  env: this.envProxy,
963
1004
  resolve(id2, parent) {
964
- throw new Error('[module runner] "import.meta.resolve" is not supported.');
1005
+ throw new Error(
1006
+ '[module runner] "import.meta.resolve" is not supported.'
1007
+ );
965
1008
  },
966
1009
  // should be replaced during transformation
967
1010
  glob() {
@@ -1019,23 +1062,27 @@ class ESModulesEvaluator {
1019
1062
  ssrExportAllKey,
1020
1063
  // source map should already be inlined by Vite
1021
1064
  '"use strict";' + code
1022
- )(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey]), Object.seal(context[ssrModuleExportsKey]);
1065
+ )(
1066
+ context[ssrModuleExportsKey],
1067
+ context[ssrImportMetaKey],
1068
+ context[ssrImportKey],
1069
+ context[ssrDynamicImportKey],
1070
+ context[ssrExportAllKey]
1071
+ ), Object.seal(context[ssrModuleExportsKey]);
1023
1072
  }
1024
1073
  runExternalModule(filepath) {
1025
1074
  return import(filepath);
1026
1075
  }
1027
1076
  }
1028
1077
  class RemoteRunnerTransport {
1029
- options;
1030
- rpcPromises = /* @__PURE__ */ new Map();
1031
1078
  constructor(options) {
1032
1079
  this.options = options, this.options.onMessage(async (data) => {
1033
- if (typeof data != "object" || !data || !data.__v)
1034
- return;
1080
+ if (typeof data != "object" || !data || !data.__v) return;
1035
1081
  const promise = this.rpcPromises.get(data.i);
1036
1082
  promise && (promise.timeoutId && clearTimeout(promise.timeoutId), this.rpcPromises.delete(data.i), data.e ? promise.reject(data.e) : promise.resolve(data.r));
1037
1083
  });
1038
1084
  }
1085
+ rpcPromises = /* @__PURE__ */ new Map();
1039
1086
  resolve(method, ...args) {
1040
1087
  const promiseId = nanoid();
1041
1088
  return this.options.send({
@@ -1047,7 +1094,11 @@ class RemoteRunnerTransport {
1047
1094
  const timeout = this.options.timeout ?? 6e4;
1048
1095
  let timeoutId;
1049
1096
  timeout > 0 && (timeoutId = setTimeout(() => {
1050
- this.rpcPromises.delete(promiseId), reject(new Error(`${method}(${args.map((arg) => JSON.stringify(arg)).join(", ")}) timed out after ${timeout}ms`));
1097
+ this.rpcPromises.delete(promiseId), reject(
1098
+ new Error(
1099
+ `${method}(${args.map((arg) => JSON.stringify(arg)).join(", ")}) timed out after ${timeout}ms`
1100
+ )
1101
+ );
1051
1102
  }, timeout), timeoutId?.unref?.()), this.rpcPromises.set(promiseId, { resolve: resolve2, reject, timeoutId });
1052
1103
  });
1053
1104
  }
@@ -1058,8 +1109,7 @@ class RemoteRunnerTransport {
1058
1109
  const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1059
1110
  function nanoid(size = 21) {
1060
1111
  let id = "", i = size;
1061
- for (; i--; )
1062
- id += urlAlphabet[Math.random() * 64 | 0];
1112
+ for (; i--; ) id += urlAlphabet[Math.random() * 64 | 0];
1063
1113
  return id;
1064
1114
  }
1065
1115
  export {