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