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,785 +0,0 @@
1
- import { fileURLToPath, pathToFileURL } from 'node:url';
2
- import vm, { isContext, runInContext } from 'node:vm';
3
- import { dirname, basename, extname, normalize, resolve } from 'pathe';
4
- import { l as loadEnvironment, a as listenForErrors, e as emitModuleRunner } from './init.k9zZ9sLh.js';
5
- import { distDir } from '../path.js';
6
- import { createCustomConsole } from './console.3WNpx0tS.js';
7
- import fs from 'node:fs';
8
- import { createRequire, Module, isBuiltin } from 'node:module';
9
- import { toArray, splitFileAndPostfix, isBareImport } from '@vitest/utils/helpers';
10
- import { findNearestPackageData } from '@vitest/utils/resolver';
11
- import { dirname as dirname$1 } from 'node:path';
12
- import { CSS_LANGS_RE, KNOWN_ASSET_RE } from '@vitest/utils/constants';
13
- import { getDefaultRequestStubs } from '../module-evaluator.js';
14
- import { s as startVitestModuleRunner, V as VITEST_VM_CONTEXT_SYMBOL, c as createNodeImportMeta } from './startVitestModuleRunner.DB-7oCpn.js';
15
- import { p as provideWorkerState } from './utils.BX5Fg8C4.js';
16
-
17
- function interopCommonJsModule(interopDefault, mod) {
18
- if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
19
- keys: [],
20
- moduleExports: {},
21
- defaultExport: mod
22
- };
23
- if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
24
- const defaultKets = Object.keys(mod.default);
25
- const moduleKeys = Object.keys(mod);
26
- const allKeys = new Set([...defaultKets, ...moduleKeys]);
27
- allKeys.delete("default");
28
- return {
29
- keys: Array.from(allKeys),
30
- moduleExports: new Proxy(mod, { get(mod, prop) {
31
- return mod[prop] ?? mod.default?.[prop];
32
- } }),
33
- defaultExport: mod
34
- };
35
- }
36
- return {
37
- keys: Object.keys(mod).filter((key) => key !== "default"),
38
- moduleExports: mod,
39
- defaultExport: mod
40
- };
41
- }
42
- function isPrimitive(obj) {
43
- return !(obj != null && (typeof obj === "object" || typeof obj === "function"));
44
- }
45
- const SyntheticModule = vm.SyntheticModule;
46
- const SourceTextModule = vm.SourceTextModule;
47
-
48
- const _require = createRequire(import.meta.url);
49
- const requiresCache = /* @__PURE__ */ new WeakMap();
50
- class CommonjsExecutor {
51
- context;
52
- requireCache = /* @__PURE__ */ new Map();
53
- publicRequireCache = this.createProxyCache();
54
- moduleCache = /* @__PURE__ */ new Map();
55
- builtinCache = Object.create(null);
56
- extensions = Object.create(null);
57
- fs;
58
- Module;
59
- interopDefault;
60
- constructor(options) {
61
- this.context = options.context;
62
- this.fs = options.fileMap;
63
- this.interopDefault = options.interopDefault;
64
- const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
65
- // eslint-disable-next-line ts/no-this-alias
66
- const executor = this;
67
- this.Module = class Module$1 {
68
- exports;
69
- isPreloading = false;
70
- id;
71
- filename;
72
- loaded;
73
- parent;
74
- children = [];
75
- path;
76
- paths = [];
77
- constructor(id = "", parent) {
78
- this.exports = primitives.Object.create(Object.prototype);
79
- // in our case the path should always be resolved already
80
- this.path = dirname(id);
81
- this.id = id;
82
- this.filename = id;
83
- this.loaded = false;
84
- this.parent = parent;
85
- }
86
- get require() {
87
- const require = requiresCache.get(this);
88
- if (require) return require;
89
- const _require = Module$1.createRequire(this.id);
90
- requiresCache.set(this, _require);
91
- return _require;
92
- }
93
- static getSourceMapsSupport = () => ({
94
- enabled: false,
95
- nodeModules: false,
96
- generatedCode: false
97
- });
98
- static setSourceMapsSupport = () => {
99
- // noop
100
- };
101
- static register = () => {
102
- throw new Error(`[vitest] "register" is not available when running in Vitest.`);
103
- };
104
- static registerHooks = () => {
105
- throw new Error(`[vitest] "registerHooks" is not available when running in Vitest.`);
106
- };
107
- _compile(code, filename) {
108
- const cjsModule = Module$1.wrap(code);
109
- const script = new vm.Script(cjsModule, {
110
- filename,
111
- importModuleDynamically: options.importModuleDynamically
112
- });
113
- // @ts-expect-error mark script with current identifier
114
- script.identifier = filename;
115
- const fn = script.runInContext(executor.context);
116
- const __dirname = dirname(filename);
117
- executor.requireCache.set(filename, this);
118
- try {
119
- fn(this.exports, this.require, this, filename, __dirname);
120
- return this.exports;
121
- } finally {
122
- this.loaded = true;
123
- }
124
- }
125
- // exposed for external use, Node.js does the opposite
126
- static _load = (request, parent, _isMain) => {
127
- return Module$1.createRequire(parent?.filename ?? request)(request);
128
- };
129
- static wrap = (script) => {
130
- return Module$1.wrapper[0] + script + Module$1.wrapper[1];
131
- };
132
- static wrapper = new primitives.Array("(function (exports, require, module, __filename, __dirname) { ", "\n});");
133
- static builtinModules = Module.builtinModules;
134
- static findSourceMap = Module.findSourceMap;
135
- static SourceMap = Module.SourceMap;
136
- static syncBuiltinESMExports = Module.syncBuiltinESMExports;
137
- static _cache = executor.publicRequireCache;
138
- static _extensions = executor.extensions;
139
- static createRequire = (filename) => {
140
- return executor.createRequire(filename);
141
- };
142
- static runMain = () => {
143
- throw new primitives.Error("[vitest] \"runMain\" is not implemented.");
144
- };
145
- // @ts-expect-error not typed
146
- static _resolveFilename = Module._resolveFilename;
147
- // @ts-expect-error not typed
148
- static _findPath = Module._findPath;
149
- // @ts-expect-error not typed
150
- static _initPaths = Module._initPaths;
151
- // @ts-expect-error not typed
152
- static _preloadModules = Module._preloadModules;
153
- // @ts-expect-error not typed
154
- static _resolveLookupPaths = Module._resolveLookupPaths;
155
- // @ts-expect-error not typed
156
- static globalPaths = Module.globalPaths;
157
- static isBuiltin = Module.isBuiltin;
158
- static constants = Module.constants;
159
- static enableCompileCache = Module.enableCompileCache;
160
- static getCompileCacheDir = Module.getCompileCacheDir;
161
- static flushCompileCache = Module.flushCompileCache;
162
- static stripTypeScriptTypes = Module.stripTypeScriptTypes;
163
- static findPackageJSON = Module.findPackageJSON;
164
- static Module = Module$1;
165
- };
166
- this.extensions[".js"] = this.requireJs;
167
- this.extensions[".json"] = this.requireJson;
168
- }
169
- requireJs = (m, filename) => {
170
- const content = this.fs.readFile(filename);
171
- m._compile(content, filename);
172
- };
173
- requireJson = (m, filename) => {
174
- const code = this.fs.readFile(filename);
175
- m.exports = JSON.parse(code);
176
- };
177
- static cjsConditions;
178
- static getCjsConditions() {
179
- if (!CommonjsExecutor.cjsConditions) CommonjsExecutor.cjsConditions = parseCjsConditions(process.execArgv, process.env.NODE_OPTIONS);
180
- return CommonjsExecutor.cjsConditions;
181
- }
182
- createRequire = (filename) => {
183
- const _require = createRequire(filename);
184
- const resolve = (id, options) => {
185
- return _require.resolve(id, {
186
- ...options,
187
- conditions: CommonjsExecutor.getCjsConditions()
188
- });
189
- };
190
- const require = ((id) => {
191
- const resolved = resolve(id);
192
- if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
193
- const module = new this.Module(resolved);
194
- return this.loadCommonJSModule(module, resolved);
195
- });
196
- require.resolve = resolve;
197
- require.resolve.paths = _require.resolve.paths;
198
- Object.defineProperty(require, "extensions", {
199
- get: () => this.extensions,
200
- set: () => {},
201
- configurable: true
202
- });
203
- require.main = void 0;
204
- require.cache = this.publicRequireCache;
205
- return require;
206
- };
207
- createProxyCache() {
208
- return new Proxy(Object.create(null), {
209
- defineProperty: () => true,
210
- deleteProperty: () => true,
211
- set: () => true,
212
- get: (_, key) => this.requireCache.get(key),
213
- has: (_, key) => this.requireCache.has(key),
214
- ownKeys: () => Array.from(this.requireCache.keys()),
215
- getOwnPropertyDescriptor() {
216
- return {
217
- configurable: true,
218
- enumerable: true
219
- };
220
- }
221
- });
222
- }
223
- // very naive implementation for Node.js require
224
- loadCommonJSModule(module, filename) {
225
- const cached = this.requireCache.get(filename);
226
- if (cached) return cached.exports;
227
- const extension = this.findLongestRegisteredExtension(filename);
228
- (this.extensions[extension] || this.extensions[".js"])(module, filename);
229
- return module.exports;
230
- }
231
- findLongestRegisteredExtension(filename) {
232
- const name = basename(filename);
233
- let currentExtension;
234
- let index;
235
- let startIndex = 0;
236
- // eslint-disable-next-line no-cond-assign
237
- while ((index = name.indexOf(".", startIndex)) !== -1) {
238
- startIndex = index + 1;
239
- if (index === 0) continue;
240
- currentExtension = name.slice(index);
241
- if (this.extensions[currentExtension]) return currentExtension;
242
- }
243
- return ".js";
244
- }
245
- getCoreSyntheticModule(identifier) {
246
- if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
247
- const exports$1 = this.require(identifier);
248
- const keys = Object.keys(exports$1);
249
- const module = new SyntheticModule([...keys, "default"], () => {
250
- for (const key of keys) module.setExport(key, exports$1[key]);
251
- module.setExport("default", exports$1);
252
- }, {
253
- context: this.context,
254
- identifier
255
- });
256
- this.moduleCache.set(identifier, module);
257
- return module;
258
- }
259
- getCjsSyntheticModule(path, identifier) {
260
- if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
261
- const exports$1 = this.require(path);
262
- // TODO: technically module should be parsed to find static exports, implement for strict mode in #2854
263
- const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.interopDefault, exports$1);
264
- const module = new SyntheticModule([...keys, "default"], function() {
265
- for (const key of keys) this.setExport(key, moduleExports[key]);
266
- this.setExport("default", defaultExport);
267
- }, {
268
- context: this.context,
269
- identifier
270
- });
271
- this.moduleCache.set(identifier, module);
272
- return module;
273
- }
274
- // TODO: use this in strict mode, when available in #2854
275
- // private _getNamedCjsExports(path: string): Set<string> {
276
- // const cachedNamedExports = this.cjsNamedExportsMap.get(path)
277
- // if (cachedNamedExports) {
278
- // return cachedNamedExports
279
- // }
280
- // if (extname(path) === '.node') {
281
- // const moduleExports = this.require(path)
282
- // const namedExports = new Set(Object.keys(moduleExports))
283
- // this.cjsNamedExportsMap.set(path, namedExports)
284
- // return namedExports
285
- // }
286
- // const code = this.fs.readFile(path)
287
- // const { exports, reexports } = parseCjs(code, path)
288
- // const namedExports = new Set(exports)
289
- // this.cjsNamedExportsMap.set(path, namedExports)
290
- // for (const reexport of reexports) {
291
- // if (isNodeBuiltin(reexport)) {
292
- // const exports = this.require(reexport)
293
- // if (exports !== null && typeof exports === 'object') {
294
- // for (const e of Object.keys(exports)) {
295
- // namedExports.add(e)
296
- // }
297
- // }
298
- // }
299
- // else {
300
- // const require = this.createRequire(path)
301
- // const resolved = require.resolve(reexport)
302
- // const exports = this._getNamedCjsExports(resolved)
303
- // for (const e of exports) {
304
- // namedExports.add(e)
305
- // }
306
- // }
307
- // }
308
- // return namedExports
309
- // }
310
- require(identifier) {
311
- if (extname(identifier) === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
312
- const module = new this.Module(identifier);
313
- return this.loadCommonJSModule(module, identifier);
314
- }
315
- requireCoreModule(identifier) {
316
- const normalized = identifier.replace(/^node:/, "");
317
- if (this.builtinCache[normalized]) return this.builtinCache[normalized].exports;
318
- const moduleExports = _require(identifier);
319
- if (identifier === "node:module" || identifier === "module") {
320
- const module = new this.Module("/module.js");
321
- module.exports = this.Module;
322
- this.builtinCache[normalized] = module;
323
- return module.exports;
324
- }
325
- this.builtinCache[normalized] = _require.cache[normalized];
326
- // TODO: should we wrap module to rethrow context errors?
327
- return moduleExports;
328
- }
329
- }
330
- // The "module-sync" exports condition (added in Node 22.12/20.19 when
331
- // require(esm) was unflagged) can resolve to ESM files that our CJS
332
- // vm.Script executor cannot handle. We exclude it by passing explicit
333
- // CJS conditions to require.resolve (Node 22.12+).
334
- // Must be a Set because Node's internal resolver calls conditions.has().
335
- // User-specified --conditions/-C flags are respected, except module-sync.
336
- function parseCjsConditions(execArgv, nodeOptions) {
337
- const conditions = [
338
- "node",
339
- "require",
340
- "node-addons"
341
- ];
342
- const args = [...execArgv, ...nodeOptions?.split(/\s+/) ?? []];
343
- for (let i = 0; i < args.length; i++) {
344
- const arg = args[i];
345
- const eqMatch = arg.match(/^(?:--conditions|-C)=(.+)$/);
346
- if (eqMatch) conditions.push(eqMatch[1]);
347
- else if ((arg === "--conditions" || arg === "-C") && i + 1 < args.length) conditions.push(args[++i]);
348
- }
349
- return new Set(conditions.filter((c) => c !== "module-sync"));
350
- }
351
-
352
- const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
353
- class EsmExecutor {
354
- moduleCache = /* @__PURE__ */ new Map();
355
- esmLinkMap = /* @__PURE__ */ new WeakMap();
356
- context;
357
- #httpIp = IPnumber("127.0.0.0");
358
- constructor(executor, options) {
359
- this.executor = executor;
360
- this.context = options.context;
361
- }
362
- async evaluateModule(m) {
363
- if (m.status === "unlinked") this.esmLinkMap.set(m, m.link((identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier)));
364
- await this.esmLinkMap.get(m);
365
- if (m.status === "linked") await m.evaluate();
366
- return m;
367
- }
368
- async createEsModule(fileURL, getCode) {
369
- const cached = this.moduleCache.get(fileURL);
370
- if (cached) return cached;
371
- const promise = this.loadEsModule(fileURL, getCode);
372
- this.moduleCache.set(fileURL, promise);
373
- return promise;
374
- }
375
- async loadEsModule(fileURL, getCode) {
376
- const code = await getCode();
377
- // TODO: should not be allowed in strict mode, implement in #2854
378
- if (fileURL.endsWith(".json")) {
379
- const m = new SyntheticModule(["default"], function() {
380
- const result = JSON.parse(code);
381
- this.setExport("default", result);
382
- });
383
- this.moduleCache.set(fileURL, m);
384
- return m;
385
- }
386
- const m = new SourceTextModule(code, {
387
- identifier: fileURL,
388
- context: this.context,
389
- importModuleDynamically: this.executor.importModuleDynamically,
390
- initializeImportMeta: (meta, mod) => {
391
- meta.url = mod.identifier;
392
- if (mod.identifier.startsWith("file:")) {
393
- const filename = fileURLToPath(mod.identifier);
394
- meta.filename = filename;
395
- meta.dirname = dirname$1(filename);
396
- }
397
- meta.resolve = (specifier, importer) => {
398
- return this.executor.resolve(specifier, importer != null ? importer.toString() : mod.identifier);
399
- };
400
- }
401
- });
402
- this.moduleCache.set(fileURL, m);
403
- return m;
404
- }
405
- async createWebAssemblyModule(fileUrl, getCode) {
406
- const cached = this.moduleCache.get(fileUrl);
407
- if (cached) return cached;
408
- const m = this.loadWebAssemblyModule(getCode(), fileUrl);
409
- this.moduleCache.set(fileUrl, m);
410
- return m;
411
- }
412
- async createNetworkModule(fileUrl) {
413
- // https://nodejs.org/api/esm.html#https-and-http-imports
414
- if (fileUrl.startsWith("http:")) {
415
- const url = new URL(fileUrl);
416
- if (url.hostname !== "localhost" && url.hostname !== "::1" && (IPnumber(url.hostname) & IPmask(8)) !== this.#httpIp) throw new Error(
417
- // we don't know the importer, so it's undefined (the same happens in --pool=threads)
418
- `import of '${fileUrl}' by undefined is not supported: http can only be used to load local resources (use https instead).`
419
- );
420
- }
421
- return this.createEsModule(fileUrl, () => fetch(fileUrl).then((r) => r.text()));
422
- }
423
- async loadWebAssemblyModule(source, identifier) {
424
- const cached = this.moduleCache.get(identifier);
425
- if (cached) return cached;
426
- const wasmModule = await WebAssembly.compile(source);
427
- const exports$1 = WebAssembly.Module.exports(wasmModule);
428
- const imports = WebAssembly.Module.imports(wasmModule);
429
- const moduleLookup = {};
430
- for (const { module } of imports) if (moduleLookup[module] === void 0) moduleLookup[module] = await this.executor.resolveModule(module, identifier);
431
- const evaluateModule = (module) => this.evaluateModule(module);
432
- return new SyntheticModule(exports$1.map(({ name }) => name), async function() {
433
- const importsObject = {};
434
- for (const { module, name } of imports) {
435
- if (!importsObject[module]) importsObject[module] = {};
436
- await evaluateModule(moduleLookup[module]);
437
- importsObject[module][name] = moduleLookup[module].namespace[name];
438
- }
439
- const wasmInstance = new WebAssembly.Instance(wasmModule, importsObject);
440
- for (const { name } of exports$1) this.setExport(name, wasmInstance.exports[name]);
441
- }, {
442
- context: this.context,
443
- identifier
444
- });
445
- }
446
- cacheModule(identifier, module) {
447
- this.moduleCache.set(identifier, module);
448
- }
449
- resolveCachedModule(identifier) {
450
- return this.moduleCache.get(identifier);
451
- }
452
- async createDataModule(identifier) {
453
- const cached = this.moduleCache.get(identifier);
454
- if (cached) return cached;
455
- const match = identifier.match(dataURIRegex);
456
- if (!match || !match.groups) throw new Error("Invalid data URI");
457
- const mime = match.groups.mime;
458
- const encoding = match.groups.encoding;
459
- if (mime === "application/wasm") {
460
- if (!encoding) throw new Error("Missing data URI encoding");
461
- if (encoding !== "base64") throw new Error(`Invalid data URI encoding: ${encoding}`);
462
- const module = this.loadWebAssemblyModule(Buffer.from(match.groups.code, "base64"), identifier);
463
- this.moduleCache.set(identifier, module);
464
- return module;
465
- }
466
- let code = match.groups.code;
467
- if (!encoding || encoding === "charset=utf-8") code = decodeURIComponent(code);
468
- else if (encoding === "base64") code = Buffer.from(code, "base64").toString();
469
- else throw new Error(`Invalid data URI encoding: ${encoding}`);
470
- if (mime === "application/json") {
471
- const module = new SyntheticModule(["default"], function() {
472
- const obj = JSON.parse(code);
473
- this.setExport("default", obj);
474
- }, {
475
- context: this.context,
476
- identifier
477
- });
478
- this.moduleCache.set(identifier, module);
479
- return module;
480
- }
481
- return this.createEsModule(identifier, () => code);
482
- }
483
- }
484
- function IPnumber(address) {
485
- const ip = address.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
486
- if (ip) return (+ip[1] << 24) + (+ip[2] << 16) + (+ip[3] << 8) + +ip[4];
487
- throw new Error(`Expected IP address, received ${address}`);
488
- }
489
- function IPmask(maskSize) {
490
- return -1 << 32 - maskSize;
491
- }
492
-
493
- const CLIENT_ID = "/@vite/client";
494
- const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
495
- class ViteExecutor {
496
- esm;
497
- constructor(options) {
498
- this.options = options;
499
- this.esm = options.esmExecutor;
500
- }
501
- resolve = (identifier) => {
502
- if (identifier === CLIENT_ID) return identifier;
503
- };
504
- get workerState() {
505
- return this.options.context.__vitest_worker__;
506
- }
507
- async createViteModule(fileUrl) {
508
- if (fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID) return this.createViteClientModule();
509
- const cached = this.esm.resolveCachedModule(fileUrl);
510
- if (cached) return cached;
511
- return this.esm.createEsModule(fileUrl, async () => {
512
- try {
513
- const result = await this.options.transform(fileUrl);
514
- if (result.code) return result.code;
515
- } catch (cause) {
516
- // rethrow vite error if it cannot load the module because it's not resolved
517
- if (typeof cause === "object" && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url")) {
518
- const error = new Error(`Cannot find module '${fileUrl}'`, { cause });
519
- error.code = "ERR_MODULE_NOT_FOUND";
520
- throw error;
521
- }
522
- }
523
- throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
524
- });
525
- }
526
- createViteClientModule() {
527
- const identifier = CLIENT_ID;
528
- const cached = this.esm.resolveCachedModule(identifier);
529
- if (cached) return cached;
530
- const stub = this.options.viteClientModule;
531
- const moduleKeys = Object.keys(stub);
532
- const module = new SyntheticModule(moduleKeys, function() {
533
- moduleKeys.forEach((key) => {
534
- this.setExport(key, stub[key]);
535
- });
536
- }, {
537
- context: this.options.context,
538
- identifier
539
- });
540
- this.esm.cacheModule(identifier, module);
541
- return module;
542
- }
543
- canResolve = (fileUrl) => {
544
- if (fileUrl === CLIENT_FILE) return true;
545
- const config = this.workerState.config.deps?.web || {};
546
- const [modulePath] = fileUrl.split("?");
547
- if (config.transformCss && CSS_LANGS_RE.test(modulePath)) return true;
548
- if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath)) return true;
549
- if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath))) return true;
550
- return false;
551
- };
552
- }
553
-
554
- const { existsSync } = fs;
555
- // always defined when we use vm pool
556
- const nativeResolve = import.meta.resolve;
557
- // TODO: improve Node.js strict mode support in #2854
558
- class ExternalModulesExecutor {
559
- cjs;
560
- esm;
561
- vite;
562
- context;
563
- fs;
564
- resolvers = [];
565
- #networkSupported = null;
566
- constructor(options) {
567
- this.options = options;
568
- this.context = options.context;
569
- this.fs = options.fileMap;
570
- this.esm = new EsmExecutor(this, { context: this.context });
571
- this.cjs = new CommonjsExecutor({
572
- context: this.context,
573
- importModuleDynamically: this.importModuleDynamically,
574
- fileMap: options.fileMap,
575
- interopDefault: options.interopDefault
576
- });
577
- this.vite = new ViteExecutor({
578
- esmExecutor: this.esm,
579
- context: this.context,
580
- transform: options.transform,
581
- viteClientModule: options.viteClientModule
582
- });
583
- this.resolvers = [this.vite.resolve];
584
- }
585
- async import(identifier) {
586
- const module = await this.createModule(identifier);
587
- await this.esm.evaluateModule(module);
588
- return module.namespace;
589
- }
590
- require(identifier) {
591
- return this.cjs.require(identifier);
592
- }
593
- createRequire(identifier) {
594
- return this.cjs.createRequire(identifier);
595
- }
596
- // dynamic import can be used in both ESM and CJS, so we have it in the executor
597
- importModuleDynamically = async (specifier, referencer) => {
598
- const module = await this.resolveModule(specifier, referencer.identifier);
599
- return await this.esm.evaluateModule(module);
600
- };
601
- resolveModule = async (specifier, referencer) => {
602
- let identifier = this.resolve(specifier, referencer);
603
- if (identifier instanceof Promise) identifier = await identifier;
604
- return await this.createModule(identifier);
605
- };
606
- resolve(specifier, parent) {
607
- for (const resolver of this.resolvers) {
608
- const id = resolver(specifier, parent);
609
- if (id) return id;
610
- }
611
- // import.meta.resolve can be asynchronous in older +18 Node versions
612
- return nativeResolve(specifier, parent);
613
- }
614
- getModuleInformation(identifier) {
615
- if (identifier.startsWith("data:")) return {
616
- type: "data",
617
- url: identifier,
618
- path: identifier
619
- };
620
- const { file, postfix } = splitFileAndPostfix(identifier);
621
- const extension = extname(file);
622
- if (extension === ".node" || isBuiltin(identifier)) return {
623
- type: "builtin",
624
- url: identifier,
625
- path: identifier
626
- };
627
- if (this.isNetworkSupported && (identifier.startsWith("http:") || identifier.startsWith("https:"))) return {
628
- type: "network",
629
- url: identifier,
630
- path: identifier
631
- };
632
- const isFileUrl = identifier.startsWith("file://");
633
- const pathUrl = isFileUrl ? fileURLToPath(file) : file;
634
- const fileUrl = isFileUrl ? identifier : `${pathToFileURL(file)}${postfix}`;
635
- let type;
636
- if (this.vite.canResolve(fileUrl)) type = "vite";
637
- else if (extension === ".mjs") type = "module";
638
- else if (extension === ".cjs") type = "commonjs";
639
- else if (extension === ".wasm")
640
- // still experimental on NodeJS --experimental-wasm-modules
641
- // cf. ESM_FILE_FORMAT(url) in https://nodejs.org/docs/latest-v20.x/api/esm.html#resolution-algorithm
642
- type = "wasm";
643
- else type = findNearestPackageData(normalize(pathUrl)).type === "module" ? "module" : "commonjs";
644
- return {
645
- type,
646
- path: pathUrl,
647
- url: fileUrl
648
- };
649
- }
650
- createModule(identifier) {
651
- const { type, url, path } = this.getModuleInformation(identifier);
652
- // create ERR_MODULE_NOT_FOUND on our own since latest NodeJS's import.meta.resolve doesn't throw on non-existing namespace or path
653
- // https://github.com/nodejs/node/pull/49038
654
- if ((type === "module" || type === "commonjs" || type === "wasm") && !existsSync(path)) {
655
- const error = /* @__PURE__ */ new Error(`Cannot find ${isBareImport(path) ? "package" : "module"} '${path}'`);
656
- error.code = "ERR_MODULE_NOT_FOUND";
657
- throw error;
658
- }
659
- switch (type) {
660
- case "data": return this.esm.createDataModule(identifier);
661
- case "builtin": return this.cjs.getCoreSyntheticModule(identifier);
662
- case "vite": return this.vite.createViteModule(url);
663
- case "wasm": return this.esm.createWebAssemblyModule(url, () => this.fs.readBuffer(path));
664
- case "module": return this.esm.createEsModule(url, () => this.fs.readFileAsync(path));
665
- case "commonjs": return this.cjs.getCjsSyntheticModule(path, identifier);
666
- case "network": return this.esm.createNetworkModule(url);
667
- default: return type;
668
- }
669
- }
670
- get isNetworkSupported() {
671
- if (this.#networkSupported == null) if (process.execArgv.includes("--experimental-network-imports")) this.#networkSupported = true;
672
- else if (process.env.NODE_OPTIONS?.includes("--experimental-network-imports")) this.#networkSupported = true;
673
- else this.#networkSupported = false;
674
- return this.#networkSupported;
675
- }
676
- }
677
-
678
- const { promises, readFileSync } = fs;
679
- class FileMap {
680
- fsCache = /* @__PURE__ */ new Map();
681
- fsBufferCache = /* @__PURE__ */ new Map();
682
- async readFileAsync(path) {
683
- const cached = this.fsCache.get(path);
684
- if (cached != null) return cached;
685
- const source = await promises.readFile(path, "utf-8");
686
- this.fsCache.set(path, source);
687
- return source;
688
- }
689
- readFile(path) {
690
- const cached = this.fsCache.get(path);
691
- if (cached != null) return cached;
692
- const source = readFileSync(path, "utf-8");
693
- this.fsCache.set(path, source);
694
- return source;
695
- }
696
- readBuffer(path) {
697
- const cached = this.fsBufferCache.get(path);
698
- if (cached != null) return cached;
699
- const buffer = readFileSync(path);
700
- this.fsBufferCache.set(path, buffer);
701
- return buffer;
702
- }
703
- }
704
-
705
- const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
706
- const fileMap = new FileMap();
707
- const packageCache = /* @__PURE__ */ new Map();
708
- async function runVmTests(method, state, traces) {
709
- const { ctx, rpc } = state;
710
- const beforeEnvironmentTime = performance.now();
711
- const { environment } = await loadEnvironment(ctx.environment.name, ctx.config.root, rpc, traces, true);
712
- state.environment = environment;
713
- if (!environment.setupVM) {
714
- const envName = ctx.environment.name;
715
- const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
716
- 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.`);
717
- }
718
- const vm = await traces.$("vitest.runtime.environment.setup", { attributes: {
719
- "vitest.environment": environment.name,
720
- "vitest.environment.vite_environment": environment.viteEnvironment || environment.name
721
- } }, () => environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {}));
722
- state.durations.environment = performance.now() - beforeEnvironmentTime;
723
- process.env.VITEST_VM_POOL = "1";
724
- if (!vm.getVmContext) throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
725
- const context = vm.getVmContext();
726
- if (!isContext(context)) throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
727
- provideWorkerState(context, state);
728
- // this is unfortunately needed for our own dependencies
729
- // we need to find a way to not rely on this by default
730
- // because browser doesn't provide these globals
731
- context.process = process;
732
- context.global = context;
733
- context.console = state.config.disableConsoleIntercept ? console : createCustomConsole(state);
734
- // TODO: don't hardcode setImmediate in fake timers defaults
735
- context.setImmediate = setImmediate;
736
- context.clearImmediate = clearImmediate;
737
- const stubs = getDefaultRequestStubs(context);
738
- const externalModulesExecutor = new ExternalModulesExecutor({
739
- context,
740
- fileMap,
741
- packageCache,
742
- transform: rpc.transform,
743
- viteClientModule: stubs["/@vite/client"]
744
- });
745
- process.exit = (code = process.exitCode || 0) => {
746
- throw new Error(`process.exit unexpectedly called with "${code}"`);
747
- };
748
- listenForErrors(() => state);
749
- const moduleRunner = startVitestModuleRunner({
750
- context,
751
- evaluatedModules: state.evaluatedModules,
752
- state,
753
- externalModulesExecutor,
754
- createImportMeta: createNodeImportMeta,
755
- traces
756
- });
757
- emitModuleRunner(moduleRunner);
758
- Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
759
- value: {
760
- context,
761
- externalModulesExecutor
762
- },
763
- configurable: true,
764
- enumerable: false,
765
- writable: false
766
- });
767
- context.__vitest_mocker__ = moduleRunner.mocker;
768
- if (ctx.config.serializedDefines) try {
769
- runInContext(ctx.config.serializedDefines, context, { filename: "virtual:load-defines.js" });
770
- } catch (error) {
771
- throw new Error(`Failed to load custom "defines": ${error.message}`);
772
- }
773
- await moduleRunner.mocker.initializeSpyModule();
774
- const { run } = await moduleRunner.import(entryFile);
775
- try {
776
- await run(method, ctx.files, ctx.config, moduleRunner, traces);
777
- } finally {
778
- await traces.$("vitest.runtime.environment.teardown", () => vm.teardown?.());
779
- }
780
- }
781
- function setupVmWorker(context) {
782
- if (context.config.experimental.viteModuleRunner === false) throw new Error(`Pool "${context.pool}" cannot run with "experimental.viteModuleRunner: false". Please, use "threads" or "forks" instead.`);
783
- }
784
-
785
- export { runVmTests as r, setupVmWorker as s };