vitest 3.0.9 → 3.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/browser.js +4 -4
  2. package/dist/chunks/base.CylSMlTD.js +41 -0
  3. package/dist/chunks/benchmark.BKUatJGy.js +39 -0
  4. package/dist/chunks/cac.JtTXbKz0.js +1525 -0
  5. package/dist/chunks/{cli-api.Ckwz_xSb.js → cli-api.BTtPTYMs.js} +4638 -5072
  6. package/dist/chunks/console.D6t261w0.js +173 -0
  7. package/dist/chunks/constants.BZZyIeIE.js +43 -0
  8. package/dist/chunks/coverage.0iPg4Wrz.js +33 -0
  9. package/dist/chunks/{coverage.gV8doR2Y.js → coverage.C2ohxaN0.js} +2216 -2479
  10. package/dist/chunks/creator.BEXek7yQ.js +640 -0
  11. package/dist/chunks/date.CDOsz-HY.js +53 -0
  12. package/dist/chunks/defaults.DmfNPoe5.js +114 -0
  13. package/dist/chunks/{env.D4Lgay0q.js → env.Dq0hM4Xv.js} +1 -1
  14. package/dist/chunks/execute.DZKwfrTs.js +791 -0
  15. package/dist/chunks/git.DXfdBEfR.js +74 -0
  16. package/dist/chunks/{globals.BEpDe-k3.js → globals.DCbUWjip.js} +10 -10
  17. package/dist/chunks/{index.D7Ny8f_s.js → index.BDobFbcz.js} +6 -7
  18. package/dist/chunks/index.DFXFpH3w.js +607 -0
  19. package/dist/chunks/index.VfYQ6MXY.js +104 -0
  20. package/dist/chunks/index.ZIOEXBQB.js +2382 -0
  21. package/dist/chunks/inspector.DbDkSkFn.js +54 -0
  22. package/dist/chunks/node.IqGoMrm4.js +15 -0
  23. package/dist/chunks/{reporters.d.CqBhtcTq.d.ts → reporters.d.5g6jXhoW.d.ts} +25 -8
  24. package/dist/chunks/rpc.DGgL5dw7.js +92 -0
  25. package/dist/chunks/run-once.I7PpBOk1.js +47 -0
  26. package/dist/chunks/runBaseTests.CqmKSG99.js +134 -0
  27. package/dist/chunks/setup-common.DEGDGBiA.js +88 -0
  28. package/dist/chunks/{typechecker.BlF3eHsb.js → typechecker.C2IpOhid.js} +620 -622
  29. package/dist/chunks/utils.BfxieIyZ.js +66 -0
  30. package/dist/chunks/utils.CtocqOoE.js +72 -0
  31. package/dist/chunks/utils.OLmtDstN.js +194 -0
  32. package/dist/chunks/{vi.nSCvwQ7l.js → vi.B-PuvDzu.js} +878 -1019
  33. package/dist/chunks/vite.d.Dh1jE-_V.d.ts +23 -0
  34. package/dist/chunks/vm.BW5voG-u.js +789 -0
  35. package/dist/cli.js +2 -2
  36. package/dist/config.cjs +97 -103
  37. package/dist/config.d.ts +3 -3
  38. package/dist/config.js +6 -6
  39. package/dist/coverage.d.ts +1 -1
  40. package/dist/coverage.js +6 -6
  41. package/dist/environments.js +1 -1
  42. package/dist/execute.js +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/index.js +6 -6
  45. package/dist/node.d.ts +3 -3
  46. package/dist/node.js +36 -45
  47. package/dist/path.js +1 -4
  48. package/dist/reporters.d.ts +1 -1
  49. package/dist/reporters.js +4 -4
  50. package/dist/runners.js +231 -267
  51. package/dist/snapshot.js +2 -2
  52. package/dist/suite.js +2 -2
  53. package/dist/worker.js +98 -114
  54. package/dist/workers/forks.js +22 -22
  55. package/dist/workers/runVmTests.js +61 -66
  56. package/dist/workers/threads.js +13 -13
  57. package/dist/workers/vmForks.js +24 -24
  58. package/dist/workers/vmThreads.js +15 -15
  59. package/dist/workers.js +10 -10
  60. package/package.json +11 -11
  61. package/dist/chunks/base.DV59CbtV.js +0 -45
  62. package/dist/chunks/benchmark.DL72EVN-.js +0 -40
  63. package/dist/chunks/cac.CeVHgzve.js +0 -1659
  64. package/dist/chunks/console.CN7AiMGV.js +0 -179
  65. package/dist/chunks/constants.DTYd6dNH.js +0 -46
  66. package/dist/chunks/coverage.A3sS5-Wm.js +0 -40
  67. package/dist/chunks/creator.BsBnpTzI.js +0 -670
  68. package/dist/chunks/date.W2xKR2qe.js +0 -53
  69. package/dist/chunks/defaults.C2Ndd9wx.js +0 -119
  70. package/dist/chunks/execute.eDH0aFFd.js +0 -839
  71. package/dist/chunks/git.B5SDxu-n.js +0 -69
  72. package/dist/chunks/index.B8tIoLPT.js +0 -2526
  73. package/dist/chunks/index.K90BXFOx.js +0 -658
  74. package/dist/chunks/index.uXkkC4xl.js +0 -111
  75. package/dist/chunks/inspector.DKLceBVD.js +0 -54
  76. package/dist/chunks/node.AKq966Jp.js +0 -15
  77. package/dist/chunks/rpc.TVf73xOu.js +0 -102
  78. package/dist/chunks/run-once.2ogXb3JV.js +0 -28
  79. package/dist/chunks/runBaseTests.BVrL_ow3.js +0 -142
  80. package/dist/chunks/setup-common.CPvtqi8q.js +0 -96
  81. package/dist/chunks/utils.C8RiOc4B.js +0 -77
  82. package/dist/chunks/utils.Cn0zI1t3.js +0 -68
  83. package/dist/chunks/utils.bLM2atbD.js +0 -198
  84. package/dist/chunks/vite.d.BUZTGxQ3.d.ts +0 -11
  85. package/dist/chunks/vm.jEFQDlX_.js +0 -852
