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
@@ -0,0 +1,1329 @@
1
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2
+ import v8 from 'node:v8';
3
+ import vm, { isContext, runInContext } from 'node:vm';
4
+ import { l as loadEnvironment, a as listenForErrors, e as emitModuleRunner } from './init.CO4AB7HZ.js';
5
+ import { distDir } from '../path.js';
6
+ import { createCustomConsole } from './console.CQZ877Hi.js';
7
+ import fs__default from 'node:fs';
8
+ import { createRequire, Module, isBuiltin } from 'node:module';
9
+ import { d as dirname, k as extname, b as basename, C as CSS_LANGS_RE, l as KNOWN_ASSET_RE, t as toArray, m as splitFileAndPostfix, n as normalize, o as isBareImport, r as resolve } from './pathe.M-eThtNZ.zq3TM4NT.js';
10
+ import { l as lookupPackageScopeType } from './resolver.BzpmeQeT.js';
11
+ import { initSync, parse } from 'es-module-lexer';
12
+ import { dirname as dirname$1 } from 'node:path';
13
+ import { V as VITEST_VM_CONTEXT_SYMBOL, s as startVitestModuleRunner, c as createNodeImportMeta } from './index.Bi0NXYPf.js';
14
+ import { getDefaultRequestStubs } from '../module-evaluator.js';
15
+ import { b as setupEnv } from './setup-common.CqAQCXzx.js';
16
+ import { p as provideWorkerState } from './utils.DYj33du9.js';
17
+
18
+ /**
19
+ * Worker-wide cache of V8 code cache buffers for externalized modules.
20
+ *
21
+ * vm pools create a fresh executor per test file, so every externalized
22
+ * module is compiled and evaluated again in each fresh context. The compiled
23
+ * code has no per-context state — reusing its V8 code cache skips the
24
+ * re-parse/re-compile while the evaluation still happens per context.
25
+ *
26
+ * Entries are keyed by the module identifier and guarded by the exact source
27
+ * text, so an invalidated module that produces different code simply replaces
28
+ * its entry.
29
+ */
30
+ class CodeCache {
31
+ entries = /* @__PURE__ */ new Map();
32
+ get(identifier, source) {
33
+ const entry = this.entries.get(identifier);
34
+ if (entry && entry.source === source) return entry.data;
35
+ }
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, source, produce) {
42
+ const entry = this.entries.get(identifier);
43
+ if (entry && entry.source === source) return;
44
+ let data;
45
+ try {
46
+ data = produce();
47
+ } catch {
48
+ data = void 0;
49
+ }
50
+ this.entries.set(identifier, {
51
+ source,
52
+ data
53
+ });
54
+ }
55
+ delete(identifier) {
56
+ this.entries.delete(identifier);
57
+ }
58
+ clear() {
59
+ this.entries.clear();
60
+ }
61
+ }
62
+ /**
63
+ * `node:v8` as seen inside the vm context: changing V8 flags invalidates every
64
+ * code cache produced so far, so `setFlagsFromString` also empties ours.
65
+ */
66
+ function createV8ModuleWithCacheReset(v8, codeCache) {
67
+ const patched = Object.create(Object.getPrototypeOf(v8), Object.getOwnPropertyDescriptors(v8));
68
+ patched.setFlagsFromString = function setFlagsFromString(flags) {
69
+ v8.setFlagsFromString(flags);
70
+ codeCache.clear();
71
+ };
72
+ return patched;
73
+ }
74
+
75
+ function interopCommonJsModule(interopDefault, mod) {
76
+ if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
77
+ keys: [],
78
+ moduleExports: {},
79
+ defaultExport: mod
80
+ };
81
+ if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
82
+ const defaultKets = Object.keys(mod.default);
83
+ const moduleKeys = Object.keys(mod);
84
+ const allKeys = /* @__PURE__ */ new Set([...defaultKets, ...moduleKeys]);
85
+ allKeys.delete("default");
86
+ // the namespace always provides its own synthetic 'module.exports'
87
+ // export, shadowing a real property of that name (Node parity)
88
+ allKeys.delete("module.exports");
89
+ return {
90
+ keys: Array.from(allKeys),
91
+ moduleExports: new Proxy(mod, { get(mod, prop) {
92
+ return mod[prop] ?? mod.default?.[prop];
93
+ } }),
94
+ defaultExport: mod
95
+ };
96
+ }
97
+ return {
98
+ keys: Object.keys(mod).filter((key) => key !== "default" && key !== "module.exports"),
99
+ moduleExports: mod,
100
+ defaultExport: mod
101
+ };
102
+ }
103
+ function isPrimitive(obj) {
104
+ return !(obj != null && (typeof obj === "object" || typeof obj === "function"));
105
+ }
106
+ const SyntheticModule = vm.SyntheticModule;
107
+ const SourceTextModule = vm.SourceTextModule;
108
+ // `SourceTextModule#hasAsyncGraph` marks the Node 24.9+ vm APIs required to
109
+ // load an ES module graph synchronously (`moduleRequests`, `linkRequests`,
110
+ // `instantiate`, synchronously-completing `evaluate`) — the same APIs Node
111
+ // itself uses for require(esm)
112
+ const supportsSyncEsmEvaluate = typeof SourceTextModule?.prototype.hasAsyncGraph === "function";
113
+ let lexerInitialized = false;
114
+ // Returns true when `source` contains ESM syntax: static import/export
115
+ // statements or `import.meta` (dynamic import is allowed in CJS and does not
116
+ // count). Returns false when the lexer cannot parse the source at all —
117
+ // native ESM would fail on it as well, so the CJS error should surface.
118
+ function hasEsmSyntax(source) {
119
+ if (!lexerInitialized) {
120
+ initSync();
121
+ lexerInitialized = true;
122
+ }
123
+ try {
124
+ return parse(source)[3];
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+ // mirrors Node's require(esm) error codes so user-side catches work uniformly
130
+ function createRequireAsyncModuleError(identifier, detail) {
131
+ const error = /* @__PURE__ */ new Error(`require() cannot be used to load ES Module ${identifier}: ${detail}. Use import() instead.`);
132
+ error.code = "ERR_REQUIRE_ASYNC_MODULE";
133
+ return error;
134
+ }
135
+ function createConcurrentRequireError(identifier) {
136
+ const error = /* @__PURE__ */ new Error(`Cannot require() ES Module ${identifier} synchronously: it is currently being loaded by a concurrent import(). Await that import before calling require(), or import this module instead of requiring it.`);
137
+ error.code = "ERR_REQUIRE_ESM";
138
+ return error;
139
+ }
140
+ let activeVmExecutor;
141
+ function setActiveVmExecutor(executor) {
142
+ activeVmExecutor = executor;
143
+ }
144
+ async function activeImportModuleDynamically(specifier, referencer) {
145
+ if (!activeVmExecutor) throw new Error(`Cannot import "${specifier}": the test context was torn down.`);
146
+ return activeVmExecutor.importModuleDynamically(specifier, referencer);
147
+ }
148
+ // Node never collects a vm context in which multiple scripts installed
149
+ // closures, and `vm.SourceTextModule`s are pinned by the realm's base object
150
+ // list: the ContextifyContext/ModuleWrap wrappers keep the whole context
151
+ // reachable even through forced full GCs, so a long-lived vm worker
152
+ // accumulates every test file's world until it hits `vmMemoryLimit` and gets
153
+ // recycled, destroying the worker's compile caches with it. Clearing what the
154
+ // test file added to the global object (and the DOM) caps what a pinned
155
+ // context retains. Pristine globals are kept so that work queued before the
156
+ // teardown (jsdom events, worker-scoped fixture cleanups) can still run.
157
+ const captureKeysScript = new vm.Script(`Object.getOwnPropertyNames(globalThis).concat(Object.getOwnPropertySymbols(globalThis))`, { filename: "virtual:vitest-capture-context-keys.js" });
158
+ function captureContextKeys(context) {
159
+ try {
160
+ return new Set(captureKeysScript.runInContext(context));
161
+ } catch {
162
+ return /* @__PURE__ */ new Set();
163
+ }
164
+ }
165
+ const stripScript = new vm.Script(`(initialKeys) => {
166
+ const g = globalThis
167
+ try { g.document.body.textContent = '' } catch {}
168
+ try { g.document.head.textContent = '' } catch {}
169
+ let keys = []
170
+ try { keys = Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g)) } catch {}
171
+ for (const key of keys) {
172
+ if (initialKeys.has(key)) continue
173
+ try { delete g[key] } catch {}
174
+ }
175
+ }`, { filename: "virtual:vitest-strip-context.js" });
176
+ function stripDisposedContext(context, initialKeys) {
177
+ try {
178
+ stripScript.runInContext(context)(initialKeys);
179
+ } catch {}
180
+ }
181
+
182
+ const _require = createRequire(import.meta.url);
183
+ // Thrown when the CJS parser rejects a .js file that may contain ESM syntax.
184
+ // `loadCommonJSModule` catches it and retries the file as an ES module,
185
+ // mirroring Node's own require() ESM-syntax fallback for .js files without
186
+ // an ESM package scope. The original error is in `cause`.
187
+ class CjsParseError extends SyntaxError {
188
+ name = "CjsParseError";
189
+ constructor(cause) {
190
+ super(cause.message, { cause });
191
+ }
192
+ }
193
+ const requiresCache = /* @__PURE__ */ new WeakMap();
194
+ // Compiled scripts of commonjs modules, shared across vm contexts: only the
195
+ // evaluation has to happen per context. No invalidation is needed because
196
+ // watch mode reruns destroy the worker.
197
+ const cjsScriptCache = /* @__PURE__ */ new Map();
198
+ class CommonjsExecutor {
199
+ context;
200
+ requireCache = /* @__PURE__ */ new Map();
201
+ publicRequireCache = this.createProxyCache();
202
+ moduleCache = /* @__PURE__ */ new Map();
203
+ builtinCache = Object.create(null);
204
+ extensions = Object.create(null);
205
+ fs;
206
+ codeCache;
207
+ Module;
208
+ interopDefault;
209
+ shouldRequireAsEsm;
210
+ requireEsm;
211
+ // .js files that the ESM-syntax fallback already loaded as ES modules,
212
+ // so later require() calls skip the guaranteed-to-fail CJS parse
213
+ esmSyntaxFallbackFiles = /* @__PURE__ */ new Set();
214
+ constructor(options) {
215
+ this.context = options.context;
216
+ this.fs = options.fileMap;
217
+ this.codeCache = options.codeCache;
218
+ this.interopDefault = options.interopDefault;
219
+ this.shouldRequireAsEsm = options.shouldRequireAsEsm;
220
+ this.requireEsm = options.requireEsm;
221
+ const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
222
+ // oxlint-disable-next-line typescript/no-this-alias
223
+ const executor = this;
224
+ this.Module = class Module$1 {
225
+ exports;
226
+ isPreloading = false;
227
+ id;
228
+ filename;
229
+ loaded;
230
+ parent;
231
+ children = [];
232
+ path;
233
+ paths = [];
234
+ constructor(id = "", parent) {
235
+ this.exports = primitives.Object.create(primitives.Object.prototype);
236
+ // in our case the path should always be resolved already
237
+ this.path = dirname(id);
238
+ this.id = id;
239
+ this.filename = id;
240
+ this.loaded = false;
241
+ this.parent = parent;
242
+ }
243
+ get require() {
244
+ const require = requiresCache.get(this);
245
+ if (require) return require;
246
+ const _require = Module$1.createRequire(this.id);
247
+ requiresCache.set(this, _require);
248
+ return _require;
249
+ }
250
+ static getSourceMapsSupport = () => ({
251
+ enabled: false,
252
+ nodeModules: false,
253
+ generatedCode: false
254
+ });
255
+ static setSourceMapsSupport = () => {
256
+ // noop
257
+ };
258
+ static register = () => {
259
+ throw new Error(`[vitest] "register" is not available when running in Vitest.`);
260
+ };
261
+ static registerHooks = () => {
262
+ throw new Error(`[vitest] "registerHooks" is not available when running in Vitest.`);
263
+ };
264
+ _compile(code, filename) {
265
+ const cjsModule = Module$1.wrap(code);
266
+ const codeCache = executor.codeCache;
267
+ let script = cjsScriptCache.get(filename);
268
+ if (!script) {
269
+ const cachedData = codeCache?.get(filename, cjsModule);
270
+ // the dynamic import callback is a static function (the executor is
271
+ // resolved when it is called), so the compiled script holds no
272
+ // per-context state and can be reused by every vm context
273
+ try {
274
+ script = new vm.Script(cjsModule, {
275
+ filename,
276
+ cachedData,
277
+ importModuleDynamically: activeImportModuleDynamically
278
+ });
279
+ } catch (error) {
280
+ if (error instanceof SyntaxError && executor.canFallbackToEsm(filename)) throw new CjsParseError(error);
281
+ throw error;
282
+ }
283
+ if (cachedData && script.cachedDataRejected) codeCache.delete(filename);
284
+ // @ts-expect-error mark script with current identifier
285
+ script.identifier = filename;
286
+ cjsScriptCache.set(filename, script);
287
+ }
288
+ const fn = script.runInContext(executor.context);
289
+ const __dirname = dirname(filename);
290
+ executor.requireCache.set(filename, this);
291
+ try {
292
+ fn.call(this.exports, this.exports, this.require, this, filename, __dirname);
293
+ return this.exports;
294
+ } finally {
295
+ this.loaded = true;
296
+ // store after execution so the code cache carries the compiled
297
+ // module body, not only the lazily-parsed wrapper
298
+ codeCache?.store(filename, cjsModule, () => script.createCachedData());
299
+ }
300
+ }
301
+ // exposed for external use, Node.js does the opposite
302
+ static _load = (request, parent, _isMain) => {
303
+ return Module$1.createRequire(parent?.filename ?? request)(request);
304
+ };
305
+ static wrap = (script) => {
306
+ return Module$1.wrapper[0] + script + Module$1.wrapper[1];
307
+ };
308
+ static wrapper = new primitives.Array("(function (exports, require, module, __filename, __dirname) { ", "\n});");
309
+ static builtinModules = Module.builtinModules;
310
+ static findSourceMap = Module.findSourceMap;
311
+ static SourceMap = Module.SourceMap;
312
+ static syncBuiltinESMExports = Module.syncBuiltinESMExports;
313
+ static _cache = executor.publicRequireCache;
314
+ static _extensions = executor.extensions;
315
+ static createRequire = (filename) => {
316
+ return executor.createRequire(filename);
317
+ };
318
+ static runMain = () => {
319
+ throw new primitives.Error("[vitest] \"runMain\" is not implemented.");
320
+ };
321
+ // @ts-expect-error not typed
322
+ static _resolveFilename = Module._resolveFilename;
323
+ // @ts-expect-error not typed
324
+ static _findPath = Module._findPath;
325
+ // @ts-expect-error not typed
326
+ static _initPaths = Module._initPaths;
327
+ // @ts-expect-error not typed
328
+ static _preloadModules = Module._preloadModules;
329
+ // @ts-expect-error not typed
330
+ static _resolveLookupPaths = Module._resolveLookupPaths;
331
+ // @ts-expect-error not typed
332
+ static globalPaths = Module.globalPaths;
333
+ static isBuiltin = Module.isBuiltin;
334
+ static constants = Module.constants;
335
+ static enableCompileCache = Module.enableCompileCache;
336
+ static getCompileCacheDir = Module.getCompileCacheDir;
337
+ static flushCompileCache = Module.flushCompileCache;
338
+ static stripTypeScriptTypes = Module.stripTypeScriptTypes;
339
+ static findPackageJSON = Module.findPackageJSON;
340
+ static Module = Module$1;
341
+ };
342
+ this.extensions[".js"] = this.requireJs;
343
+ this.extensions[".json"] = this.requireJson;
344
+ }
345
+ requireJs = (m, filename) => {
346
+ const content = this.fs.readFile(filename);
347
+ const code = content.startsWith("#!") ? `//${content.slice(2)}` : content;
348
+ m._compile(code, filename);
349
+ };
350
+ requireJson = (m, filename) => {
351
+ const code = this.fs.readFile(filename);
352
+ m.exports = JSON.parse(code);
353
+ };
354
+ static cjsConditions;
355
+ static getCjsConditions() {
356
+ if (!CommonjsExecutor.cjsConditions) CommonjsExecutor.cjsConditions = parseCjsConditions(process.execArgv, process.env.NODE_OPTIONS, supportsSyncEsmEvaluate);
357
+ return CommonjsExecutor.cjsConditions;
358
+ }
359
+ createRequire = (filename) => {
360
+ const _require = createRequire(filename);
361
+ const resolve = (id, options) => {
362
+ return _require.resolve(id, {
363
+ ...options,
364
+ // Works on Node 22.12+ where _resolveFilename supports conditions.
365
+ // Silently ignored on older Node versions.
366
+ conditions: CommonjsExecutor.getCjsConditions()
367
+ });
368
+ };
369
+ const require = ((id) => {
370
+ const resolved = resolve(id);
371
+ if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
372
+ if (this.shouldRequireAsEsm(resolved)) return this.requireEsm(resolved);
373
+ const module = new this.Module(resolved);
374
+ return this.loadCommonJSModule(module, resolved);
375
+ });
376
+ require.resolve = resolve;
377
+ require.resolve.paths = _require.resolve.paths;
378
+ Object.defineProperty(require, "extensions", {
379
+ get: () => this.extensions,
380
+ set: () => {},
381
+ configurable: true
382
+ });
383
+ require.main = void 0;
384
+ require.cache = this.publicRequireCache;
385
+ return require;
386
+ };
387
+ createProxyCache() {
388
+ return new Proxy(Object.create(null), {
389
+ defineProperty: () => true,
390
+ deleteProperty: () => true,
391
+ set: () => true,
392
+ get: (_, key) => this.requireCache.get(key),
393
+ has: (_, key) => this.requireCache.has(key),
394
+ ownKeys: () => Array.from(this.requireCache.keys()),
395
+ getOwnPropertyDescriptor() {
396
+ return {
397
+ configurable: true,
398
+ enumerable: true
399
+ };
400
+ }
401
+ });
402
+ }
403
+ // very naive implementation for Node.js require
404
+ loadCommonJSModule(module, filename) {
405
+ const cached = this.requireCache.get(filename);
406
+ if (cached) return cached.exports;
407
+ if (this.esmSyntaxFallbackFiles.has(filename)) return this.requireEsm(filename);
408
+ const extension = this.findLongestRegisteredExtension(filename);
409
+ const loader = this.extensions[extension] || this.extensions[".js"];
410
+ try {
411
+ loader(module, filename);
412
+ } catch (error) {
413
+ if (error instanceof CjsParseError) return this.fallbackRequireEsm(filename, error);
414
+ throw error;
415
+ }
416
+ return module.exports;
417
+ }
418
+ canFallbackToEsm(filename) {
419
+ return supportsSyncEsmEvaluate && extname(filename) === ".js";
420
+ }
421
+ fallbackRequireEsm(filename, parseError) {
422
+ let exports;
423
+ try {
424
+ exports = this.requireEsm(filename);
425
+ } catch (esmError) {
426
+ // both parsers rejected the file — surface the original CJS error
427
+ if (esmError instanceof SyntaxError) throw parseError.cause;
428
+ throw esmError;
429
+ }
430
+ this.esmSyntaxFallbackFiles.add(filename);
431
+ return exports;
432
+ }
433
+ findLongestRegisteredExtension(filename) {
434
+ const name = basename(filename);
435
+ let currentExtension;
436
+ let index;
437
+ let startIndex = 0;
438
+ // oxlint-disable-next-line no-cond-assign
439
+ while ((index = name.indexOf(".", startIndex)) !== -1) {
440
+ startIndex = index + 1;
441
+ if (index === 0) continue;
442
+ currentExtension = name.slice(index);
443
+ if (this.extensions[currentExtension]) return currentExtension;
444
+ }
445
+ return ".js";
446
+ }
447
+ getCoreSyntheticModule(identifier) {
448
+ if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
449
+ const exports = this.require(identifier);
450
+ const keys = Object.keys(exports);
451
+ const module = new SyntheticModule([...keys, "default"], () => {
452
+ for (const key of keys) module.setExport(key, exports[key]);
453
+ module.setExport("default", exports);
454
+ }, {
455
+ context: this.context,
456
+ identifier
457
+ });
458
+ this.moduleCache.set(identifier, module);
459
+ return module;
460
+ }
461
+ syncBuiltinESMExports() {
462
+ Module.syncBuiltinESMExports();
463
+ for (const [identifier, module] of this.moduleCache) {
464
+ if (!isBuiltin(identifier) || module.status !== "evaluated") continue;
465
+ const exports = this.require(identifier);
466
+ for (const key of Object.keys(module.namespace)) if (key !== "default") module.setExport(key, exports[key]);
467
+ }
468
+ }
469
+ getCjsSyntheticModule(path, identifier) {
470
+ if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
471
+ const exports = this.require(path);
472
+ // TODO: technically module should be parsed to find static exports, implement for strict mode in #2854
473
+ const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.interopDefault, exports);
474
+ const module = new SyntheticModule([
475
+ ...keys,
476
+ "default",
477
+ "module.exports"
478
+ ], function() {
479
+ for (const key of keys) this.setExport(key, moduleExports[key]);
480
+ this.setExport("default", defaultExport);
481
+ // the raw module.exports value, mirroring the handling of the
482
+ // 'module.exports' export name in require(esm) interop:
483
+ // https://nodejs.org/api/esm.html#commonjs-namespaces
484
+ this.setExport("module.exports", exports);
485
+ }, {
486
+ context: this.context,
487
+ identifier
488
+ });
489
+ this.moduleCache.set(identifier, module);
490
+ return module;
491
+ }
492
+ // TODO: use this in strict mode, when available in #2854
493
+ // private _getNamedCjsExports(path: string): Set<string> {
494
+ // const cachedNamedExports = this.cjsNamedExportsMap.get(path)
495
+ // if (cachedNamedExports) {
496
+ // return cachedNamedExports
497
+ // }
498
+ // if (extname(path) === '.node') {
499
+ // const moduleExports = this.require(path)
500
+ // const namedExports = new Set(Object.keys(moduleExports))
501
+ // this.cjsNamedExportsMap.set(path, namedExports)
502
+ // return namedExports
503
+ // }
504
+ // const code = this.fs.readFile(path)
505
+ // const { exports, reexports } = parseCjs(code, path)
506
+ // const namedExports = new Set(exports)
507
+ // this.cjsNamedExportsMap.set(path, namedExports)
508
+ // for (const reexport of reexports) {
509
+ // if (isNodeBuiltin(reexport)) {
510
+ // const exports = this.require(reexport)
511
+ // if (exports !== null && typeof exports === 'object') {
512
+ // for (const e of Object.keys(exports)) {
513
+ // namedExports.add(e)
514
+ // }
515
+ // }
516
+ // }
517
+ // else {
518
+ // const require = this.createRequire(path)
519
+ // const resolved = require.resolve(reexport)
520
+ // const exports = this._getNamedCjsExports(resolved)
521
+ // for (const e of exports) {
522
+ // namedExports.add(e)
523
+ // }
524
+ // }
525
+ // }
526
+ // return namedExports
527
+ // }
528
+ require(identifier) {
529
+ if (extname(identifier) === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
530
+ if (this.shouldRequireAsEsm(identifier)) return this.requireEsm(identifier);
531
+ const module = new this.Module(identifier);
532
+ return this.loadCommonJSModule(module, identifier);
533
+ }
534
+ requireCoreModule(identifier) {
535
+ const normalized = identifier.replace(/^node:/, "");
536
+ if (this.builtinCache[normalized]) return this.builtinCache[normalized].exports;
537
+ const moduleExports = _require(identifier);
538
+ if (identifier === "node:module" || identifier === "module") {
539
+ const module = new this.Module("/module.js");
540
+ module.exports = this.Module;
541
+ this.builtinCache[normalized] = module;
542
+ return module.exports;
543
+ }
544
+ if (normalized === "v8" && this.codeCache) {
545
+ const module = new this.Module("/v8.js");
546
+ module.exports = createV8ModuleWithCacheReset(moduleExports, this.codeCache);
547
+ this.builtinCache[normalized] = module;
548
+ return module.exports;
549
+ }
550
+ this.builtinCache[normalized] = _require.cache[normalized];
551
+ // TODO: should we wrap module to rethrow context errors?
552
+ return moduleExports;
553
+ }
554
+ }
555
+ // The "module-sync" exports condition (added in Node 22.12/20.19 when
556
+ // require(esm) was unflagged) can resolve to ESM files. When require(esm)
557
+ // is supported (Node 24.9+), the condition is included, matching Node.
558
+ // Otherwise our CJS vm.Script executor cannot handle the resolved ESM
559
+ // files, so the condition is excluded by passing explicit CJS conditions
560
+ // to require.resolve (Node 22.12+).
561
+ // Must be a Set because Node's internal resolver calls conditions.has().
562
+ function parseCjsConditions(execArgv, nodeOptions, requireEsmSupported = false) {
563
+ const conditions = [
564
+ "node",
565
+ "require",
566
+ "node-addons"
567
+ ];
568
+ if (requireEsmSupported) conditions.push("module-sync");
569
+ const args = [...execArgv, ...nodeOptions?.split(/\s+/) ?? []];
570
+ for (let i = 0; i < args.length; i++) {
571
+ const arg = args[i];
572
+ const eqMatch = arg.match(/^(?:--conditions|-C)=(.+)$/);
573
+ if (eqMatch) conditions.push(eqMatch[1]);
574
+ else if ((arg === "--conditions" || arg === "-C") && i + 1 < args.length) conditions.push(args[++i]);
575
+ }
576
+ if (!requireEsmSupported) return new Set(conditions.filter((c) => c !== "module-sync"));
577
+ return new Set(conditions);
578
+ }
579
+
580
+ // `hasAsyncGraph` only exists on SourceTextModule — a SyntheticModule is
581
+ // synchronous by definition (its evaluation callback is sync)
582
+ function moduleHasAsyncGraph(module) {
583
+ return module instanceof SourceTextModule && module.hasAsyncGraph();
584
+ }
585
+ const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
586
+ function parseDataUri(identifier) {
587
+ const match = identifier.match(dataURIRegex);
588
+ if (!match || !match.groups) throw new Error("Invalid data URI");
589
+ const { mime, encoding } = match.groups;
590
+ let code = match.groups.code;
591
+ if (mime === "application/wasm") {
592
+ if (!encoding) throw new Error("Missing data URI encoding");
593
+ if (encoding !== "base64") throw new Error(`Invalid data URI encoding: ${encoding}`);
594
+ return {
595
+ mime,
596
+ code: Buffer.from(code, "base64")
597
+ };
598
+ }
599
+ if (!encoding || encoding === "charset=utf-8") code = decodeURIComponent(code);
600
+ else if (encoding === "base64") code = Buffer.from(code, "base64").toString();
601
+ else throw new Error(`Invalid data URI encoding: ${encoding}`);
602
+ return {
603
+ mime,
604
+ code
605
+ };
606
+ }
607
+ function getContextExecutor(mod) {
608
+ const vmContext = mod.context?.[VITEST_VM_CONTEXT_SYMBOL];
609
+ if (!vmContext) throw new Error(`Cannot import "${mod.identifier}": its vm context was torn down.`);
610
+ return vmContext.externalModulesExecutor;
611
+ }
612
+ async function staticImportModuleDynamically(specifier, referencer) {
613
+ return getContextExecutor(referencer).importModuleDynamically(specifier, referencer);
614
+ }
615
+ function staticInitializeImportMeta(meta, mod) {
616
+ meta.url = mod.identifier;
617
+ if (mod.identifier.startsWith("file:")) {
618
+ const filename = fileURLToPath(mod.identifier);
619
+ meta.filename = filename;
620
+ meta.dirname = dirname$1(filename);
621
+ }
622
+ meta.resolve = (specifier, importer) => {
623
+ return getContextExecutor(mod).resolve(specifier, importer != null ? importer.toString() : mod.identifier);
624
+ };
625
+ }
626
+ class EsmExecutor {
627
+ executor;
628
+ moduleCache = /* @__PURE__ */ new Map();
629
+ esmLinkMap = /* @__PURE__ */ new WeakMap();
630
+ linkQueue = Promise.resolve();
631
+ context;
632
+ #httpIp = IPnumber("127.0.0.0");
633
+ constructor(executor, options) {
634
+ this.executor = executor;
635
+ this.context = options.context;
636
+ }
637
+ async evaluateModule(m) {
638
+ // a module that failed to evaluate keeps living in the cache — rethrow
639
+ // its error instead of silently returning an unusable namespace
640
+ if (m.status === "errored") throw m.error;
641
+ await this.linkModule(m);
642
+ if (m.status === "linked") await m.evaluate();
643
+ return m;
644
+ }
645
+ // Roots are linked one at a time: Node's link() does not wait for a
646
+ // dependency that another root is still linking, and instantiate() then
647
+ // fails on it. Sharing the queue with all roots keeps cycle handling to
648
+ // Node's own single-root linker, which never has to wait.
649
+ linkModule(m) {
650
+ const pending = this.esmLinkMap.get(m);
651
+ if (pending) return pending;
652
+ if (m.status !== "unlinked" && m.status !== "linking") return Promise.resolve();
653
+ const linking = this.linkQueue.then(() => {
654
+ if (m.status === "unlinked") return m.link(this.linker);
655
+ });
656
+ this.esmLinkMap.set(m, linking);
657
+ this.linkQueue = linking.catch(() => {});
658
+ return linking;
659
+ }
660
+ linker = (identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier);
661
+ async createEsModule(fileURL, getCode) {
662
+ const cached = this.moduleCache.get(fileURL);
663
+ if (cached) return cached;
664
+ const promise = this.loadEsModule(fileURL, getCode);
665
+ this.moduleCache.set(fileURL, promise);
666
+ return promise;
667
+ }
668
+ loadEsModule(fileURL, getCode) {
669
+ const code = getCode();
670
+ if (code instanceof Promise) return code.then((content) => this.createModule(fileURL, content));
671
+ return this.createModule(fileURL, code);
672
+ }
673
+ createModule(fileURL, code) {
674
+ const module = fileURL.endsWith(".json") ? this.createJsonModule(fileURL, code) : this.createSourceTextModule(fileURL, code);
675
+ this.moduleCache.set(fileURL, module);
676
+ return module;
677
+ }
678
+ createSourceTextModule(fileURL, code) {
679
+ const codeCache = this.executor.codeCache;
680
+ let cachedData = codeCache?.get(fileURL, code);
681
+ const options = {
682
+ identifier: fileURL,
683
+ context: this.context,
684
+ // static callbacks: Node keeps them registered for as long as the
685
+ // module's host-defined-options symbol is alive, so a closure here would
686
+ // retain this executor (and the whole test file's world) beyond the
687
+ // file's lifetime. The executor is recovered from the module's context
688
+ // at call time instead.
689
+ importModuleDynamically: staticImportModuleDynamically,
690
+ initializeImportMeta: staticInitializeImportMeta
691
+ };
692
+ let m;
693
+ if (cachedData) try {
694
+ m = new SourceTextModule(code, {
695
+ ...options,
696
+ cachedData
697
+ });
698
+ } catch (error) {
699
+ // unlike vm.Script, a module throws when V8 rejects the cache (e.g. the
700
+ // V8 flags changed at runtime): compile from source instead
701
+ if (error?.code !== "ERR_VM_MODULE_CACHED_DATA_REJECTED") throw error;
702
+ codeCache.delete(fileURL);
703
+ cachedData = void 0;
704
+ }
705
+ m ??= new SourceTextModule(code, options);
706
+ // the code cache of a SourceTextModule must be created before evaluation
707
+ if (!cachedData) {
708
+ const created = m;
709
+ codeCache?.store(fileURL, code, () => created.createCachedData());
710
+ }
711
+ return m;
712
+ }
713
+ // Loads an ES module graph synchronously for require(esm), mirroring Node's
714
+ // own behaviour on Node 24.9+. The graph is collected into a local scratch
715
+ // map first and committed to the module cache only after the whole graph is
716
+ // proven to be synchronously evaluable, so a failed require() does not
717
+ // poison the cache for a later import() of the same file.
718
+ requireEsModuleSync(rootIdentifier) {
719
+ const cachedRoot = this.moduleCache.get(rootIdentifier);
720
+ if (cachedRoot) return this.reuseSyncModule(rootIdentifier, cachedRoot);
721
+ const scratch = /* @__PURE__ */ new Map();
722
+ const worklist = [rootIdentifier];
723
+ while (worklist.length > 0) {
724
+ const identifier = worklist.pop();
725
+ if (scratch.has(identifier)) continue;
726
+ const cached = this.moduleCache.get(identifier);
727
+ if (cached) {
728
+ scratch.set(identifier, {
729
+ module: this.reuseSyncModule(identifier, cached),
730
+ commit: false
731
+ });
732
+ continue;
733
+ }
734
+ const disposition = identifier.startsWith("data:") ? this.materializeSyncDataModule(identifier) : this.executor.materializeSyncModule(identifier, identifier === rootIdentifier);
735
+ if (disposition.kind === "ready") {
736
+ scratch.set(identifier, {
737
+ module: disposition.module,
738
+ commit: false
739
+ });
740
+ continue;
741
+ }
742
+ if (disposition.kind === "json") {
743
+ scratch.set(identifier, {
744
+ module: this.createJsonModule(identifier, disposition.code),
745
+ commit: true
746
+ });
747
+ continue;
748
+ }
749
+ const module = this.createSourceTextModule(identifier, disposition.code);
750
+ if (module.hasTopLevelAwait()) throw createRequireAsyncModuleError(identifier, "the module uses top-level await");
751
+ const deps = [];
752
+ for (const request of module.moduleRequests) {
753
+ const depIdentifier = this.executor.resolveSyncSpecifier(request.specifier, identifier);
754
+ deps.push(depIdentifier);
755
+ if (!scratch.has(depIdentifier)) worklist.push(depIdentifier);
756
+ }
757
+ scratch.set(identifier, {
758
+ module,
759
+ deps,
760
+ commit: true
761
+ });
762
+ }
763
+ for (const entry of scratch.values()) if (entry.deps) entry.module.linkRequests(entry.deps.map((dep) => scratch.get(dep).module));
764
+ const root = scratch.get(rootIdentifier);
765
+ if (root.deps) root.module.instantiate();
766
+ if (moduleHasAsyncGraph(root.module)) {
767
+ // top-level await is rejected per module during the walk, so this is a
768
+ // defensive check that an async graph never reaches the sync evaluate
769
+ let culprit = rootIdentifier;
770
+ for (const [identifier, entry] of scratch) if (entry.deps && entry.module.hasTopLevelAwait()) {
771
+ culprit = identifier;
772
+ break;
773
+ }
774
+ throw createRequireAsyncModuleError(rootIdentifier, culprit === rootIdentifier ? "the module uses top-level await" : `its dependency uses top-level await (${culprit})`);
775
+ }
776
+ for (const [identifier, entry] of scratch) if (entry.commit && !this.moduleCache.has(identifier)) this.moduleCache.set(identifier, entry.module);
777
+ // with no top-level await in the graph, evaluate() fulfills synchronously
778
+ // and an evaluation error lands on `status`/`error`, not on the promise
779
+ root.module.evaluate().catch(() => {});
780
+ if (root.module.status === "errored") throw root.module.error;
781
+ if (root.module.status !== "evaluated") throw new Error(`[vitest] Expected synchronous evaluation to complete for ${rootIdentifier}, but module status is "${root.module.status}". This is a bug in Vitest.`);
782
+ return root.module;
783
+ }
784
+ // A cached module is reusable by the sync walker only when it is settled:
785
+ // anything else (a pending Promise or a module in 'unlinked' → 'evaluating')
786
+ // is a concurrent import() mid-flight that a synchronous require() can
787
+ // neither await nor safely link against.
788
+ reuseSyncModule(identifier, cached) {
789
+ if (cached instanceof Promise) throw createConcurrentRequireError(identifier);
790
+ if (cached.status === "errored") throw cached.error;
791
+ if (cached.status !== "evaluated") throw createConcurrentRequireError(identifier);
792
+ // a module with top-level await reports 'evaluated' as soon as evaluate()
793
+ // is called, while its async evaluation may still be pending — and even a
794
+ // settled async graph is never allowed in require() (Node parity)
795
+ if (moduleHasAsyncGraph(cached)) throw createRequireAsyncModuleError(identifier, "the module uses top-level await");
796
+ return cached;
797
+ }
798
+ materializeSyncDataModule(identifier) {
799
+ const { mime, code } = parseDataUri(identifier);
800
+ if (mime === "application/wasm") throw createRequireAsyncModuleError(identifier, "WebAssembly modules cannot be loaded synchronously");
801
+ if (mime === "application/json") return {
802
+ kind: "json",
803
+ code
804
+ };
805
+ return {
806
+ kind: "source",
807
+ code
808
+ };
809
+ }
810
+ createJsonModule(identifier, code) {
811
+ return new SyntheticModule(["default"], function() {
812
+ this.setExport("default", JSON.parse(code));
813
+ }, {
814
+ context: this.context,
815
+ identifier
816
+ });
817
+ }
818
+ async createWebAssemblyModule(fileUrl, getCode) {
819
+ const cached = this.moduleCache.get(fileUrl);
820
+ if (cached) return cached;
821
+ const m = this.loadWebAssemblyModule(getCode(), fileUrl);
822
+ this.moduleCache.set(fileUrl, m);
823
+ return m;
824
+ }
825
+ async createNetworkModule(fileUrl) {
826
+ // https://nodejs.org/api/esm.html#https-and-http-imports
827
+ if (fileUrl.startsWith("http:")) {
828
+ const url = new URL(fileUrl);
829
+ if (url.hostname !== "localhost" && url.hostname !== "::1" && (IPnumber(url.hostname) & IPmask(8)) !== this.#httpIp) throw new Error(
830
+ // we don't know the importer, so it's undefined (the same happens in --pool=threads)
831
+ `import of '${fileUrl}' by undefined is not supported: http can only be used to load local resources (use https instead).`
832
+ );
833
+ }
834
+ return this.createEsModule(fileUrl, () => fetch(fileUrl).then((r) => r.text()));
835
+ }
836
+ async loadWebAssemblyModule(source, identifier) {
837
+ const cached = this.moduleCache.get(identifier);
838
+ if (cached) return cached;
839
+ const wasmModule = await WebAssembly.compile(source);
840
+ const exports = WebAssembly.Module.exports(wasmModule);
841
+ const imports = WebAssembly.Module.imports(wasmModule);
842
+ const moduleLookup = {};
843
+ for (const { module } of imports) if (moduleLookup[module] === void 0) moduleLookup[module] = await this.executor.resolveModule(module, identifier);
844
+ const evaluateModule = (module) => this.evaluateModule(module);
845
+ return new SyntheticModule(exports.map(({ name }) => name), async function() {
846
+ const importsObject = {};
847
+ for (const { module, name } of imports) {
848
+ if (!importsObject[module]) importsObject[module] = {};
849
+ await evaluateModule(moduleLookup[module]);
850
+ importsObject[module][name] = moduleLookup[module].namespace[name];
851
+ }
852
+ const wasmInstance = new WebAssembly.Instance(wasmModule, importsObject);
853
+ for (const { name } of exports) this.setExport(name, wasmInstance.exports[name]);
854
+ }, {
855
+ context: this.context,
856
+ identifier
857
+ });
858
+ }
859
+ cacheModule(identifier, module) {
860
+ this.moduleCache.set(identifier, module);
861
+ }
862
+ resolveCachedModule(identifier) {
863
+ return this.moduleCache.get(identifier);
864
+ }
865
+ async createDataModule(identifier) {
866
+ const cached = this.moduleCache.get(identifier);
867
+ if (cached) return cached;
868
+ const { mime, code } = parseDataUri(identifier);
869
+ if (mime === "application/wasm") {
870
+ const module = this.loadWebAssemblyModule(code, identifier);
871
+ this.moduleCache.set(identifier, module);
872
+ return module;
873
+ }
874
+ if (mime === "application/json") {
875
+ const module = this.createJsonModule(identifier, code);
876
+ this.moduleCache.set(identifier, module);
877
+ return module;
878
+ }
879
+ return this.createEsModule(identifier, () => code);
880
+ }
881
+ }
882
+ function IPnumber(address) {
883
+ const ip = address.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
884
+ if (ip) return (+ip[1] << 24) + (+ip[2] << 16) + (+ip[3] << 8) + +ip[4];
885
+ throw new Error(`Expected IP address, received ${address}`);
886
+ }
887
+ function IPmask(maskSize) {
888
+ return -1 << 32 - maskSize;
889
+ }
890
+
891
+ const CLIENT_ID = "/@vite/client";
892
+ const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
893
+ class ViteExecutor {
894
+ options;
895
+ esm;
896
+ constructor(options) {
897
+ this.options = options;
898
+ this.esm = options.esmExecutor;
899
+ }
900
+ resolve = (identifier) => {
901
+ if (identifier === CLIENT_ID) return identifier;
902
+ };
903
+ get workerState() {
904
+ return this.options.context.__vitest_worker__;
905
+ }
906
+ async createViteModule(fileUrl) {
907
+ if (fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID) return this.createViteClientModule();
908
+ const cached = this.esm.resolveCachedModule(fileUrl);
909
+ if (cached) return cached;
910
+ return this.esm.createEsModule(fileUrl, async () => {
911
+ try {
912
+ const result = await this.options.transform(fileUrl);
913
+ if (result.code) return result.code;
914
+ } catch (cause) {
915
+ // rethrow vite error if it cannot load the module because it's not resolved
916
+ if (typeof cause === "object" && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url")) {
917
+ const error = new Error(`Cannot find module '${fileUrl}'`, { cause });
918
+ error.code = "ERR_MODULE_NOT_FOUND";
919
+ throw error;
920
+ }
921
+ }
922
+ throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
923
+ });
924
+ }
925
+ createViteClientModule() {
926
+ const identifier = CLIENT_ID;
927
+ const cached = this.esm.resolveCachedModule(identifier);
928
+ if (cached) return cached;
929
+ const stub = this.options.viteClientModule;
930
+ const moduleKeys = Object.keys(stub);
931
+ const module = new SyntheticModule(moduleKeys, function() {
932
+ moduleKeys.forEach((key) => {
933
+ this.setExport(key, stub[key]);
934
+ });
935
+ }, {
936
+ context: this.options.context,
937
+ identifier
938
+ });
939
+ this.esm.cacheModule(identifier, module);
940
+ return module;
941
+ }
942
+ canResolve = (fileUrl) => {
943
+ if (fileUrl === CLIENT_FILE) return true;
944
+ const config = this.workerState.config.deps?.web || {};
945
+ const [modulePath] = fileUrl.split("?");
946
+ if (config.transformCss && CSS_LANGS_RE.test(modulePath)) return true;
947
+ if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath)) return true;
948
+ if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath))) return true;
949
+ return false;
950
+ };
951
+ }
952
+
953
+ const { existsSync } = fs__default;
954
+ // always defined when we use vm pool
955
+ const nativeResolve = import.meta.resolve;
956
+ // a relative ESM specifier resolves by plain URL join — Node's resolver adds
957
+ // no information for these (it does not check existence and relative
958
+ // specifiers never consult package.json), but it re-derives the package
959
+ // scope on every uncached call, re-parsing large `exports` maps. Restricted
960
+ // to a conservative charset so anything URL-special falls back to Node.
961
+ const SIMPLE_RELATIVE_SPECIFIER_RE = /^\.{1,2}\/[\w\-./]+$/;
962
+ // TODO: improve Node.js strict mode support in #2854
963
+ class ExternalModulesExecutor {
964
+ options;
965
+ cjs;
966
+ esm;
967
+ vite;
968
+ context;
969
+ fs;
970
+ codeCache;
971
+ resolvers = [];
972
+ #networkSupported = null;
973
+ constructor(options) {
974
+ this.options = options;
975
+ this.context = options.context;
976
+ this.fs = options.fileMap;
977
+ this.codeCache = options.codeCache;
978
+ this.esm = new EsmExecutor(this, { context: this.context });
979
+ setActiveVmExecutor(this);
980
+ this.cjs = new CommonjsExecutor({
981
+ context: this.context,
982
+ fileMap: options.fileMap,
983
+ codeCache: options.codeCache,
984
+ interopDefault: options.interopDefault,
985
+ shouldRequireAsEsm: this.shouldRequireAsEsm,
986
+ requireEsm: this.requireEsm
987
+ });
988
+ this.vite = new ViteExecutor({
989
+ esmExecutor: this.esm,
990
+ context: this.context,
991
+ transform: options.transform,
992
+ viteClientModule: options.viteClientModule
993
+ });
994
+ this.resolvers = [this.vite.resolve];
995
+ }
996
+ syncBuiltinESMExports() {
997
+ this.cjs.syncBuiltinESMExports();
998
+ }
999
+ async import(identifier) {
1000
+ const module = await this.createModule(identifier);
1001
+ await this.esm.evaluateModule(module);
1002
+ return module.namespace;
1003
+ }
1004
+ require(identifier) {
1005
+ return this.cjs.require(identifier);
1006
+ }
1007
+ createRequire(identifier) {
1008
+ return this.cjs.createRequire(identifier);
1009
+ }
1010
+ #esmSyntaxCache = /* @__PURE__ */ new Map();
1011
+ // require() dispatches to the sync ESM loader only for files that are
1012
+ // explicitly marked as ESM (.mjs or a "type": "module" package scope).
1013
+ // JSON files keep the CJS json loader for Node require() parity — the
1014
+ // extension wins over the package scope.
1015
+ shouldRequireAsEsm = (resolvedPath) => {
1016
+ if (!supportsSyncEsmEvaluate) return false;
1017
+ const information = this.getModuleInformation(resolvedPath);
1018
+ if (information.type !== "module" || information.path.endsWith(".json")) return false;
1019
+ if (information.path.endsWith(".mjs")) return true;
1020
+ // A .js file in an ESM package scope may still contain plain CJS code —
1021
+ // Node evaluates it as ESM with injected CJS module variables (module,
1022
+ // require, __filename), which a vm SourceTextModule cannot emulate.
1023
+ // Files without ESM syntax keep loading through the CJS executor; a
1024
+ // false negative here is corrected by its ESM-syntax fallback.
1025
+ let syntax = this.#esmSyntaxCache.get(information.path);
1026
+ if (syntax == null) {
1027
+ syntax = hasEsmSyntax(this.fs.readFile(information.path));
1028
+ this.#esmSyntaxCache.set(information.path, syntax);
1029
+ }
1030
+ return syntax;
1031
+ };
1032
+ requireEsm = (resolvedPath) => {
1033
+ const { url } = this.getModuleInformation(resolvedPath);
1034
+ const namespace = this.esm.requireEsModuleSync(url).namespace;
1035
+ // Node parity: an ES module can define its own require() result with an
1036
+ // export named "module.exports"
1037
+ return "module.exports" in namespace ? namespace["module.exports"] : namespace;
1038
+ };
1039
+ resolveSyncSpecifier = (specifier, referencer) => {
1040
+ const resolved = this.resolve(specifier, referencer);
1041
+ if (resolved instanceof Promise) throw createRequireAsyncModuleError(referencer, `"${specifier}" cannot be resolved synchronously`);
1042
+ return resolved;
1043
+ };
1044
+ // the sync counterpart of `createModule`, used by the require(esm) graph
1045
+ // walker. `forceEsmSource` loads a 'commonjs'-typed file as ES module
1046
+ // source — the CJS executor requests this after its parser rejected a .js
1047
+ // file that contains ESM syntax.
1048
+ materializeSyncModule = (identifier, forceEsmSource) => {
1049
+ const information = this.getModuleInformation(identifier);
1050
+ const { type, path } = information;
1051
+ this.assertModuleExists(information);
1052
+ switch (type) {
1053
+ case "builtin": return {
1054
+ kind: "ready",
1055
+ module: this.cjs.getCoreSyntheticModule(identifier)
1056
+ };
1057
+ case "module":
1058
+ case "commonjs":
1059
+ if (type === "commonjs" && !forceEsmSource) return {
1060
+ kind: "ready",
1061
+ module: this.cjs.getCjsSyntheticModule(path, identifier)
1062
+ };
1063
+ if (path.endsWith(".json")) return {
1064
+ kind: "json",
1065
+ code: this.fs.readFile(path)
1066
+ };
1067
+ return {
1068
+ kind: "source",
1069
+ code: this.fs.readFile(path)
1070
+ };
1071
+ case "data":
1072
+ // data: URIs are materialized by the ESM executor before it consults
1073
+ // the external executor
1074
+ throw new Error(`[vitest] Unexpected data: module ${identifier} in the sync module walker. This is a bug in Vitest.`);
1075
+ case "vite": throw createRequireAsyncModuleError(identifier, "the module is transformed by Vite, which is asynchronous");
1076
+ case "wasm": throw createRequireAsyncModuleError(identifier, "WebAssembly modules cannot be loaded synchronously");
1077
+ case "network": throw createRequireAsyncModuleError(identifier, "network modules cannot be loaded synchronously");
1078
+ default: return type;
1079
+ }
1080
+ };
1081
+ // dynamic import can be used in both ESM and CJS, so we have it in the executor
1082
+ importModuleDynamically = async (specifier, referencer) => {
1083
+ const module = await this.resolveModule(specifier, referencer.identifier);
1084
+ return await this.esm.evaluateModule(module);
1085
+ };
1086
+ resolveModule = async (specifier, referencer) => {
1087
+ let identifier = this.resolve(specifier, referencer);
1088
+ if (identifier instanceof Promise) identifier = await identifier;
1089
+ return await this.createModule(identifier);
1090
+ };
1091
+ resolve(specifier, parent) {
1092
+ for (const resolver of this.resolvers) {
1093
+ const id = resolver(specifier, parent);
1094
+ if (id) return id;
1095
+ }
1096
+ if (SIMPLE_RELATIVE_SPECIFIER_RE.test(specifier) && parent.startsWith("file://")) return new URL(specifier, parent).href;
1097
+ // resolution of externalized modules is stable for the lifetime of the
1098
+ // worker (like fileMap/packageCache), while fresh vm contexts re-resolve
1099
+ // every import edge
1100
+ const cache = this.options.resolveCache;
1101
+ const key = cache ? `${parent}\n${specifier}` : void 0;
1102
+ if (cache) {
1103
+ const cached = cache.get(key);
1104
+ if (cached !== void 0) return cached;
1105
+ }
1106
+ // import.meta.resolve can be asynchronous in older +18 Node versions
1107
+ const resolved = nativeResolve(specifier, parent);
1108
+ if (cache && typeof resolved === "string") cache.set(key, resolved);
1109
+ return resolved;
1110
+ }
1111
+ getModuleInformation(identifier) {
1112
+ const cached = this.options.moduleInfoCache?.get(identifier);
1113
+ if (cached) return cached;
1114
+ const info = this.resolveModuleInformation(identifier);
1115
+ this.options.moduleInfoCache?.set(identifier, info);
1116
+ return info;
1117
+ }
1118
+ resolveModuleInformation(identifier) {
1119
+ if (identifier.startsWith("data:")) return {
1120
+ type: "data",
1121
+ url: identifier,
1122
+ path: identifier
1123
+ };
1124
+ const { file, postfix } = splitFileAndPostfix(identifier);
1125
+ const extension = extname(file);
1126
+ if (extension === ".node" || isBuiltin(identifier)) return {
1127
+ type: "builtin",
1128
+ url: identifier,
1129
+ path: identifier
1130
+ };
1131
+ if (this.isNetworkSupported && (identifier.startsWith("http:") || identifier.startsWith("https:"))) return {
1132
+ type: "network",
1133
+ url: identifier,
1134
+ path: identifier
1135
+ };
1136
+ const isFileUrl = identifier.startsWith("file://");
1137
+ const pathUrl = isFileUrl ? fileURLToPath(file) : file;
1138
+ const fileUrl = isFileUrl ? identifier : `${pathToFileURL(file)}${postfix}`;
1139
+ let type;
1140
+ if (this.vite.canResolve(fileUrl)) type = "vite";
1141
+ else if (extension === ".mjs") type = "module";
1142
+ else if (extension === ".cjs") type = "commonjs";
1143
+ else if (extension === ".wasm")
1144
+ // still experimental on NodeJS --experimental-wasm-modules
1145
+ // cf. ESM_FILE_FORMAT(url) in https://nodejs.org/docs/latest-v20.x/api/esm.html#resolution-algorithm
1146
+ type = "wasm";
1147
+ else type = lookupPackageScopeType(normalize(pathUrl)) === "esm" ? "module" : "commonjs";
1148
+ return {
1149
+ type,
1150
+ path: pathUrl,
1151
+ url: fileUrl
1152
+ };
1153
+ }
1154
+ // create ERR_MODULE_NOT_FOUND on our own since latest NodeJS's import.meta.resolve doesn't throw on non-existing namespace or path
1155
+ // https://github.com/nodejs/node/pull/49038
1156
+ assertModuleExists(information) {
1157
+ const { type, path } = information;
1158
+ if (type === "module" || type === "commonjs" || type === "wasm") information.exists ??= existsSync(path);
1159
+ if (information.exists === false) {
1160
+ const error = /* @__PURE__ */ new Error(`Cannot find ${isBareImport(path) ? "package" : "module"} '${path}'`);
1161
+ error.code = "ERR_MODULE_NOT_FOUND";
1162
+ throw error;
1163
+ }
1164
+ }
1165
+ createModule(identifier) {
1166
+ const information = this.getModuleInformation(identifier);
1167
+ const { type, url, path } = information;
1168
+ this.assertModuleExists(information);
1169
+ switch (type) {
1170
+ case "data": return this.esm.createDataModule(identifier);
1171
+ case "builtin": return this.cjs.getCoreSyntheticModule(identifier);
1172
+ case "vite": return this.vite.createViteModule(url);
1173
+ case "wasm": return this.esm.createWebAssemblyModule(url, () => this.fs.readBuffer(path));
1174
+ case "module": return this.esm.createEsModule(url, () => this.fs.readFile(path));
1175
+ case "commonjs": return this.cjs.getCjsSyntheticModule(path, identifier);
1176
+ case "network": return this.esm.createNetworkModule(url);
1177
+ default: return type;
1178
+ }
1179
+ }
1180
+ get isNetworkSupported() {
1181
+ if (this.#networkSupported == null) {
1182
+ if (process.execArgv.includes("--experimental-network-imports")) this.#networkSupported = true;
1183
+ else if (process.env.NODE_OPTIONS?.includes("--experimental-network-imports")) this.#networkSupported = true;
1184
+ else this.#networkSupported = false;
1185
+ }
1186
+ return this.#networkSupported;
1187
+ }
1188
+ }
1189
+
1190
+ const { promises, readFileSync } = fs__default;
1191
+ class FileMap {
1192
+ fsCache = /* @__PURE__ */ new Map();
1193
+ fsBufferCache = /* @__PURE__ */ new Map();
1194
+ async readFileAsync(path) {
1195
+ const cached = this.fsCache.get(path);
1196
+ if (cached != null) return cached;
1197
+ const source = await promises.readFile(path, "utf-8");
1198
+ this.fsCache.set(path, source);
1199
+ return source;
1200
+ }
1201
+ readFile(path) {
1202
+ const cached = this.fsCache.get(path);
1203
+ if (cached != null) return cached;
1204
+ const source = readFileSync(path, "utf-8");
1205
+ this.fsCache.set(path, source);
1206
+ return source;
1207
+ }
1208
+ readBuffer(path) {
1209
+ const cached = this.fsBufferCache.get(path);
1210
+ if (cached != null) return cached;
1211
+ const buffer = readFileSync(path);
1212
+ this.fsBufferCache.set(path, buffer);
1213
+ return buffer;
1214
+ }
1215
+ }
1216
+
1217
+ const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
1218
+ const fileMap = new FileMap();
1219
+ const packageCache = /* @__PURE__ */ new Map();
1220
+ const codeCache = new CodeCache();
1221
+ const resolveCache = /* @__PURE__ */ new Map();
1222
+ const moduleInfoCache = /* @__PURE__ */ new Map();
1223
+ async function runVmTests(method, state, traces) {
1224
+ const { ctx, rpc } = state;
1225
+ const beforeEnvironmentTime = performance.now();
1226
+ const { environment, loader } = await loadEnvironment(ctx.environment.name, ctx.config.root, rpc, traces, true);
1227
+ state.environment = environment;
1228
+ loader?.evaluatedModules.idToModuleMap.forEach((_, id) => state.dependencies?.add(id));
1229
+ // let the server transform this file's import graph while this worker is
1230
+ // busy setting up the environment (jsdom takes ~0.5s per worker) —
1231
+ // the server is otherwise idle during that window on a cold start.
1232
+ if (environment.prewarmModules !== false) rpc.prewarmModuleGraph(environment.viteEnvironment || environment.name, ctx.files.map((file) => file.filepath)).catch(() => {});
1233
+ if (!environment.setupVM) {
1234
+ const envName = ctx.environment.name;
1235
+ const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
1236
+ throw new TypeError(`Environment "${ctx.environment.name}" is not a valid environment. Path "${packageId}" doesn't support vm environment because it doesn't provide "setupVM" method.`);
1237
+ }
1238
+ const vm = await traces.$("vitest.runtime.environment.setup", { attributes: {
1239
+ "vitest.environment": environment.name,
1240
+ "vitest.environment.vite_environment": environment.viteEnvironment || environment.name
1241
+ } }, () => environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {}));
1242
+ state.durations.environment = performance.now() - beforeEnvironmentTime;
1243
+ process.env.VITEST_VM_POOL = "1";
1244
+ if (!vm.getVmContext) throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
1245
+ const context = vm.getVmContext();
1246
+ if (!isContext(context)) throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
1247
+ // this is unfortunately needed for our own dependencies
1248
+ // we need to find a way to not rely on this by default
1249
+ // because browser doesn't provide these globals
1250
+ context.process = process;
1251
+ context.global = context;
1252
+ // TODO: don't hardcode setImmediate in fake timers defaults
1253
+ context.setImmediate = setImmediate;
1254
+ context.clearImmediate = clearImmediate;
1255
+ // captured before vitest installs its own globals (worker state, console,
1256
+ // mocker, executor symbol): they reference the test file's module graph, so
1257
+ // the teardown strip must treat them as removable, not as pristine. The
1258
+ // globals above are kept, work a test file didn't await may still use them
1259
+ const initialContextKeys = captureContextKeys(context);
1260
+ provideWorkerState(context, state);
1261
+ context.console = state.config.disableConsoleIntercept ? console : createCustomConsole(state);
1262
+ const stubs = getDefaultRequestStubs(context);
1263
+ const externalModulesExecutor = new ExternalModulesExecutor({
1264
+ context,
1265
+ fileMap,
1266
+ codeCache,
1267
+ resolveCache,
1268
+ moduleInfoCache,
1269
+ packageCache,
1270
+ transform: rpc.transform,
1271
+ viteClientModule: stubs["/@vite/client"]
1272
+ });
1273
+ process.exit = (code = process.exitCode || 0) => {
1274
+ const filepath = state.filepath;
1275
+ throw new Error(`process.exit unexpectedly called with "${code}"${filepath ? ` (test file: ${filepath})` : ""}`);
1276
+ };
1277
+ listenForErrors(() => state);
1278
+ const moduleRunner = startVitestModuleRunner({
1279
+ context,
1280
+ evaluatedModules: state.evaluatedModules,
1281
+ state,
1282
+ externalModulesExecutor,
1283
+ createImportMeta: createNodeImportMeta,
1284
+ traces
1285
+ });
1286
+ emitModuleRunner(moduleRunner);
1287
+ Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
1288
+ value: {
1289
+ context,
1290
+ externalModulesExecutor
1291
+ },
1292
+ configurable: true,
1293
+ enumerable: false,
1294
+ writable: false
1295
+ });
1296
+ context.__vitest_mocker__ = moduleRunner.mocker;
1297
+ setupEnv(ctx.config.env, state.metaEnv);
1298
+ if (ctx.config.serializedDefines) try {
1299
+ runInContext(ctx.config.serializedDefines, context, { filename: "virtual:load-defines.js" });
1300
+ } catch (error) {
1301
+ throw new Error(`Failed to load custom "defines": ${error.message}`);
1302
+ }
1303
+ await moduleRunner.mocker.initializeSpyModule();
1304
+ const { run } = await moduleRunner.import(entryFile);
1305
+ try {
1306
+ await run(method, ctx.files, ctx.config, moduleRunner, traces, () => externalModulesExecutor.syncBuiltinESMExports());
1307
+ } finally {
1308
+ await traces.$("vitest.runtime.environment.teardown", () => vm.teardown?.());
1309
+ // unregisters the runner from Vite's `Error.prepareStackTrace` interceptor:
1310
+ // its module-level cache holds `evaluatedModules` of every runner it has
1311
+ // seen, which would otherwise keep each test file's entire module graph
1312
+ // (and with it the vm context) alive for the lifetime of the worker
1313
+ await moduleRunner.close();
1314
+ stripDisposedContext(context, initialContextKeys);
1315
+ setActiveVmExecutor(void 0);
1316
+ }
1317
+ }
1318
+ function setupVmWorker(context) {
1319
+ if (context.config.experimental.viteModuleRunner === false) throw new Error(`Pool "${context.pool}" cannot run with "experimental.viteModuleRunner: false". Please, use "threads" or "forks" instead.`);
1320
+ // V8's isolate-level compilation cache keeps evaluated `vm.SourceTextModule`s
1321
+ // (and everything their module state references) alive until a
1322
+ // memory-pressure GC clears the cache, which in practice means every test
1323
+ // file's world accumulates until the worker hits `vmMemoryLimit`. The
1324
+ // compiled-code caching the flag disables is already covered by the
1325
+ // worker's own script and code caches.
1326
+ v8.setFlagsFromString("--no-compilation-cache");
1327
+ }
1328
+
1329
+ export { runVmTests as r, setupVmWorker as s };