vite 6.0.0-beta.0 → 6.0.0-beta.2

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.
@@ -16,11 +16,12 @@ function cleanUrl(url) {
16
16
  function isPrimitive(value) {
17
17
  return !value || typeof value != "object" && typeof value != "function";
18
18
  }
19
- function withTrailingSlash(path) {
20
- return path[path.length - 1] !== "/" ? `${path}/` : path;
21
- }
22
19
  const AsyncFunction = async function() {
23
- }.constructor, _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
20
+ }.constructor, asyncFunctionDeclarationPaddingLineCount = /* @__PURE__ */ (() => {
21
+ const body = "/*code*/", source = new AsyncFunction("a", "b", body).toString();
22
+ return source.slice(0, source.indexOf(body)).split(`
23
+ `).length - 1;
24
+ })(), _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
24
25
  function normalizeWindowsPath(input = "") {
25
26
  return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
26
27
  }
@@ -236,94 +237,92 @@ function getOriginalPosition(map, needle) {
236
237
  const MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(
237
238
  `//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
238
239
  );
239
- class ModuleCacheMap extends Map {
240
- root;
241
- constructor(root, entries) {
242
- super(entries), this.root = withTrailingSlash(root);
243
- }
244
- normalize(fsPath) {
245
- return normalizeModuleId(fsPath, this.root);
246
- }
240
+ class EvaluatedModuleNode {
241
+ constructor(id, url) {
242
+ this.id = id, this.url = url, this.file = cleanUrl(id);
243
+ }
244
+ importers = /* @__PURE__ */ new Set();
245
+ imports = /* @__PURE__ */ new Set();
246
+ evaluated = !1;
247
+ meta;
248
+ promise;
249
+ exports;
250
+ file;
251
+ map;
252
+ }
253
+ class EvaluatedModules {
254
+ idToModuleMap = /* @__PURE__ */ new Map();
255
+ fileToModulesMap = /* @__PURE__ */ new Map();
256
+ urlToIdModuleMap = /* @__PURE__ */ new Map();
247
257
  /**
248
- * Assign partial data to the map
258
+ * Returns the module node by the resolved module ID. Usually, module ID is
259
+ * the file system path with query and/or hash. It can also be a virtual module.
260
+ *
261
+ * Module runner graph will have 1 to 1 mapping with the server module graph.
262
+ * @param id Resolved module ID
249
263
  */
250
- update(fsPath, mod) {
251
- return fsPath = this.normalize(fsPath), super.has(fsPath) ? Object.assign(super.get(fsPath), mod) : this.setByModuleId(fsPath, mod), this;
252
- }
253
- setByModuleId(modulePath, mod) {
254
- return super.set(modulePath, mod);
255
- }
256
- set(fsPath, mod) {
257
- return this.setByModuleId(this.normalize(fsPath), mod);
258
- }
259
- getByModuleId(modulePath) {
260
- super.has(modulePath) || this.setByModuleId(modulePath, {});
261
- const mod = super.get(modulePath);
262
- return mod.imports || Object.assign(mod, {
263
- imports: /* @__PURE__ */ new Set(),
264
- importers: /* @__PURE__ */ new Set(),
265
- timestamp: 0
266
- }), mod;
267
- }
268
- get(fsPath) {
269
- return this.getByModuleId(this.normalize(fsPath));
264
+ getModuleById(id) {
265
+ return this.idToModuleMap.get(id);
270
266
  }
271
- deleteByModuleId(modulePath) {
272
- return super.delete(modulePath);
273
- }
274
- delete(fsPath) {
275
- return this.deleteByModuleId(this.normalize(fsPath));
276
- }
277
- invalidateUrl(id) {
278
- const module = this.get(id);
279
- this.invalidateModule(module);
280
- }
281
- invalidateModule(module) {
282
- module.evaluated = !1, module.meta = void 0, module.map = void 0, module.promise = void 0, module.exports = void 0, module.imports?.clear();
267
+ /**
268
+ * Returns all modules related to the file system path. Different modules
269
+ * might have different query parameters or hash, so it's possible to have
270
+ * multiple modules for the same file.
271
+ * @param file The file system path of the module
272
+ */
273
+ getModulesByFile(file) {
274
+ return this.fileToModulesMap.get(file);
283
275
  }
284
276
  /**
285
- * Invalidate modules that dependent on the given modules, up to the main entry
277
+ * Returns the module node by the URL that was used in the import statement.
278
+ * Unlike module graph on the server, the URL is not resolved and is used as is.
279
+ * @param url Server URL that was used in the import statement
286
280
  */
287
- invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
288
- for (const _id of ids) {
289
- const id = this.normalize(_id);
290
- if (invalidated.has(id)) continue;
291
- invalidated.add(id);
292
- const mod = super.get(id);
293
- mod?.importers && this.invalidateDepTree(mod.importers, invalidated), this.invalidateUrl(id);
294
- }
295
- return invalidated;
281
+ getModuleByUrl(url) {
282
+ return this.urlToIdModuleMap.get(unwrapId(url));
296
283
  }
297
284
  /**
298
- * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
285
+ * Ensure that module is in the graph. If the module is already in the graph,
286
+ * it will return the existing module node. Otherwise, it will create a new
287
+ * module node and add it to the graph.
288
+ * @param id Resolved module ID
289
+ * @param url URL that was used in the import statement
299
290
  */
300
- invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
301
- for (const _id of ids) {
302
- const id = this.normalize(_id);
303
- if (invalidated.has(id)) continue;
304
- invalidated.add(id);
305
- const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
306
- subIds.length && this.invalidateSubDepTree(subIds, invalidated), super.delete(id);
291
+ ensureModule(id, url) {
292
+ if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
293
+ const moduleNode2 = this.idToModuleMap.get(id);
294
+ return this.urlToIdModuleMap.set(url, moduleNode2), moduleNode2;
307
295
  }
308
- return invalidated;
296
+ const moduleNode = new EvaluatedModuleNode(id, url);
297
+ this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
298
+ const fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
299
+ return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
309
300
  }
310
- getSourceMap(moduleId) {
311
- const mod = this.get(moduleId);
301
+ invalidateModule(node) {
302
+ node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
303
+ }
304
+ /**
305
+ * Extracts the inlined source map from the module code and returns the decoded
306
+ * source map. If the source map is not inlined, it will return null.
307
+ * @param id Resolved module ID
308
+ */
309
+ getModuleSourceMapById(id) {
310
+ const mod = this.getModuleById(id);
311
+ if (!mod) return null;
312
312
  if (mod.map) return mod.map;
313
313
  if (!mod.meta || !("code" in mod.meta)) return null;
314
314
  const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
315
315
  mod.meta.code
316
316
  )?.[1];
317
- if (!mapString) return null;
318
- const baseFile = mod.meta.file || moduleId.split("?")[0];
319
- return mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), baseFile), mod.map;
317
+ return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
318
+ }
319
+ clear() {
320
+ this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
320
321
  }
321
322
  }
322
323
  const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test", "node:sqlite"]);
323
- function normalizeModuleId(file, root) {
324
- if (prefixedBuiltins.has(file)) return file;
325
- let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
326
- return unixFile.startsWith(root) && (unixFile = unixFile.slice(root.length - 1)), unixFile.replace(/^file:\//, "/");
324
+ function normalizeModuleId(file) {
325
+ return prefixedBuiltins.has(file) ? file : slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
327
326
  }
328
327
  class HMRContext {
329
328
  constructor(hmrClient, ownerPath) {
@@ -403,9 +402,7 @@ class HMRContext {
403
402
  removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
404
403
  }
405
404
  send(event, data) {
406
- this.hmrClient.messenger.send(
407
- JSON.stringify({ type: "custom", event, data })
408
- );
405
+ this.hmrClient.messenger.send({ type: "custom", event, data });
409
406
  }
410
407
  acceptDeps(deps, callback = () => {
411
408
  }) {
@@ -424,8 +421,8 @@ class HMRMessenger {
424
421
  this.connection = connection;
425
422
  }
426
423
  queue = [];
427
- send(message) {
428
- this.queue.push(message), this.flush();
424
+ send(payload) {
425
+ this.queue.push(payload), this.flush();
429
426
  }
430
427
  flush() {
431
428
  this.connection.isReady() && (this.queue.forEach((msg) => this.connection.send(msg)), this.queue = []);
@@ -558,14 +555,14 @@ async function handleHotPayload(runner, payload) {
558
555
  break;
559
556
  }
560
557
  case "full-reload": {
561
- const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? getModulesEntrypoints(
558
+ const { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(
562
559
  runner,
563
560
  getModulesByFile(runner, slash(triggeredBy))
564
561
  ) : findAllEntrypoints(runner);
565
- if (!clearEntrypoints.size) break;
566
- hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.moduleCache.clear();
567
- for (const id of clearEntrypoints)
568
- await runner.import(id);
562
+ if (!clearEntrypointUrls.size) break;
563
+ hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
564
+ for (const url of clearEntrypointUrls)
565
+ await runner.import(url);
569
566
  break;
570
567
  }
571
568
  case "prune":
@@ -607,31 +604,31 @@ class Queue {
607
604
  }
608
605
  }
609
606
  function getModulesByFile(runner, file) {
610
- const modules = [];
611
- for (const [id, mod] of runner.moduleCache.entries())
612
- mod.meta && "file" in mod.meta && mod.meta.file === file && modules.push(id);
613
- return modules;
607
+ const nodes = runner.evaluatedModules.getModulesByFile(file);
608
+ return nodes ? [...nodes].map((node) => node.id) : [];
614
609
  }
615
610
  function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
616
611
  for (const moduleId of modules) {
617
612
  if (visited.has(moduleId)) continue;
618
613
  visited.add(moduleId);
619
- const module = runner.moduleCache.getByModuleId(moduleId);
620
- if (module.importers && !module.importers.size) {
621
- entrypoints.add(moduleId);
622
- continue;
614
+ const module = runner.evaluatedModules.getModuleById(moduleId);
615
+ if (module) {
616
+ if (module.importers && !module.importers.size) {
617
+ entrypoints.add(module.url);
618
+ continue;
619
+ }
620
+ for (const importer of module.importers || [])
621
+ getModulesEntrypoints(runner, [importer], visited, entrypoints);
623
622
  }
624
- for (const importer of module.importers || [])
625
- getModulesEntrypoints(runner, [importer], visited, entrypoints);
626
623
  }
627
624
  return entrypoints;
628
625
  }
629
626
  function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
630
- for (const [id, mod] of runner.moduleCache.entries())
631
- mod.importers && !mod.importers.size && entrypoints.add(id);
627
+ for (const mod of runner.evaluatedModules.idToModuleMap.values())
628
+ mod.importers && !mod.importers.size && entrypoints.add(mod.url);
632
629
  return entrypoints;
633
630
  }
634
- const sourceMapCache = {}, fileContentsCache = {}, moduleGraphs = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
631
+ const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
635
632
  for (const handler of handlers) {
636
633
  const result = handler(...args);
637
634
  if (result) return result;
@@ -643,10 +640,10 @@ const sourceMapCache = {}, fileContentsCache = {}, moduleGraphs = /* @__PURE__ *
643
640
  let overridden = !1;
644
641
  const originalPrepare = Error.prepareStackTrace;
645
642
  function resetInterceptor(runner, options) {
646
- moduleGraphs.delete(runner.moduleCache), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), moduleGraphs.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
643
+ evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
647
644
  }
648
645
  function interceptStackTrace(runner, options = {}) {
649
- 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);
646
+ 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);
650
647
  }
651
648
  function supportRelativeURL(file, url) {
652
649
  if (!file) return url;
@@ -656,8 +653,8 @@ function supportRelativeURL(file, url) {
656
653
  return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
657
654
  }
658
655
  function getRunnerSourceMap(position) {
659
- for (const moduleCache of moduleGraphs) {
660
- const sourceMap = moduleCache.getSourceMap(position.source);
656
+ for (const moduleGraph of evaluatedModulesCache) {
657
+ const sourceMap = moduleGraph.getModuleSourceMapById(position.source);
661
658
  if (sourceMap)
662
659
  return {
663
660
  url: position.source,
@@ -848,20 +845,14 @@ class ModuleRunner {
848
845
  constructor(options, evaluator, debug) {
849
846
  this.options = options, this.evaluator = evaluator, this.debug = debug;
850
847
  const root = this.options.root;
851
- 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(
848
+ this.root = root[root.length - 1] === "/" ? root : `${root}/`, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = options.transport, typeof options.hmr == "object" && (this.hmrClient = new HMRClient(
852
849
  options.hmr.logger === !1 ? silentConsole : options.hmr.logger || hmrLogger,
853
850
  options.hmr.connection,
854
851
  ({ acceptedPath }) => this.import(acceptedPath)
855
852
  ), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
856
853
  }
857
- /**
858
- * Holds the cache of modules
859
- * Keys of the map are ids
860
- */
861
- moduleCache;
854
+ evaluatedModules;
862
855
  hmrClient;
863
- urlToIdMap = /* @__PURE__ */ new Map();
864
- fileToIdMap = /* @__PURE__ */ new Map();
865
856
  envProxy = new Proxy({}, {
866
857
  get(_, p) {
867
858
  throw new Error(
@@ -872,7 +863,7 @@ class ModuleRunner {
872
863
  transport;
873
864
  resetSourceMapSupport;
874
865
  root;
875
- moduleInfoCache = /* @__PURE__ */ new Map();
866
+ concurrentModuleNodePromises = /* @__PURE__ */ new Map();
876
867
  destroyed = !1;
877
868
  /**
878
869
  * URL to execute. Accepts file path, server path or id relative to the root.
@@ -885,7 +876,7 @@ class ModuleRunner {
885
876
  * Clear all caches including HMR listeners.
886
877
  */
887
878
  clearCache() {
888
- this.moduleCache.clear(), this.urlToIdMap.clear(), this.hmrClient?.clear();
879
+ this.evaluatedModules.clear(), this.hmrClient?.clear();
889
880
  }
890
881
  /**
891
882
  * Clears all caches, removes all HMR listeners, and resets source map support.
@@ -903,8 +894,8 @@ class ModuleRunner {
903
894
  processImport(exports, fetchResult, metadata) {
904
895
  if (!("externalize" in fetchResult))
905
896
  return exports;
906
- const { url: id, type } = fetchResult;
907
- return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, id, type, metadata), exports;
897
+ const { url, type } = fetchResult;
898
+ return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
908
899
  }
909
900
  isCircularModule(mod) {
910
901
  for (const importedFile of mod.imports)
@@ -918,32 +909,30 @@ class ModuleRunner {
918
909
  continue;
919
910
  if (visited.add(importer), importer === moduleUrl)
920
911
  return !0;
921
- const mod = this.moduleCache.getByModuleId(
922
- importer
923
- );
924
- if (mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited))
912
+ const mod = this.evaluatedModules.getModuleById(importer);
913
+ if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited))
925
914
  return !0;
926
915
  }
927
916
  return !1;
928
917
  }
929
- async cachedRequest(id, mod_, callstack = [], metadata) {
930
- const mod = mod_, meta = mod.meta, moduleUrl = meta.url, { importers } = mod, importee = callstack[callstack.length - 1];
931
- if (importee && importers.add(importee), (callstack.includes(moduleUrl) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleUrl)) && mod.exports)
918
+ async cachedRequest(url, mod, callstack = [], metadata) {
919
+ const meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
920
+ if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports)
932
921
  return this.processImport(mod.exports, meta, metadata);
933
922
  let debugTimer;
934
923
  this.debug && (debugTimer = setTimeout(() => {
935
924
  const getStack = () => `stack:
936
- ${[...callstack, moduleUrl].reverse().map((p) => ` - ${p}`).join(`
925
+ ${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join(`
937
926
  `)}`;
938
927
  this.debug(
939
- `[module runner] module ${moduleUrl} takes over 2s to load.
928
+ `[module runner] module ${moduleId} takes over 2s to load.
940
929
  ${getStack()}`
941
930
  );
942
931
  }, 2e3));
943
932
  try {
944
933
  if (mod.promise)
945
934
  return this.processImport(await mod.promise, meta, metadata);
946
- const promise = this.directRequest(id, mod, callstack);
935
+ const promise = this.directRequest(url, mod, callstack);
947
936
  return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
948
937
  } finally {
949
938
  mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
@@ -951,15 +940,18 @@ ${getStack()}`
951
940
  }
952
941
  async cachedModule(url, importer) {
953
942
  url = normalizeAbsoluteUrl(url, this.root);
954
- const normalized = this.urlToIdMap.get(url);
955
- let cachedModule = normalized && this.moduleCache.getByModuleId(normalized);
956
- cachedModule || (cachedModule = this.moduleCache.getByModuleId(url));
957
- let cached = this.moduleInfoCache.get(url);
958
- return cached ? this.debug?.("[module runner] using cached module info for", url) : (cached = this.getModuleInformation(url, importer, cachedModule).finally(
959
- () => {
960
- this.moduleInfoCache.delete(url);
961
- }
962
- ), this.moduleInfoCache.set(url, cached)), cached;
943
+ let cached = this.concurrentModuleNodePromises.get(url);
944
+ if (cached)
945
+ this.debug?.("[module runner] using cached module info for", url);
946
+ else {
947
+ const cachedModule = this.evaluatedModules.getModuleByUrl(url);
948
+ cached = this.getModuleInformation(url, importer, cachedModule).finally(
949
+ () => {
950
+ this.concurrentModuleNodePromises.delete(url);
951
+ }
952
+ ), this.concurrentModuleNodePromises.set(url, cached);
953
+ }
954
+ return cached;
963
955
  }
964
956
  async getModuleInformation(url, importer, cachedModule) {
965
957
  if (this.destroyed)
@@ -968,7 +960,8 @@ ${getStack()}`
968
960
  const isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = (
969
961
  // fast return for established externalized pattern
970
962
  url.startsWith("data:") ? { externalize: url, type: "builtin" } : await this.transport.fetchModule(url, importer, {
971
- cached: isCached
963
+ cached: isCached,
964
+ startOffset: this.evaluator.startOffset
972
965
  })
973
966
  );
974
967
  if ("cache" in fetchedModule) {
@@ -978,19 +971,15 @@ ${getStack()}`
978
971
  );
979
972
  return cachedModule;
980
973
  }
981
- const idQuery = url.split("?")[1], query = idQuery ? `?${idQuery}` : "", file = "file" in fetchedModule ? fetchedModule.file : void 0, fileId = file ? `${file}${query}` : url, moduleUrl = this.moduleCache.normalize(fileId), mod = this.moduleCache.getByModuleId(moduleUrl);
982
- if ("invalidate" in fetchedModule && fetchedModule.invalidate && this.moduleCache.invalidateModule(mod), fetchedModule.url = moduleUrl, mod.meta = fetchedModule, file) {
983
- const fileModules = this.fileToIdMap.get(file) || [];
984
- fileModules.push(moduleUrl), this.fileToIdMap.set(file, fileModules);
985
- }
986
- return this.urlToIdMap.set(url, moduleUrl), this.urlToIdMap.set(unwrapId(url), moduleUrl), mod;
974
+ const moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
975
+ return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
987
976
  }
988
977
  // override is allowed, consider this a public API
989
- async directRequest(id, mod, _callstack) {
990
- const fetchResult = mod.meta, moduleUrl = fetchResult.url, callstack = [..._callstack, moduleUrl], request = async (dep, metadata) => {
991
- const importer = "file" in fetchResult && fetchResult.file || moduleUrl, fetchedModule = await this.cachedModule(dep, importer), resolvedId = fetchedModule.meta.url;
992
- return this.moduleCache.getByModuleId(resolvedId).importers.add(moduleUrl), mod.imports.add(resolvedId), this.cachedRequest(dep, fetchedModule, callstack, metadata);
993
- }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(id), dep)), request(dep, { isDynamicImport: !0 }));
978
+ async directRequest(url, mod, _callstack) {
979
+ const fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
980
+ const importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
981
+ return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
982
+ }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
994
983
  if ("externalize" in fetchResult) {
995
984
  const { externalize } = fetchResult;
996
985
  this.debug?.("[module runner] externalizing", externalize);
@@ -1001,10 +990,10 @@ ${getStack()}`
1001
990
  if (code == null) {
1002
991
  const importer = callstack[callstack.length - 2];
1003
992
  throw new Error(
1004
- `[module runner] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`
993
+ `[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`
1005
994
  );
1006
995
  }
1007
- const modulePath = cleanUrl(file || moduleUrl), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
996
+ const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
1008
997
  filename: isWindows ? toWindowsPath(filename) : filename,
1009
998
  dirname: isWindows ? toWindowsPath(dirname2) : dirname2,
1010
999
  url: href,
@@ -1016,7 +1005,9 @@ ${getStack()}`
1016
1005
  },
1017
1006
  // should be replaced during transformation
1018
1007
  glob() {
1019
- throw new Error('[module runner] "import.meta.glob" is not supported.');
1008
+ throw new Error(
1009
+ '[module runner] "import.meta.glob" is statically replaced during file transformation. Make sure to reference it by the full name.'
1010
+ );
1020
1011
  }
1021
1012
  }, exports = /* @__PURE__ */ Object.create(null);
