vitest 4.1.12 → 5.1.0

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.
Files changed (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -1,10 +1,11 @@
1
1
  import { ModuleEvaluator, ModuleRunnerImportMeta, ModuleRunnerContext, EvaluatedModuleNode } from 'vite/module-runner';
2
- import { V as VitestEvaluatedModules } from './chunks/evaluatedModules.d.BxJ5omdx.js';
2
+ import { G as GetterTracker } from './chunks/rpc.d.3FOhdFx8.js';
3
+ import { RuntimeRPC } from './index.js';
4
+ import { EvaluatedModules as VitestEvaluatedModules } from './index.js';
3
5
  import vm from 'node:vm';
4
- import { R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
5
- import '@vitest/runner';
6
- import '@vitest/snapshot';
7
- import './chunks/traces.d.D2T_R8rx.js';
6
+ import './chunks/config.d.B3YV4t0O.js';
7
+ import 'vitest/optional-runtime-types.js';
8
+ import 'tinybench';
8
9
 
9
10
  type ModuleExecutionInfo = Map<string, ModuleExecutionInfoEntry>;
10
11
  interface ModuleExecutionInfoEntry {
@@ -17,6 +18,31 @@ interface ModuleExecutionInfoEntry {
17
18
  importer?: string;
18
19
  }
19
20
 
21
+ /**
22
+ * Worker-wide cache of V8 code cache buffers for externalized modules.
23
+ *
24
+ * vm pools create a fresh executor per test file, so every externalized
25
+ * module is compiled and evaluated again in each fresh context. The compiled
26
+ * code has no per-context state — reusing its V8 code cache skips the
27
+ * re-parse/re-compile while the evaluation still happens per context.
28
+ *
29
+ * Entries are keyed by the module identifier and guarded by the exact source
30
+ * text, so an invalidated module that produces different code simply replaces
31
+ * its entry.
32
+ */
33
+ declare class CodeCache {
34
+ private entries;
35
+ get(identifier: string, source: string): Buffer | undefined;
36
+ /**
37
+ * Stores the code cache produced by `produce` unless an entry for the same
38
+ * source already exists. A `produce` failure is recorded as an empty entry,
39
+ * so it is not retried on every fresh context.
40
+ */
41
+ store(identifier: string, source: string, produce: () => Buffer): void;
42
+ delete(identifier: string): void;
43
+ clear(): void;
44
+ }
45
+
20
46
  declare class FileMap {
21
47
  private fsCache;
22
48
  private fsBufferCache;
@@ -47,11 +73,30 @@ declare class VMModule {
47
73
  interface ExternalModulesExecutorOptions {
48
74
  context: vm.Context;
49
75
  fileMap: FileMap;
76
+ codeCache?: CodeCache;
77
+ resolveCache?: Map<string, string>;
78
+ moduleInfoCache?: Map<string, ModuleInformation>;
50
79
  packageCache: Map<string, any>;
51
80
  transform: RuntimeRPC["transform"];
52
81
  interopDefault?: boolean;
53
82
  viteClientModule: Record<string, unknown>;
54
83
  }
84
+ interface ModuleInformation {
85
+ type: "data" | "builtin" | "vite" | "wasm" | "module" | "commonjs" | "network";
86
+ url: string;
87
+ path: string;
88
+ exists?: boolean;
89
+ }
90
+ type SyncModuleDisposition = {
91
+ kind: "ready";
92
+ module: VMModule;
93
+ } | {
94
+ kind: "json";
95
+ code: string;
96
+ } | {
97
+ kind: "source";
98
+ code: string;
99
+ };
55
100
  declare class ExternalModulesExecutor {
56
101
  #private;
57
102
  private options;
@@ -60,15 +105,23 @@ declare class ExternalModulesExecutor {
60
105
  private vite;
61
106
  private context;
62
107
  private fs;
108
+ readonly codeCache: CodeCache | undefined;
63
109
  private resolvers;
64
110
  constructor(options: ExternalModulesExecutorOptions);
111
+ syncBuiltinESMExports(): void;
65
112
  import(identifier: string): Promise<object>;
66
113
  require(identifier: string): any;
67
114
  createRequire(identifier: string): NodeJS.Require;
115
+ private shouldRequireAsEsm;
116
+ private requireEsm;
117
+ resolveSyncSpecifier: (specifier: string, referencer: string) => string;
118
+ materializeSyncModule: (identifier: string, forceEsmSource: boolean) => SyncModuleDisposition;
68
119
  importModuleDynamically: (specifier: string, referencer: VMModule) => Promise<VMModule>;
69
120
  resolveModule: (specifier: string, referencer: string) => Promise<VMModule>;
70
121
  resolve(specifier: string, parent: string): string;
71
122
  private getModuleInformation;
123
+ private resolveModuleInformation;
124
+ private assertModuleExists;
72
125
  private createModule;
73
126
  private get isNetworkSupported();
74
127
  }
@@ -98,11 +151,15 @@ interface VitestVmOptions {
98
151
 
99
152
  interface VitestModuleEvaluatorOptions {
100
153
  evaluatedModules?: VitestEvaluatedModules;
154
+ metaEnv?: ModuleRunnerImportMeta["env"];
101
155
  interopDefault?: boolean | undefined;
156
+ injectCjsGlobals?: boolean | undefined;
102
157
  moduleExecutionInfo?: ModuleExecutionInfo;
103
158
  getCurrentTestFilepath?: () => string | undefined;
159
+ getEnvironmentName?: () => string;
104
160
  compiledFunctionArgumentsNames?: string[];
105
161
  compiledFunctionArgumentsValues?: unknown[];
162
+ getterTracker?: GetterTracker;
106
163
  }
107
164
  declare class VitestModuleEvaluator implements ModuleEvaluator {
108
165
  private options;
@@ -111,6 +168,8 @@ declare class VitestModuleEvaluator implements ModuleEvaluator {
111
168
  private vm;
112
169
  private compiledFunctionArgumentsNames?;
113
170
  private compiledFunctionArgumentsValues;
171
+ private getterTracker;
172
+ static EXPORTS_MAX_INVOCATIONS: number;
114
173
  private primitives;
115
174
  private debug;
116
175
  private _otel;
@@ -2,7 +2,7 @@ import { isBuiltin, createRequire } from 'node:module';
2
2
  import { pathToFileURL, fileURLToPath } from 'node:url';
3
3
  import vm from 'node:vm';
4
4
  import { ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey } from 'vite/module-runner';
5
- import { T as Traces } from './chunks/traces.DT5aQ62U.js';
5
+ import { Traces } from './traces.js';
6
6
 
7
7
  const performanceNow = performance.now.bind(performance);
8
8
  class ModuleDebug {
@@ -32,12 +32,33 @@ class ModuleDebug {
32
32
  }
33
33
 
34
34
  const isWindows = process.platform === "win32";
35
+ // Compiled scripts of inlined modules, shared across vm contexts: vm pools
36
+ // evaluate every module again in each fresh context, but the compiled script
37
+ // holds no per-context state (Vite rewrites dynamic imports to
38
+ // `__vite_ssr_dynamic_import__`, so no per-context import callback is baked
39
+ // in) — only its evaluation has to happen per context. Keyed by module id
40
+ // (`mock:` ids stay distinct from their originals) and Vite environment: one
41
+ // worker can run files of different environments, which transform the same id
42
+ // differently.
43
+ const vmInlineScriptCache = /* @__PURE__ */ new Map();
44
+ function getVmInlineScript(environment, id, wrappedCode, options) {
45
+ const key = `${environment}:${id}`;
46
+ let script = vmInlineScriptCache.get(key);
47
+ if (!script) {
48
+ script = new vm.Script(wrappedCode, options);
49
+ vmInlineScriptCache.set(key, script);
50
+ }
51
+ return script;
52
+ }
35
53
  class VitestModuleEvaluator {
54
+ options;
36
55
  stubs = {};
37
- env = createImportMetaEnvProxy();
56
+ env;
38
57
  vm;
39
58
  compiledFunctionArgumentsNames;
40
59
  compiledFunctionArgumentsValues = [];
60
+ getterTracker;
61
+ static EXPORTS_MAX_INVOCATIONS = 1e6;
41
62
  primitives;
42
63
  debug = new ModuleDebug();
43
64
  _otel;
@@ -45,6 +66,7 @@ class VitestModuleEvaluator {
45
66
  constructor(vmOptions, options = {}) {
46
67
  this.options = options;
47
68
  this._otel = options.traces || new Traces({ enabled: false });
69
+ this.env = options.metaEnv ?? createImportMetaEnvProxy();
48
70
  this.vm = vmOptions;
49
71
  this.stubs = getDefaultRequestStubs(vmOptions?.context);
50
72
  this._evaluatedModules = options.evaluatedModules;
@@ -56,6 +78,7 @@ class VitestModuleEvaluator {
56
78
  Proxy,
57
79
  Reflect
58
80
  };
81
+ this.getterTracker = options.getterTracker;
59
82
  }
60
83
  convertIdToImportUrl(id) {
61
84
  // TODO: vitest returns paths for external modules, but Vite returns file://
@@ -163,11 +186,28 @@ class VitestModuleEvaluator {
163
186
  async _runInlinedModule(context, code, module, span) {
164
187
  const meta = context[ssrImportMetaKey];
165
188
  meta.env = this.env;
166
- if (this.options.getCurrentTestFilepath?.() === module.file) {
167
- const globalNamespace = this.vm?.context || globalThis;
168
- Object.defineProperty(meta, "vitest", { get: () => globalNamespace.__vitest_index__ });
189
+ const globalNamespace = this.vm?.context || globalThis;
190
+ // `import.meta` defines evaluated by the runtime defines script;
191
+ // `import.meta.env.*` entries are applied through `process.env` instead
192
+ const metaDefines = globalNamespace.__vitest_worker__?.metaDefines;
193
+ if (metaDefines) for (const key in metaDefines) {
194
+ const segments = key.split(".");
195
+ let target = meta;
196
+ for (let i = 0; i < segments.length - 1; i++) target = target[segments[i]] || (target[segments[i]] = {});
197
+ target[segments[segments.length - 1]] = metaDefines[key];
169
198
  }
199
+ if (this.options.getCurrentTestFilepath?.() === module.file) Object.defineProperty(meta, "vitest", {
200
+ // @ts-expect-error injected untyped global
201
+ get: () => globalNamespace.__vitest_index__ });
170
202
  span.setAttribute("code.file.path", meta.filename);
203
+ const __vite_ssr_exportName__ = context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(context[ssrModuleExportsKey], name, {
204
+ enumerable: true,
205
+ configurable: true,
206
+ get: getter
207
+ }));
208
+ let __vite_track_exportName__;
209
+ const getterTracker = this.getterTracker;
210
+ if (getterTracker) __vite_track_exportName__ = getterTracker.createTracker(module.id, __vite_ssr_exportName__);
171
211
  const argumentsList = [
172
212
  ssrModuleExportsKey,
173
213
  ssrImportMetaKey,
@@ -176,52 +216,52 @@ class VitestModuleEvaluator {
176
216
  ssrExportAllKey,
177
217
  "__vite_ssr_exportName__"
178
218
  ];
179
- const cjsGlobals = this._createCJSGlobals(context, module, span);
180
- argumentsList.push(
181
- // TODO@discuss deprecate in Vitest 5, remove in Vitest 6(?)
182
- // backwards compat for vite-node
183
- "__filename",
184
- "__dirname",
185
- "module",
186
- "exports",
187
- "require"
188
- );
219
+ const argumentsValues = [
220
+ context[ssrModuleExportsKey],
221
+ context[ssrImportMetaKey],
222
+ context[ssrImportKey],
223
+ context[ssrDynamicImportKey],
224
+ context[ssrExportAllKey],
225
+ __vite_track_exportName__ || __vite_ssr_exportName__
226
+ ];
227
+ // TODO@discuss switch the default in Vitest 6(?)
228
+ // backwards compat for vite-node
229
+ const injectCjsGlobals = this.options.injectCjsGlobals !== false || module.meta?.moduleType === "cjs";
230
+ if (injectCjsGlobals) {
231
+ const cjsGlobals = this._createCJSGlobals(context, module, span);
232
+ argumentsList.push("__filename", "__dirname", "module", "exports", "require");
233
+ argumentsValues.push(cjsGlobals.__filename, cjsGlobals.__dirname, cjsGlobals.module, cjsGlobals.exports, cjsGlobals.require);
234
+ }
189
235
  if (this.compiledFunctionArgumentsNames) argumentsList.push(...this.compiledFunctionArgumentsNames);
236
+ if (this.compiledFunctionArgumentsValues) argumentsValues.push(...this.compiledFunctionArgumentsValues);
190
237
  span.setAttribute("vitest.module.arguments", argumentsList);
191
238
  // add 'use strict' since ESM enables it by default
192
239
  const codeDefinition = `'use strict';async (${argumentsList.join(",")})=>{{`;
193
240
  const wrappedCode = `${codeDefinition}${code}\n}}`;
194
241
  const options = {
242
+ // use original id for auto spy module (vi.mock(..., { spy: true }))
195
243
  filename: module.id.startsWith("mock:") ? module.id.slice(5) : module.id,
196
244
  lineOffset: 0,
197
245
  columnOffset: -codeDefinition.length
198
246
  };
199
247
  // this will always be 1 element because it's cached after load
200
248
  const importer = module.importers.values().next().value;
249
+ // Initialize execution info in case worker exited before module evaluation finished
250
+ this.options.moduleExecutionInfo?.set(options.filename, {
251
+ duration: 0,
252
+ selfTime: 0,
253
+ startOffset: codeDefinition.length,
254
+ importer
255
+ });
201
256
  const finishModuleExecutionInfo = this.debug.startCalculateModuleExecutionInfo(options.filename, {
202
257
  startOffset: codeDefinition.length,
203
258
  importer
204
259
  });
205
260
  try {
206
- await (this.vm ? vm.runInContext(wrappedCode, this.vm.context, options) : vm.runInThisContext(wrappedCode, options))(
207
- context[ssrModuleExportsKey],
208
- context[ssrImportMetaKey],
209
- context[ssrImportKey],
210
- context[ssrDynamicImportKey],
211
- context[ssrExportAllKey],
212
- // vite 7 support, remove when vite 7+ is supported
213
- context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(context[ssrModuleExportsKey], name, {
214
- enumerable: true,
215
- configurable: true,
216
- get: getter
217
- })),
218
- cjsGlobals.__filename,
219
- cjsGlobals.__dirname,
220
- cjsGlobals.module,
221
- cjsGlobals.exports,
222
- cjsGlobals.require,
223
- ...this.compiledFunctionArgumentsValues
224
- );
261
+ await (this.vm ? getVmInlineScript(this.options.getEnvironmentName?.() ?? "", module.id, wrappedCode, options).runInContext(this.vm.context) : vm.runInThisContext(wrappedCode, options))(...argumentsValues);
262
+ } catch (error) {
263
+ if (!injectCjsGlobals) throw enhanceMissingCjsGlobalsError(error);
264
+ throw error;
225
265
  } finally {
226
266
  // moduleExecutionInfo needs to use Node filename instead of the normalized one
227
267
  // because we rely on this behaviour in coverage-v8, for example
@@ -285,46 +325,46 @@ function removeStyle(id) {
285
325
  const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
286
326
  if (sheet) document.head.removeChild(sheet);
287
327
  }
328
+ function createHotContext() {
329
+ return {
330
+ data: {},
331
+ accept: () => {},
332
+ acceptExports: () => {},
333
+ prune: () => {},
334
+ dispose: () => {},
335
+ decline: () => {},
336
+ invalidate: () => {},
337
+ on: () => {},
338
+ off: () => {},
339
+ send: () => {}
340
+ };
341
+ }
288
342
  const defaultClientStub = {
289
343
  injectQuery: (id) => id,
290
- createHotContext: () => {
291
- return {
292
- accept: () => {},
293
- prune: () => {},
294
- dispose: () => {},
295
- decline: () => {},
296
- invalidate: () => {},
297
- on: () => {},
298
- send: () => {}
299
- };
300
- },
344
+ createHotContext,
301
345
  updateStyle: () => {},
302
346
  removeStyle: () => {}
303
347
  };
304
348
  function getDefaultRequestStubs(context) {
305
- if (!context) {
306
- const clientStub = {
307
- ...defaultClientStub,
308
- updateStyle,
309
- removeStyle
310
- };
311
- return { "/@vite/client": clientStub };
312
- }
313
- const clientStub = vm.runInContext(`(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`, context)(defaultClientStub);
314
- return { "/@vite/client": clientStub };
349
+ if (!context) return { "/@vite/client": {
350
+ ...defaultClientStub,
351
+ updateStyle,
352
+ removeStyle
353
+ } };
354
+ return { "/@vite/client": vm.runInContext(`(defaultClient) => ({ ...defaultClient, createHotContext: ${createHotContext.toString()}, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`, context)(defaultClientStub) };
315
355
  }
316
- function exportAll(exports$1, sourceModule) {
356
+ function exportAll(exports, sourceModule) {
317
357
  // #1120 when a module exports itself it causes
318
358
  // call stack error
319
- if (exports$1 === sourceModule) return;
359
+ if (exports === sourceModule) return;
320
360
  if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) return;
321
- for (const key in sourceModule) if (key !== "default" && !(key in exports$1)) try {
322
- defineExport(exports$1, key, () => sourceModule[key]);
361
+ for (const key in sourceModule) if (key !== "default" && !(key in exports)) try {
362
+ defineExport(exports, key, () => sourceModule[key]);
323
363
  } catch {}
324
364
  }
325
365
  // keep consistency with Vite on how exports are defined
326
- function defineExport(exports$1, key, value) {
327
- Object.defineProperty(exports$1, key, {
366
+ function defineExport(exports, key, value) {
367
+ Object.defineProperty(exports, key, {
328
368
  enumerable: true,
329
369
  configurable: true,
330
370
  get: value
@@ -339,7 +379,7 @@ function interopModule(mod) {
339
379
  defaultExport: mod
340
380
  };
341
381
  let defaultExport = "default" in mod ? mod.default : mod;
342
- if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
382
+ if (!isPrimitive(defaultExport) && defaultExport.__esModule) {
343
383
  mod = defaultExport;
344
384
  if ("default" in defaultExport) defaultExport = defaultExport.default;
345
385
  }
@@ -348,6 +388,26 @@ function interopModule(mod) {
348
388
  defaultExport
349
389
  };
350
390
  }
391
+ const CJS_GLOBALS_REFERENCE_ERROR_RE = /^(module|exports|require|__filename|__dirname) is not defined$/;
392
+ const ESM_HINTS = {
393
+ module: "use \"export\" declarations instead of \"module.exports\"",
394
+ exports: "use \"export\" declarations instead of \"exports\"",
395
+ require: "use \"import\" declarations or \"createRequire(import.meta.url)\" instead of \"require\"",
396
+ __filename: "use \"import.meta.filename\" instead of \"__filename\"",
397
+ __dirname: "use \"import.meta.dirname\" instead of \"__dirname\""
398
+ };
399
+ function enhanceMissingCjsGlobalsError(error) {
400
+ if (error == null || typeof error !== "object") return error;
401
+ const referenceError = error;
402
+ if (referenceError.name !== "ReferenceError" || typeof referenceError.message !== "string") return error;
403
+ // the message is anchored, so already enhanced errors are not enhanced twice
404
+ const name = referenceError.message.match(CJS_GLOBALS_REFERENCE_ERROR_RE)?.[1];
405
+ if (!name) return error;
406
+ const message = `${referenceError.message}\n\n"${name}" is a CommonJS variable that is not available in ES modules, and "injectCjsGlobals" is disabled. If this module is meant to be an ES module, ${ESM_HINTS[name]}. If it is meant to be a CommonJS module, use the ".cjs" file extension, set "type": "commonjs" in the nearest package.json, or externalize it with "server.deps.external".`;
407
+ if (typeof referenceError.stack === "string") referenceError.stack = referenceError.stack.replace(referenceError.message, message);
408
+ referenceError.message = message;
409
+ return error;
410
+ }
351
411
  const VALID_ID_PREFIX = `/@id/`;
352
412
  const NULL_BYTE_PLACEHOLDER = `__x00__`;
353
413
  function wrapId(id) {