@@ -0,0 +1,789 @@
1
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2
+ import vm, { isContext } from 'node:vm';
3
+ import { dirname, basename, extname, normalize, join, resolve } from 'pathe';
4
+ import { distDir } from '../path.js';
5
+ import { createCustomConsole } from './console.D6t261w0.js';
6
+ import { g as getDefaultRequestStubs, s as startVitestExecutor } from './execute.DZKwfrTs.js';
7
+ import fs from 'node:fs';
8
+ import { dirname as dirname$1 } from 'node:path';
9
+ import { isNodeBuiltin, isPrimitive, toArray, getCachedData, setCacheData } from 'vite-node/utils';
10
+ import { createRequire, Module } from 'node:module';
11
+ import { CSS_LANGS_RE, KNOWN_ASSET_RE } from 'vite-node/constants';
12
+ import { p as provideWorkerState } from './utils.CtocqOoE.js';
13
+
14
+ const _require = createRequire(import.meta.url);
15
+ const requiresCache = new WeakMap();
16
+ class CommonjsExecutor {
17
+ context;
18
+ requireCache = new Map();
19
+ publicRequireCache = this.createProxyCache();
20
+ moduleCache = new Map();
21
+ builtinCache = Object.create(null);
22
+ extensions = Object.create(null);
23
+ fs;
24
+ Module;
25
+ constructor(options) {
26
+ this.context = options.context;
27
+ this.fs = options.fileMap;
28
+ const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
29
+ const executor = this;
30
+ this.Module = class Module$1 {
31
+ exports;
32
+ isPreloading = false;
33
+ id;
34
+ filename;
35
+ loaded;
36
+ parent;
37
+ children = [];
38
+ path;
39
+ paths = [];
40
+ constructor(id = "", parent) {
41
+ this.exports = primitives.Object.create(Object.prototype);
42
+ this.path = dirname(id);
43
+ this.id = id;
44
+ this.filename = id;
45
+ this.loaded = false;
46
+ this.parent = parent;
47
+ }
48
+ get require() {
49
+ const require = requiresCache.get(this);
50
+ if (require) {
51
+ return require;
52
+ }
53
+ const _require = Module$1.createRequire(this.id);
54
+ requiresCache.set(this, _require);
55
+ return _require;
56
+ }
57
+ static register = () => {
58
+ throw new Error(`[vitest] "register" is not available when running in Vitest.`);
59
+ };
60
+ _compile(code, filename) {
61
+ const cjsModule = Module$1.wrap(code);
62
+ const script = new vm.Script(cjsModule, {
63
+ filename,
64
+ importModuleDynamically: options.importModuleDynamically
65
+ });
66
+ script.identifier = filename;
67
+ const fn = script.runInContext(executor.context);
68
+ const __dirname = dirname(filename);
69
+ executor.requireCache.set(filename, this);
70
+ try {
71
+ fn(this.exports, this.require, this, filename, __dirname);
72
+ return this.exports;
73
+ } finally {
74
+ this.loaded = true;
75
+ }
76
+ }
77
+ static _load = (request, parent, _isMain) => {
78
+ const require = Module$1.createRequire(parent?.filename ?? request);
79
+ return require(request);
80
+ };
81
+ static wrap = (script) => {
82
+ return Module$1.wrapper[0] + script + Module$1.wrapper[1];
83
+ };
84
+ static wrapper = new primitives.Array("(function (exports, require, module, __filename, __dirname) { ", "\n});");
85
+ static builtinModules = Module.builtinModules;
86
+ static findSourceMap = Module.findSourceMap;
87
+ static SourceMap = Module.SourceMap;
88
+ static syncBuiltinESMExports = Module.syncBuiltinESMExports;
89
+ static _cache = executor.moduleCache;
90
+ static _extensions = executor.extensions;
91
+ static createRequire = (filename) => {
92
+ return executor.createRequire(filename);
93
+ };
94
+ static runMain = () => {
95
+ throw new primitives.Error("[vitest] \"runMain\" is not implemented.");
96
+ };
97
+ static _resolveFilename = Module._resolveFilename;
98
+ static _findPath = Module._findPath;
99
+ static _initPaths = Module._initPaths;
100
+ static _preloadModules = Module._preloadModules;
101
+ static _resolveLookupPaths = Module._resolveLookupPaths;
102
+ static globalPaths = Module.globalPaths;
103
+ static isBuiltin = Module.isBuiltin;
104
+ static constants = Module.constants;
105
+ static enableCompileCache = Module.enableCompileCache;
106
+ static getCompileCacheDir = Module.getCompileCacheDir;
107
+ static flushCompileCache = Module.flushCompileCache;
108
+ static stripTypeScriptTypes = Module.stripTypeScriptTypes;
109
+ static findPackageJSON = Module.findPackageJSON;
110
+ static Module = Module$1;
111
+ };
112
+ this.extensions[".js"] = this.requireJs;
113
+ this.extensions[".json"] = this.requireJson;
114
+ }
115
+ requireJs = (m, filename) => {
116
+ const content = this.fs.readFile(filename);
117
+ m._compile(content, filename);
118
+ };
119
+ requireJson = (m, filename) => {
120
+ const code = this.fs.readFile(filename);
121
+ m.exports = JSON.parse(code);
122
+ };
123
+ createRequire = (filename) => {
124
+ const _require = createRequire(filename);
125
+ const require = (id) => {
126
+ const resolved = _require.resolve(id);
127
+ const ext = extname(resolved);
128
+ if (ext === ".node" || isNodeBuiltin(resolved)) {
129
+ return this.requireCoreModule(resolved);
130
+ }
131
+ const module = new this.Module(resolved);
132
+ return this.loadCommonJSModule(module, resolved);
133
+ };
134
+ require.resolve = _require.resolve;
135
+ Object.defineProperty(require, "extensions", {
136
+ get: () => this.extensions,
137
+ set: () => {},
138
+ configurable: true
139
+ });
140
+ require.main = undefined;
141
+ require.cache = this.publicRequireCache;
142
+ return require;
143
+ };
144
+ createProxyCache() {
145
+ return new Proxy(Object.create(null), {
146
+ defineProperty: () => true,
147
+ deleteProperty: () => true,
148
+ set: () => true,
149
+ get: (_, key) => this.requireCache.get(key),
150
+ has: (_, key) => this.requireCache.has(key),
151
+ ownKeys: () => Array.from(this.requireCache.keys()),
152
+ getOwnPropertyDescriptor() {
153
+ return {
154
+ configurable: true,
155
+ enumerable: true
156
+ };
157
+ }
158
+ });
159
+ }
160
+ loadCommonJSModule(module, filename) {
161
+ const cached = this.requireCache.get(filename);
162
+ if (cached) {
163
+ return cached.exports;
164
+ }
165
+ const extension = this.findLongestRegisteredExtension(filename);
166
+ const loader = this.extensions[extension] || this.extensions[".js"];
167
+ loader(module, filename);
168
+ return module.exports;
169
+ }
170
+ findLongestRegisteredExtension(filename) {
171
+ const name = basename(filename);
172
+ let currentExtension;
173
+ let index;
174
+ let startIndex = 0;
175
+ while ((index = name.indexOf(".", startIndex)) !== -1) {
176
+ startIndex = index + 1;
177
+ if (index === 0) {
178
+ continue;
179
+ }
180
+ currentExtension = name.slice(index);
181
+ if (this.extensions[currentExtension]) {
182
+ return currentExtension;
183
+ }
184
+ }
185
+ return ".js";
186
+ }
187
+ require(identifier) {
188
+ const ext = extname(identifier);
189
+ if (ext === ".node" || isNodeBuiltin(identifier)) {
190
+ return this.requireCoreModule(identifier);
191
+ }
192
+ const module = new this.Module(identifier);
193
+ return this.loadCommonJSModule(module, identifier);
194
+ }
195
+ requireCoreModule(identifier) {
196
+ const normalized = identifier.replace(/^node:/, "");
197
+ if (this.builtinCache[normalized]) {
198
+ return this.builtinCache[normalized].exports;
199
+ }
200
+ const moduleExports = _require(identifier);
201
+ if (identifier === "node:module" || identifier === "module") {
202
+ const module = new this.Module("/module.js");
203
+ module.exports = this.Module;
204
+ this.builtinCache[normalized] = module;
205
+ return module.exports;
206
+ }
207
+ this.builtinCache[normalized] = _require.cache[normalized];
208
+ return moduleExports;
209
+ }
210
+ }
211
+
212
+ function interopCommonJsModule(interopDefault, mod) {
213
+ if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) {
214
+ return {
215
+ keys: [],
216
+ moduleExports: {},
217
+ defaultExport: mod
218
+ };
219
+ }
220
+ if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
221
+ const defaultKets = Object.keys(mod.default);
222
+ const moduleKeys = Object.keys(mod);
223
+ const allKeys = new Set([...defaultKets, ...moduleKeys]);
224
+ allKeys.delete("default");
225
+ return {
226
+ keys: Array.from(allKeys),
227
+ moduleExports: new Proxy(mod, { get(mod, prop) {
228
+ return mod[prop] ?? mod.default?.[prop];
229
+ } }),
230
+ defaultExport: mod
231
+ };
232
+ }
233
+ return {
234
+ keys: Object.keys(mod).filter((key) => key !== "default"),
235
+ moduleExports: mod,
236
+ defaultExport: mod
237
+ };
238
+ }
239
+ const SyntheticModule$1 = vm.SyntheticModule;
240
+ const SourceTextModule = vm.SourceTextModule;
241
+
242
+ const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
243
+ class EsmExecutor {
244
+ moduleCache = new Map();
245
+ esmLinkMap = new WeakMap();
246
+ context;
247
+ #httpIp = IPnumber("127.0.0.0");
248
+ constructor(executor, options) {
249
+ this.executor = executor;
250
+ this.context = options.context;
251
+ }
252
+ async evaluateModule(m) {
253
+ if (m.status === "unlinked") {
254
+ this.esmLinkMap.set(m, m.link((identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier)));
255
+ }
256
+ await this.esmLinkMap.get(m);
257
+ if (m.status === "linked") {
258
+ await m.evaluate();
259
+ }
260
+ return m;
261
+ }
262
+ async createEsModule(fileURL, getCode) {
263
+ const cached = this.moduleCache.get(fileURL);
264
+ if (cached) {
265
+ return cached;
266
+ }
267
+ const promise = this.loadEsModule(fileURL, getCode);
268
+ this.moduleCache.set(fileURL, promise);
269
+ return promise;
270
+ }
271
+ async loadEsModule(fileURL, getCode) {
272
+ const code = await getCode();
273
+ if (fileURL.endsWith(".json")) {
274
+ const m = new SyntheticModule$1(["default"], () => {
275
+ const result = JSON.parse(code);
276
+ m.setExport("default", result);
277
+ });
278
+ this.moduleCache.set(fileURL, m);
279
+ return m;
280
+ }
281
+ const m = new SourceTextModule(code, {
282
+ identifier: fileURL,
283
+ context: this.context,
284
+ importModuleDynamically: this.executor.importModuleDynamically,
285
+ initializeImportMeta: (meta, mod) => {
286
+ meta.url = mod.identifier;
287
+ if (mod.identifier.startsWith("file:")) {
288
+ const filename = fileURLToPath(mod.identifier);
289
+ meta.filename = filename;
290
+ meta.dirname = dirname$1(filename);
291
+ }
292
+ meta.resolve = (specifier, importer) => {
293
+ return this.executor.resolve(specifier, importer != null ? importer.toString() : mod.identifier);
294
+ };
295
+ }
296
+ });
297
+ this.moduleCache.set(fileURL, m);
298
+ return m;
299
+ }
300
+ async createWebAssemblyModule(fileUrl, getCode) {
301
+ const cached = this.moduleCache.get(fileUrl);
302
+ if (cached) {
303
+ return cached;
304
+ }
305
+ const m = this.loadWebAssemblyModule(getCode(), fileUrl);
306
+ this.moduleCache.set(fileUrl, m);
307
+ return m;
308
+ }
309
+ async createNetworkModule(fileUrl) {
310
+ if (fileUrl.startsWith("http:")) {
311
+ const url = new URL(fileUrl);
312
+ if (url.hostname !== "localhost" && url.hostname !== "::1" && (IPnumber(url.hostname) & IPmask(8)) !== this.#httpIp) {
313
+ throw new Error(
314
+ // we don't know the importer, so it's undefined (the same happens in --pool=threads)
315
+ `import of '${fileUrl}' by undefined is not supported: ` + "http can only be used to load local resources (use https instead)."
316
+ );
317
+ }
318
+ }
319
+ return this.createEsModule(fileUrl, () => fetch(fileUrl).then((r) => r.text()));
320
+ }
321
+ async loadWebAssemblyModule(source, identifier) {
322
+ const cached = this.moduleCache.get(identifier);
323
+ if (cached) {
324
+ return cached;
325
+ }
326
+ const wasmModule = await WebAssembly.compile(source);
327
+ const exports = WebAssembly.Module.exports(wasmModule);
328
+ const imports = WebAssembly.Module.imports(wasmModule);
329
+ const moduleLookup = {};
330
+ for (const { module } of imports) {
331
+ if (moduleLookup[module] === undefined) {
332
+ moduleLookup[module] = await this.executor.resolveModule(module, identifier);
333
+ }
334
+ }
335
+ const syntheticModule = new SyntheticModule$1(exports.map(({ name }) => name), async () => {
336
+ const importsObject = {};
337
+ for (const { module, name } of imports) {
338
+ if (!importsObject[module]) {
339
+ importsObject[module] = {};
340
+ }
341
+ await this.evaluateModule(moduleLookup[module]);
342
+ importsObject[module][name] = moduleLookup[module].namespace[name];
343
+ }
344
+ const wasmInstance = new WebAssembly.Instance(wasmModule, importsObject);
345
+ for (const { name } of exports) {
346
+ syntheticModule.setExport(name, wasmInstance.exports[name]);
347
+ }
348
+ }, {
349
+ context: this.context,
350
+ identifier
351
+ });
352
+ return syntheticModule;
353
+ }
354
+ cacheModule(identifier, module) {
355
+ this.moduleCache.set(identifier, module);
356
+ }
357
+ resolveCachedModule(identifier) {
358
+ return this.moduleCache.get(identifier);
359
+ }
360
+ async createDataModule(identifier) {
361
+ const cached = this.moduleCache.get(identifier);
362
+ if (cached) {
363
+ return cached;
364
+ }
365
+ const match = identifier.match(dataURIRegex);
366
+ if (!match || !match.groups) {
367
+ throw new Error("Invalid data URI");
368
+ }
369
+ const mime = match.groups.mime;
370
+ const encoding = match.groups.encoding;
371
+ if (mime === "application/wasm") {
372
+ if (!encoding) {
373
+ throw new Error("Missing data URI encoding");
374
+ }
375
+ if (encoding !== "base64") {
376
+ throw new Error(`Invalid data URI encoding: ${encoding}`);
377
+ }
378
+ const module = this.loadWebAssemblyModule(Buffer.from(match.groups.code, "base64"), identifier);
379
+ this.moduleCache.set(identifier, module);
380
+ return module;
381
+ }
382
+ let code = match.groups.code;
383
+ if (!encoding || encoding === "charset=utf-8") {
384
+ code = decodeURIComponent(code);
385
+ } else if (encoding === "base64") {
386
+ code = Buffer.from(code, "base64").toString();
387
+ } else {
388
+ throw new Error(`Invalid data URI encoding: ${encoding}`);
389
+ }
390
+ if (mime === "application/json") {
391
+ const module = new SyntheticModule$1(["default"], () => {
392
+ const obj = JSON.parse(code);
393
+ module.setExport("default", obj);
394
+ }, {
395
+ context: this.context,
396
+ identifier
397
+ });
398
+ this.moduleCache.set(identifier, module);
399
+ return module;
400
+ }
401
+ return this.createEsModule(identifier, () => code);
402
+ }
403
+ }
404
+ function IPnumber(address) {
405
+ const ip = address.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
406
+ if (ip) {
407
+ return (+ip[1] << 24) + (+ip[2] << 16) + (+ip[3] << 8) + +ip[4];
408
+ }
409
+ throw new Error(`Expected IP address, received ${address}`);
410
+ }
411
+ function IPmask(maskSize) {
412
+ return -1 << 32 - maskSize;
413
+ }
414
+
415
+ const CLIENT_ID = "/@vite/client";
416
+ const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
417
+ class ViteExecutor {
418
+ esm;
419
+ constructor(options) {
420
+ this.options = options;
421
+ this.esm = options.esmExecutor;
422
+ }
423
+ resolve = (identifier, parent) => {
424
+ if (identifier === CLIENT_ID) {
425
+ if (this.workerState.environment.transformMode === "web") {
426
+ return identifier;
427
+ }
428
+ const packageName = this.getPackageName(parent);
429
+ throw new Error(`[vitest] Vitest cannot handle ${CLIENT_ID} imported in ${parent} when running in SSR environment. Add "${packageName}" to "ssr.noExternal" if you are using Vite SSR, or to "server.deps.inline" if you are using Vite Node.`);
430
+ }
431
+ };
432
+ get workerState() {
433
+ return this.options.context.__vitest_worker__;
434
+ }
435
+ getPackageName(modulePath) {
436
+ const path = normalize(modulePath);
437
+ let name = path.split("/node_modules/").pop() || "";
438
+ if (name?.startsWith("@")) {
439
+ name = name.split("/").slice(0, 2).join("/");
440
+ } else {
441
+ name = name.split("/")[0];
442
+ }
443
+ return name;
444
+ }
445
+ async createViteModule(fileUrl) {
446
+ if (fileUrl === CLIENT_FILE) {
447
+ return this.createViteClientModule();
448
+ }
449
+ const cached = this.esm.resolveCachedModule(fileUrl);
450
+ if (cached) {
451
+ return cached;
452
+ }
453
+ return this.esm.createEsModule(fileUrl, async () => {
454
+ const result = await this.options.transform(fileUrl, "web");
455
+ if (!result.code) {
456
+ throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
457
+ }
458
+ return result.code;
459
+ });
460
+ }
461
+ createViteClientModule() {
462
+ const identifier = CLIENT_ID;
463
+ const cached = this.esm.resolveCachedModule(identifier);
464
+ if (cached) {
465
+ return cached;
466
+ }
467
+ const stub = this.options.viteClientModule;
468
+ const moduleKeys = Object.keys(stub);
469
+ const module = new SyntheticModule$1(moduleKeys, () => {
470
+ moduleKeys.forEach((key) => {
471
+ module.setExport(key, stub[key]);
472
+ });
473
+ }, {
474
+ context: this.options.context,
475
+ identifier
476
+ });
477
+ this.esm.cacheModule(identifier, module);
478
+ return module;
479
+ }
480
+ canResolve = (fileUrl) => {
481
+ const transformMode = this.workerState.environment.transformMode;
482
+ if (transformMode !== "web") {
483
+ return false;
484
+ }
485
+ if (fileUrl === CLIENT_FILE) {
486
+ return true;
487
+ }
488
+ const config = this.workerState.config.deps?.web || {};
489
+ const [modulePath] = fileUrl.split("?");
490
+ if (config.transformCss && CSS_LANGS_RE.test(modulePath)) {
491
+ return true;
492
+ }
493
+ if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath)) {
494
+ return true;
495
+ }
496
+ if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath))) {
497
+ return true;
498
+ }
499
+ return false;
500
+ };
501
+ }
502
+
503
+ const SyntheticModule = vm.SyntheticModule;
504
+ const { existsSync, statSync } = fs;
505
+ const nativeResolve = import.meta.resolve;
506
+ class ExternalModulesExecutor {
507
+ cjs;
508
+ esm;
509
+ vite;
510
+ context;
511
+ fs;
512
+ resolvers = [];
513
+ #networkSupported = null;
514
+ constructor(options) {
515
+ this.options = options;
516
+ this.context = options.context;
517
+ this.fs = options.fileMap;
518
+ this.esm = new EsmExecutor(this, { context: this.context });
519
+ this.cjs = new CommonjsExecutor({
520
+ context: this.context,
521
+ importModuleDynamically: this.importModuleDynamically,
522
+ fileMap: options.fileMap
523
+ });
524
+ this.vite = new ViteExecutor({
525
+ esmExecutor: this.esm,
526
+ context: this.context,
527
+ transform: options.transform,
528
+ viteClientModule: options.viteClientModule
529
+ });
530
+ this.resolvers = [this.vite.resolve];
531
+ }
532
+ async import(identifier) {
533
+ const module = await this.createModule(identifier);
534
+ await this.esm.evaluateModule(module);
535
+ return module.namespace;
536
+ }
537
+ require(identifier) {
538
+ return this.cjs.require(identifier);
539
+ }
540
+ createRequire(identifier) {
541
+ return this.cjs.createRequire(identifier);
542
+ }
543
+ importModuleDynamically = async (specifier, referencer) => {
544
+ const module = await this.resolveModule(specifier, referencer.identifier);
545
+ return await this.esm.evaluateModule(module);
546
+ };
547
+ resolveModule = async (specifier, referencer) => {
548
+ let identifier = this.resolve(specifier, referencer);
549
+ if (identifier instanceof Promise) {
550
+ identifier = await identifier;
551
+ }
552
+ return await this.createModule(identifier);
553
+ };
554
+ resolve(specifier, parent) {
555
+ for (const resolver of this.resolvers) {
556
+ const id = resolver(specifier, parent);
557
+ if (id) {
558
+ return id;
559
+ }
560
+ }
561
+ return nativeResolve(specifier, parent);
562
+ }
563
+ findNearestPackageData(basedir) {
564
+ const originalBasedir = basedir;
565
+ const packageCache = this.options.packageCache;
566
+ while (basedir) {
567
+ const cached = getCachedData(packageCache, basedir, originalBasedir);
568
+ if (cached) {
569
+ return cached;
570
+ }
571
+ const pkgPath = join(basedir, "package.json");
572
+ try {
573
+ if (statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) {
574
+ const pkgData = JSON.parse(this.fs.readFile(pkgPath));
575
+ if (packageCache) {
576
+ setCacheData(packageCache, pkgData, basedir, originalBasedir);
577
+ }
578
+ return pkgData;
579
+ }
580
+ } catch {}
581
+ const nextBasedir = dirname$1(basedir);
582
+ if (nextBasedir === basedir) {
583
+ break;
584
+ }
585
+ basedir = nextBasedir;
586
+ }
587
+ return {};
588
+ }
589
+ wrapCoreSyntheticModule(identifier, exports) {
590
+ const moduleKeys = Object.keys(exports);
591
+ const m = new SyntheticModule([...moduleKeys, "default"], () => {
592
+ for (const key of moduleKeys) {
593
+ m.setExport(key, exports[key]);
594
+ }
595
+ m.setExport("default", exports);
596
+ }, {
597
+ context: this.context,
598
+ identifier
599
+ });
600
+ return m;
601
+ }
602
+ wrapCommonJsSynteticModule(identifier, exports) {
603
+ const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.options.interopDefault, exports);
604
+ const m = new SyntheticModule([...keys, "default"], () => {
605
+ for (const key of keys) {
606
+ m.setExport(key, moduleExports[key]);
607
+ }
608
+ m.setExport("default", defaultExport);
609
+ }, {
610
+ context: this.context,
611
+ identifier
612
+ });
613
+ return m;
614
+ }
615
+ getModuleInformation(identifier) {
616
+ if (identifier.startsWith("data:")) {
617
+ return {
618
+ type: "data",
619
+ url: identifier,
620
+ path: identifier
621
+ };
622
+ }
623
+ const extension = extname(identifier);
624
+ if (extension === ".node" || isNodeBuiltin(identifier)) {
625
+ return {
626
+ type: "builtin",
627
+ url: identifier,
628
+ path: identifier
629
+ };
630
+ }
631
+ if (this.isNetworkSupported && (identifier.startsWith("http:") || identifier.startsWith("https:"))) {
632
+ return {
633
+ type: "network",
634
+ url: identifier,
635
+ path: identifier
636
+ };
637
+ }
638
+ const isFileUrl = identifier.startsWith("file://");
639
+ const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
640
+ const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
641
+ let type;
642
+ if (this.vite.canResolve(fileUrl)) {
643
+ type = "vite";
644
+ } else if (extension === ".mjs") {
645
+ type = "module";
646
+ } else if (extension === ".cjs") {
647
+ type = "commonjs";
648
+ } else if (extension === ".wasm") {
649
+ type = "wasm";
650
+ } else {
651
+ const pkgData = this.findNearestPackageData(normalize(pathUrl));
652
+ type = pkgData.type === "module" ? "module" : "commonjs";
653
+ }
654
+ return {
655
+ type,
656
+ path: pathUrl,
657
+ url: fileUrl
658
+ };
659
+ }
660
+ async createModule(identifier) {
661
+ const { type, url, path } = this.getModuleInformation(identifier);
662
+ if ((type === "module" || type === "commonjs" || type === "wasm") && !existsSync(path)) {
663
+ const error = new Error(`Cannot find module '${path}'`);
664
+ error.code = "ERR_MODULE_NOT_FOUND";
665
+ throw error;
666
+ }
667
+ switch (type) {
668
+ case "data": return await this.esm.createDataModule(identifier);
669
+ case "builtin": {
670
+ const exports = this.require(identifier);
671
+ return this.wrapCoreSyntheticModule(identifier, exports);
672
+ }
673
+ case "vite": return await this.vite.createViteModule(url);
674
+ case "wasm": return await this.esm.createWebAssemblyModule(url, () => this.fs.readBuffer(path));
675
+ case "module": return await this.esm.createEsModule(url, () => this.fs.readFileAsync(path));
676
+ case "commonjs": {
677
+ const exports = this.require(path);
678
+ return this.wrapCommonJsSynteticModule(identifier, exports);
679
+ }
680
+ case "network": return await this.esm.createNetworkModule(url);
681
+ default: {
682
+ const _deadend = type;
683
+ return _deadend;
684
+ }
685
+ }
686
+ }
687
+ get isNetworkSupported() {
688
+ if (this.#networkSupported == null) {
689
+ if (process.execArgv.includes("--experimental-network-imports")) {
690
+ this.#networkSupported = true;
691
+ } else if (process.env.NODE_OPTIONS?.includes("--experimental-network-imports")) {
692
+ this.#networkSupported = true;
693
+ } else {
694
+ this.#networkSupported = false;
695
+ }
696
+ }
697
+ return this.#networkSupported;
698
+ }
699
+ }
700
+
701
+ const { promises, readFileSync } = fs;
702
+ class FileMap {
703
+ fsCache = new Map();
704
+ fsBufferCache = new Map();
705
+ async readFileAsync(path) {
706
+ const cached = this.fsCache.get(path);
707
+ if (cached != null) {
708
+ return cached;
709
+ }
710
+ const source = await promises.readFile(path, "utf-8");
711
+ this.fsCache.set(path, source);
712
+ return source;
713
+ }
714
+ readFile(path) {
715
+ const cached = this.fsCache.get(path);
716
+ if (cached != null) {
717
+ return cached;
718
+ }
719
+ const source = readFileSync(path, "utf-8");
720
+ this.fsCache.set(path, source);
721
+ return source;
722
+ }
723
+ readBuffer(path) {
724
+ const cached = this.fsBufferCache.get(path);
725
+ if (cached != null) {
726
+ return cached;
727
+ }
728
+ const buffer = readFileSync(path);
729
+ this.fsBufferCache.set(path, buffer);
730
+ return buffer;
731
+ }
732
+ }
733
+
734
+ const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
735
+ const fileMap = new FileMap();
736
+ const packageCache = new Map();
737
+ async function runVmTests(method, state) {
738
+ const { environment, ctx, rpc } = state;
739
+ if (!environment.setupVM) {
740
+ const envName = ctx.environment.name;
741
+ const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
742
+ 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.`);
743
+ }
744
+ const vm = await environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {});
745
+ state.durations.environment = performance.now() - state.durations.environment;
746
+ process.env.VITEST_VM_POOL = "1";
747
+ if (!vm.getVmContext) {
748
+ throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
749
+ }
750
+ const context = vm.getVmContext();
751
+ if (!isContext(context)) {
752
+ throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
753
+ }
754
+ provideWorkerState(context, state);
755
+ context.process = process;
756
+ context.global = context;
757
+ context.console = state.config.disableConsoleIntercept ? console : createCustomConsole(state);
758
+ context.setImmediate = setImmediate;
759
+ context.clearImmediate = clearImmediate;
760
+ const stubs = getDefaultRequestStubs(context);
761
+ const externalModulesExecutor = new ExternalModulesExecutor({
762
+ context,
763
+ fileMap,
764
+ packageCache,
765
+ transform: rpc.transform,
766
+ viteClientModule: stubs["/@vite/client"]
767
+ });
768
+ const executor = await startVitestExecutor({
769
+ context,
770
+ moduleCache: state.moduleCache,
771
+ state,
772
+ externalModulesExecutor,
773
+ requestStubs: stubs
774
+ });
775
+ context.__vitest_mocker__ = executor.mocker;
776
+ const { run } = await executor.importExternalModule(entryFile);
777
+ const fileSpecs = ctx.files.map((f) => typeof f === "string" ? {
778
+ filepath: f,
779
+ testLocations: undefined
780
+ } : f);
781
+ try {
782
+ await run(method, fileSpecs, ctx.config, executor);
783
+ } finally {
784
+ await vm.teardown?.();
785
+ state.environmentTeardownRun = true;
786
+ }
787
+ }
788
+
789
+ export { runVmTests as r };