1022
1013
  Object.defineProperty(exports, Symbol.toStringTag, {
@@ -1030,7 +1021,7 @@ ${getStack()}`
1030
1021
  get: () => {
1031
1022
  if (!this.hmrClient)
1032
1023
  throw new Error("[module runner] HMR client was destroyed.");
1033
- return this.debug?.("[module runner] creating hmr context for", moduleUrl), hotContext ||= new HMRContext(this.hmrClient, moduleUrl), hotContext;
1024
+ return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
1034
1025
  },
1035
1026
  set: (value) => {
1036
1027
  hotContext = value;
@@ -1043,7 +1034,7 @@ ${getStack()}`
1043
1034
  [ssrExportAllKey]: (obj) => exportAll(exports, obj),
1044
1035
  [ssrImportMetaKey]: meta
1045
1036
  };
1046
- return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, id), exports;
1037
+ return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
1047
1038
  }
1048
1039
  }
1049
1040
  function exportAll(exports, sourceModule) {
@@ -1061,6 +1052,7 @@ function exportAll(exports, sourceModule) {
1061
1052
  }
1062
1053
  }
1063
1054
  class ESModulesEvaluator {
1055
+ startOffset = asyncFunctionDeclarationPaddingLineCount;
1064
1056
  async runInlinedModule(context, code) {
1065
1057
  await new AsyncFunction(
1066
1058
  ssrModuleExportsKey,
@@ -1122,7 +1114,7 @@ class RemoteRunnerTransport {
1122
1114
  }
1123
1115
  export {
1124
1116
  ESModulesEvaluator,
1125
- ModuleCacheMap,
1117
+ EvaluatedModules,
1126
1118
  ModuleRunner,
1127
1119
  RemoteRunnerTransport,
1128
1120
  ssrDynamicImportKey,