vitest 3.1.0-beta.1 → 3.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 (88) hide show
  1. package/LICENSE.md +29 -0
  2. package/dist/browser.js +4 -4
  3. package/dist/chunks/base.bV8rwssx.js +41 -0
  4. package/dist/chunks/benchmark.BKUatJGy.js +39 -0
  5. package/dist/chunks/cac.1WcTh-zl.js +1529 -0
  6. package/dist/chunks/{cli-api.BwkkJsRe.js → cli-api.2yb7XCwB.js} +4640 -5072
  7. package/dist/chunks/console.D6t261w0.js +173 -0
  8. package/dist/chunks/constants.BZZyIeIE.js +43 -0
  9. package/dist/chunks/coverage.0iPg4Wrz.js +33 -0
  10. package/dist/chunks/{coverage.gV8doR2Y.js → coverage.SfnlalVs.js} +2424 -2482
  11. package/dist/chunks/creator.CuL7xDWI.js +705 -0
  12. package/dist/chunks/date.CDOsz-HY.js +53 -0
  13. package/dist/chunks/defaults.DmfNPoe5.js +114 -0
  14. package/dist/chunks/{env.D4Lgay0q.js → env.Dq0hM4Xv.js} +1 -1
  15. package/dist/chunks/execute.CwmnH2oH.js +791 -0
  16. package/dist/chunks/git.DXfdBEfR.js +74 -0
  17. package/dist/chunks/{globals.BEpDe-k3.js → globals.DCbUWjip.js} +10 -10
  18. package/dist/chunks/{index.D7Ny8f_s.js → index.BDobFbcz.js} +6 -7
  19. package/dist/chunks/index.CwHmn5H5.js +2422 -0
  20. package/dist/chunks/index.DFXFpH3w.js +607 -0
  21. package/dist/chunks/index.VfYQ6MXY.js +104 -0
  22. package/dist/chunks/inspector.DbDkSkFn.js +54 -0
  23. package/dist/chunks/node.IqGoMrm4.js +15 -0
  24. package/dist/chunks/{reporters.d.r7poTZjA.d.ts → reporters.d.CfRkRKN2.d.ts} +52 -20
  25. package/dist/chunks/rpc.DGgL5dw7.js +92 -0
  26. package/dist/chunks/run-once.I7PpBOk1.js +47 -0
  27. package/dist/chunks/runBaseTests.CqmKSG99.js +134 -0
  28. package/dist/chunks/setup-common.DEGDGBiA.js +88 -0
  29. package/dist/chunks/{typechecker.BlF3eHsb.js → typechecker.CG0zmr19.js} +620 -622
  30. package/dist/chunks/utils.BfxieIyZ.js +66 -0
  31. package/dist/chunks/utils.CtocqOoE.js +72 -0
  32. package/dist/chunks/utils.Lot3J_8U.js +194 -0
  33. package/dist/chunks/{vi.nSCvwQ7l.js → vi.B-PuvDzu.js} +878 -1019
  34. package/dist/chunks/vite.d.4pkSbgmp.d.ts +23 -0
  35. package/dist/chunks/vm.Lp7mPCVW.js +796 -0
  36. package/dist/cli.js +2 -2
  37. package/dist/config.cjs +97 -103
  38. package/dist/config.d.ts +6 -4
  39. package/dist/config.js +6 -6
  40. package/dist/coverage.d.ts +2 -1
  41. package/dist/coverage.js +7 -7
  42. package/dist/environments.js +1 -1
  43. package/dist/execute.d.ts +0 -2
  44. package/dist/execute.js +1 -1
  45. package/dist/index.d.ts +6 -5
  46. package/dist/index.js +6 -6
  47. package/dist/node.d.ts +17 -6
  48. package/dist/node.js +36 -45
  49. package/dist/path.js +1 -4
  50. package/dist/reporters.d.ts +2 -1
  51. package/dist/reporters.js +4 -4
  52. package/dist/runners.js +231 -267
  53. package/dist/snapshot.js +2 -2
  54. package/dist/suite.js +2 -2
  55. package/dist/worker.js +98 -114
  56. package/dist/workers/forks.js +22 -22
  57. package/dist/workers/runVmTests.js +61 -66
  58. package/dist/workers/threads.js +13 -13
  59. package/dist/workers/vmForks.js +24 -24
  60. package/dist/workers/vmThreads.js +15 -15
  61. package/dist/workers.d.ts +2 -1
  62. package/dist/workers.js +10 -10
  63. package/package.json +17 -17
  64. package/dist/chunks/base.DV59CbtV.js +0 -45
  65. package/dist/chunks/benchmark.DL72EVN-.js +0 -40
  66. package/dist/chunks/cac.BjmXy7OV.js +0 -1664
  67. package/dist/chunks/console.CN7AiMGV.js +0 -179
  68. package/dist/chunks/constants.DTYd6dNH.js +0 -46
  69. package/dist/chunks/coverage.A3sS5-Wm.js +0 -40
  70. package/dist/chunks/creator.BsBnpTzI.js +0 -670
  71. package/dist/chunks/date.W2xKR2qe.js +0 -53
  72. package/dist/chunks/defaults.C2Ndd9wx.js +0 -119
  73. package/dist/chunks/execute.eDH0aFFd.js +0 -839
  74. package/dist/chunks/git.B5SDxu-n.js +0 -69
  75. package/dist/chunks/index.DOyx6FYJ.js +0 -2551
  76. package/dist/chunks/index.K90BXFOx.js +0 -658
  77. package/dist/chunks/index.uXkkC4xl.js +0 -111
  78. package/dist/chunks/inspector.DKLceBVD.js +0 -54
  79. package/dist/chunks/node.AKq966Jp.js +0 -15
  80. package/dist/chunks/rpc.TVf73xOu.js +0 -102
  81. package/dist/chunks/run-once.2ogXb3JV.js +0 -28
  82. package/dist/chunks/runBaseTests.BVrL_ow3.js +0 -142
  83. package/dist/chunks/setup-common.CPvtqi8q.js +0 -96
  84. package/dist/chunks/utils.C8RiOc4B.js +0 -77
  85. package/dist/chunks/utils.Cn0zI1t3.js +0 -68
  86. package/dist/chunks/utils.bLM2atbD.js +0 -198
  87. package/dist/chunks/vite.d.Fvq-NZoa.d.ts +0 -11
  88. package/dist/chunks/vm.jEFQDlX_.js +0 -852
@@ -1,839 +0,0 @@
1
- import fs from 'node:fs';
2
- import { pathToFileURL } from 'node:url';
3
- import vm from 'node:vm';
4
- import { processError } from '@vitest/utils/error';
5
- import { normalize as normalize$1 } from 'pathe';
6
- import { ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
7
- import { isInternalRequest, isNodeBuiltin as isNodeBuiltin$1, isPrimitive, toFilePath } from 'vite-node/utils';
8
- import { distDir } from '../path.js';
9
- import { resolve as resolve$1, isAbsolute as isAbsolute$1 } from 'node:path';
10
- import { MockerRegistry, mockObject, RedirectedModule, AutomockedModule } from '@vitest/mocker';
11
- import { builtinModules } from 'node:module';
12
- import { highlight } from '@vitest/utils';
13
-
14
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
15
- function normalizeWindowsPath(input = "") {
16
- if (!input) {
17
- return input;
18
- }
19
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
20
- }
21
- const _UNC_REGEX = /^[/\\]{2}/;
22
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
23
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
24
- const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
25
- const normalize = function(path) {
26
- if (path.length === 0) {
27
- return ".";
28
- }
29
- path = normalizeWindowsPath(path);
30
- const isUNCPath = path.match(_UNC_REGEX);
31
- const isPathAbsolute = isAbsolute(path);
32
- const trailingSeparator = path[path.length - 1] === "/";
33
- path = normalizeString(path, !isPathAbsolute);
34
- if (path.length === 0) {
35
- if (isPathAbsolute) {
36
- return "/";
37
- }
38
- return trailingSeparator ? "./" : ".";
39
- }
40
- if (trailingSeparator) {
41
- path += "/";
42
- }
43
- if (_DRIVE_LETTER_RE.test(path)) {
44
- path += "/";
45
- }
46
- if (isUNCPath) {
47
- if (!isPathAbsolute) {
48
- return `//./${path}`;
49
- }
50
- return `//${path}`;
51
- }
52
- return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
53
- };
54
- const join = function(...segments) {
55
- let path = "";
56
- for (const seg of segments) {
57
- if (!seg) {
58
- continue;
59
- }
60
- if (path.length > 0) {
61
- const pathTrailing = path[path.length - 1] === "/";
62
- const segLeading = seg[0] === "/";
63
- const both = pathTrailing && segLeading;
64
- if (both) {
65
- path += seg.slice(1);
66
- } else {
67
- path += pathTrailing || segLeading ? seg : `/${seg}`;
68
- }
69
- } else {
70
- path += seg;
71
- }
72
- }
73
- return normalize(path);
74
- };
75
- function cwd() {
76
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
77
- return process.cwd().replace(/\\/g, "/");
78
- }
79
- return "/";
80
- }
81
- const resolve = function(...arguments_) {
82
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
83
- let resolvedPath = "";
84
- let resolvedAbsolute = false;
85
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
86
- const path = index >= 0 ? arguments_[index] : cwd();
87
- if (!path || path.length === 0) {
88
- continue;
89
- }
90
- resolvedPath = `${path}/${resolvedPath}`;
91
- resolvedAbsolute = isAbsolute(path);
92
- }
93
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
94
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
95
- return `/${resolvedPath}`;
96
- }
97
- return resolvedPath.length > 0 ? resolvedPath : ".";
98
- };
99
- function normalizeString(path, allowAboveRoot) {
100
- let res = "";
101
- let lastSegmentLength = 0;
102
- let lastSlash = -1;
103
- let dots = 0;
104
- let char = null;
105
- for (let index = 0; index <= path.length; ++index) {
106
- if (index < path.length) {
107
- char = path[index];
108
- } else if (char === "/") {
109
- break;
110
- } else {
111
- char = "/";
112
- }
113
- if (char === "/") {
114
- if (lastSlash === index - 1 || dots === 1) ;
115
- else if (dots === 2) {
116
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
117
- if (res.length > 2) {
118
- const lastSlashIndex = res.lastIndexOf("/");
119
- if (lastSlashIndex === -1) {
120
- res = "";
121
- lastSegmentLength = 0;
122
- } else {
123
- res = res.slice(0, lastSlashIndex);
124
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
125
- }
126
- lastSlash = index;
127
- dots = 0;
128
- continue;
129
- } else if (res.length > 0) {
130
- res = "";
131
- lastSegmentLength = 0;
132
- lastSlash = index;
133
- dots = 0;
134
- continue;
135
- }
136
- }
137
- if (allowAboveRoot) {
138
- res += res.length > 0 ? "/.." : "..";
139
- lastSegmentLength = 2;
140
- }
141
- } else {
142
- if (res.length > 0) {
143
- res += `/${path.slice(lastSlash + 1, index)}`;
144
- } else {
145
- res = path.slice(lastSlash + 1, index);
146
- }
147
- lastSegmentLength = index - lastSlash - 1;
148
- }
149
- lastSlash = index;
150
- dots = 0;
151
- } else if (char === "." && dots !== -1) {
152
- ++dots;
153
- } else {
154
- dots = -1;
155
- }
156
- }
157
- return res;
158
- }
159
- const isAbsolute = function(p) {
160
- return _IS_ABSOLUTE_RE.test(p);
161
- };
162
- const extname = function(p) {
163
- if (p === "..") return "";
164
- const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
165
- return match && match[1] || "";
166
- };
167
- const dirname = function(p) {
168
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
169
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
170
- segments[0] += "/";
171
- }
172
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
173
- };
174
- const basename = function(p, extension) {
175
- const segments = normalizeWindowsPath(p).split("/");
176
- let lastSegment = "";
177
- for (let i = segments.length - 1; i >= 0; i--) {
178
- const val = segments[i];
179
- if (val) {
180
- lastSegment = val;
181
- break;
182
- }
183
- }
184
- return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
185
- };
186
-
187
- const { existsSync, readdirSync, statSync } = fs;
188
- function findMockRedirect(root, mockPath, external) {
189
- const path = external || mockPath;
190
- if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
191
- let findFile2 = function(mockFolder2, baseOriginal2) {
192
- const files = readdirSync(mockFolder2);
193
- for (const file of files) {
194
- const baseFile = basename(file, extname(file));
195
- if (baseFile === baseOriginal2) {
196
- const path2 = resolve(mockFolder2, file);
197
- if (statSync(path2).isFile()) {
198
- return path2;
199
- } else {
200
- const indexFile = findFile2(path2, "index");
201
- if (indexFile) {
202
- return indexFile;
203
- }
204
- }
205
- }
206
- }
207
- return null;
208
- };
209
- const mockDirname = dirname(path);
210
- const mockFolder = join(root, "__mocks__", mockDirname);
211
- if (!existsSync(mockFolder)) {
212
- return null;
213
- }
214
- const baseOriginal = basename(path);
215
- return findFile2(mockFolder, baseOriginal);
216
- }
217
- const dir = dirname(path);
218
- const baseId = basename(path);
219
- const fullPath = resolve(dir, "__mocks__", baseId);
220
- return existsSync(fullPath) ? fullPath : null;
221
- }
222
- const builtins = /* @__PURE__ */ new Set([
223
- ...builtinModules,
224
- "assert/strict",
225
- "diagnostics_channel",
226
- "dns/promises",
227
- "fs/promises",
228
- "path/posix",
229
- "path/win32",
230
- "readline/promises",
231
- "stream/consumers",
232
- "stream/promises",
233
- "stream/web",
234
- "timers/promises",
235
- "util/types",
236
- "wasi"
237
- ]);
238
- const prefixedBuiltins = /* @__PURE__ */ new Set([
239
- "node:sea",
240
- "node:sqlite",
241
- "node:test",
242
- "node:test/reporters"
243
- ]);
244
- const NODE_BUILTIN_NAMESPACE = "node:";
245
- function isNodeBuiltin(id) {
246
- if (prefixedBuiltins.has(id)) {
247
- return true;
248
- }
249
- return builtins.has(
250
- id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id
251
- );
252
- }
253
-
254
- const spyModulePath = resolve$1(distDir, "spy.js");
255
- class VitestMocker {
256
- constructor(executor) {
257
- this.executor = executor;
258
- const context = this.executor.options.context;
259
- if (context) {
260
- this.primitives = vm.runInContext(
261
- "({ Object, Error, Function, RegExp, Symbol, Array, Map })",
262
- context
263
- );
264
- } else {
265
- this.primitives = {
266
- Object,
267
- Error,
268
- Function,
269
- RegExp,
270
- Symbol: globalThis.Symbol,
271
- Array,
272
- Map
273
- };
274
- }
275
- const Symbol2 = this.primitives.Symbol;
276
- this.filterPublicKeys = [
277
- "__esModule",
278
- Symbol2.asyncIterator,
279
- Symbol2.hasInstance,
280
- Symbol2.isConcatSpreadable,
281
- Symbol2.iterator,
282
- Symbol2.match,
283
- Symbol2.matchAll,
284
- Symbol2.replace,
285
- Symbol2.search,
286
- Symbol2.split,
287
- Symbol2.species,
288
- Symbol2.toPrimitive,
289
- Symbol2.toStringTag,
290
- Symbol2.unscopables
291
- ];
292
- }
293
- static pendingIds = [];
294
- spyModule;
295
- primitives;
296
- filterPublicKeys;
297
- registries = /* @__PURE__ */ new Map();
298
- mockContext = {
299
- callstack: null
300
- };
301
- get root() {
302
- return this.executor.options.root;
303
- }
304
- get moduleCache() {
305
- return this.executor.moduleCache;
306
- }
307
- get moduleDirectories() {
308
- return this.executor.options.moduleDirectories || [];
309
- }
310
- async initializeSpyModule() {
311
- this.spyModule = await this.executor.executeId(spyModulePath);
312
- }
313
- getMockerRegistry() {
314
- const suite = this.getSuiteFilepath();
315
- if (!this.registries.has(suite)) {
316
- this.registries.set(suite, new MockerRegistry());
317
- }
318
- return this.registries.get(suite);
319
- }
320
- reset() {
321
- this.registries.clear();
322
- }
323
- deleteCachedItem(id) {
324
- const mockId = this.getMockPath(id);
325
- if (this.moduleCache.has(mockId)) {
326
- this.moduleCache.delete(mockId);
327
- }
328
- }
329
- isModuleDirectory(path) {
330
- return this.moduleDirectories.some((dir) => path.includes(dir));
331
- }
332
- getSuiteFilepath() {
333
- return this.executor.state.filepath || "global";
334
- }
335
- createError(message, codeFrame) {
336
- const Error2 = this.primitives.Error;
337
- const error = new Error2(message);
338
- Object.assign(error, { codeFrame });
339
- return error;
340
- }
341
- async resolvePath(rawId, importer) {
342
- let id;
343
- let fsPath;
344
- try {
345
- [id, fsPath] = await this.executor.originalResolveUrl(rawId, importer);
346
- } catch (error) {
347
- if (error.code === "ERR_MODULE_NOT_FOUND") {
348
- const { id: unresolvedId } = error[Symbol.for("vitest.error.not_found.data")];
349
- id = unresolvedId;
350
- fsPath = unresolvedId;
351
- } else {
352
- throw error;
353
- }
354
- }
355
- const external = !isAbsolute$1(fsPath) || this.isModuleDirectory(fsPath) ? rawId : null;
356
- return {
357
- id,
358
- fsPath,
359
- external: external ? this.normalizePath(external) : external
360
- };
361
- }
362
- async resolveMocks() {
363
- if (!VitestMocker.pendingIds.length) {
364
- return;
365
- }
366
- await Promise.all(
367
- VitestMocker.pendingIds.map(async (mock) => {
368
- const { fsPath, external } = await this.resolvePath(
369
- mock.id,
370
- mock.importer
371
- );
372
- if (mock.action === "unmock") {
373
- this.unmockPath(fsPath);
374
- }
375
- if (mock.action === "mock") {
376
- this.mockPath(
377
- mock.id,
378
- fsPath,
379
- external,
380
- mock.type,
381
- mock.factory
382
- );
383
- }
384
- })
385
- );
386
- VitestMocker.pendingIds = [];
387
- }
388
- async callFunctionMock(dep, mock) {
389
- const cached = this.moduleCache.get(dep)?.exports;
390
- if (cached) {
391
- return cached;
392
- }
393
- const exports = await mock.resolve();
394
- const moduleExports = new Proxy(exports, {
395
- get: (target, prop) => {
396
- const val = target[prop];
397
- if (prop === "then") {
398
- if (target instanceof Promise) {
399
- return target.then.bind(target);
400
- }
401
- } else if (!(prop in target)) {
402
- if (this.filterPublicKeys.includes(prop)) {
403
- return void 0;
404
- }
405
- throw this.createError(
406
- `[vitest] No "${String(prop)}" export is defined on the "${mock.raw}" mock. Did you forget to return it from "vi.mock"?
407
- If you need to partially mock a module, you can use "importOriginal" helper inside:
408
- `,
409
- highlight(`vi.mock(import("${mock.raw}"), async (importOriginal) => {
410
- const actual = await importOriginal()
411
- return {
412
- ...actual,
413
- // your mocked methods
414
- }
415
- })`)
416
- );
417
- }
418
- return val;
419
- }
420
- });
421
- this.moduleCache.set(dep, { exports: moduleExports });
422
- return moduleExports;
423
- }
424
- // public method to avoid circular dependency
425
- getMockContext() {
426
- return this.mockContext;
427
- }
428
- // path used to store mocked dependencies
429
- getMockPath(dep) {
430
- return `mock:${dep}`;
431
- }
432
- getDependencyMock(id) {
433
- const registry = this.getMockerRegistry();
434
- return registry.get(id);
435
- }
436
- normalizePath(path) {
437
- return this.moduleCache.normalizePath(path);
438
- }
439
- resolveMockPath(mockPath, external) {
440
- return findMockRedirect(this.root, mockPath, external);
441
- }
442
- mockObject(object, mockExports = {}, behavior = "automock") {
443
- const spyOn = this.spyModule?.spyOn;
444
- if (!spyOn) {
445
- throw this.createError(
446
- "[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction."
447
- );
448
- }
449
- return mockObject({
450
- globalConstructors: this.primitives,
451
- spyOn,
452
- type: behavior
453
- }, object, mockExports);
454
- }
455
- unmockPath(path) {
456
- const registry = this.getMockerRegistry();
457
- const id = this.normalizePath(path);
458
- registry.delete(id);
459
- this.deleteCachedItem(id);
460
- }
461
- mockPath(originalId, path, external, mockType, factory) {
462
- const registry = this.getMockerRegistry();
463
- const id = this.normalizePath(path);
464
- if (mockType === "manual") {
465
- registry.register("manual", originalId, id, factory);
466
- } else if (mockType === "autospy") {
467
- registry.register("autospy", originalId, id);
468
- } else {
469
- const redirect = this.resolveMockPath(id, external);
470
- if (redirect) {
471
- registry.register("redirect", originalId, id, redirect);
472
- } else {
473
- registry.register("automock", originalId, id);
474
- }
475
- }
476
- this.deleteCachedItem(id);
477
- }
478
- async importActual(rawId, importer, callstack) {
479
- const { id, fsPath } = await this.resolvePath(rawId, importer);
480
- const result = await this.executor.cachedRequest(
481
- id,
482
- fsPath,
483
- callstack || [importer]
484
- );
485
- return result;
486
- }
487
- async importMock(rawId, importee) {
488
- const { id, fsPath, external } = await this.resolvePath(rawId, importee);
489
- const normalizedId = this.normalizePath(fsPath);
490
- let mock = this.getDependencyMock(normalizedId);
491
- if (!mock) {
492
- const redirect = this.resolveMockPath(normalizedId, external);
493
- if (redirect) {
494
- mock = new RedirectedModule(rawId, normalizedId, redirect);
495
- } else {
496
- mock = new AutomockedModule(rawId, normalizedId);
497
- }
498
- }
499
- if (mock.type === "automock" || mock.type === "autospy") {
500
- const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
501
- return this.mockObject(mod, {}, mock.type);
502
- }
503
- if (mock.type === "manual") {
504
- return this.callFunctionMock(fsPath, mock);
505
- }
506
- return this.executor.dependencyRequest(mock.redirect, mock.redirect, [importee]);
507
- }
508
- async requestWithMock(url, callstack) {
509
- const id = this.normalizePath(url);
510
- const mock = this.getDependencyMock(id);
511
- if (!mock) {
512
- return;
513
- }
514
- const mockPath = this.getMockPath(id);
515
- if (mock.type === "automock" || mock.type === "autospy") {
516
- const cache = this.moduleCache.get(mockPath);
517
- if (cache.exports) {
518
- return cache.exports;
519
- }
520
- const exports = {};
521
- this.moduleCache.set(mockPath, { exports });
522
- const mod = await this.executor.directRequest(url, url, callstack);
523
- this.mockObject(mod, exports, mock.type);
524
- return exports;
525
- }
526
- if (mock.type === "manual" && !callstack.includes(mockPath) && !callstack.includes(url)) {
527
- try {
528
- callstack.push(mockPath);
529
- this.mockContext.callstack = callstack;
530
- return await this.callFunctionMock(mockPath, mock);
531
- } finally {
532
- this.mockContext.callstack = null;
533
- const indexMock = callstack.indexOf(mockPath);
534
- callstack.splice(indexMock, 1);
535
- }
536
- } else if (mock.type === "redirect" && !callstack.includes(mock.redirect)) {
537
- return mock.redirect;
538
- }
539
- }
540
- queueMock(id, importer, factoryOrOptions) {
541
- const mockType = getMockType(factoryOrOptions);
542
- VitestMocker.pendingIds.push({
543
- action: "mock",
544
- id,
545
- importer,
546
- factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
547
- type: mockType
548
- });
549
- }
550
- queueUnmock(id, importer) {
551
- VitestMocker.pendingIds.push({
552
- action: "unmock",
553
- id,
554
- importer
555
- });
556
- }
557
- }
558
- function getMockType(factoryOrOptions) {
559
- if (!factoryOrOptions) {
560
- return "automock";
561
- }
562
- if (typeof factoryOrOptions === "function") {
563
- return "manual";
564
- }
565
- return factoryOrOptions.spy ? "autospy" : "automock";
566
- }
567
-
568
- const normalizedDistDir = normalize$1(distDir);
569
- const { readFileSync } = fs;
570
- async function createVitestExecutor(options) {
571
- const runner = new VitestExecutor(options);
572
- await runner.executeId("/@vite/env");
573
- await runner.mocker.initializeSpyModule();
574
- return runner;
575
- }
576
- const externalizeMap = /* @__PURE__ */ new Map();
577
- const bareVitestRegexp = /^@?vitest(?:\/|$)/;
578
- const dispose = [];
579
- function listenForErrors(state) {
580
- dispose.forEach((fn) => fn());
581
- dispose.length = 0;
582
- function catchError(err, type, event) {
583
- const worker = state();
584
- if (worker.current?.type === "test") {
585
- const listeners = process.listeners(event);
586
- if (listeners.length > 1) {
587
- return;
588
- }
589
- }
590
- const error = processError(err);
591
- if (!isPrimitive(error)) {
592
- error.VITEST_TEST_NAME = worker.current?.type === "test" ? worker.current.name : void 0;
593
- if (worker.filepath) {
594
- error.VITEST_TEST_PATH = worker.filepath;
595
- }
596
- error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
597
- }
598
- state().rpc.onUnhandledError(error, type);
599
- }
600
- const uncaughtException = (e) => catchError(e, "Uncaught Exception", "uncaughtException");
601
- const unhandledRejection = (e) => catchError(e, "Unhandled Rejection", "unhandledRejection");
602
- process.on("uncaughtException", uncaughtException);
603
- process.on("unhandledRejection", unhandledRejection);
604
- dispose.push(() => {
605
- process.off("uncaughtException", uncaughtException);
606
- process.off("unhandledRejection", unhandledRejection);
607
- });
608
- }
609
- async function startVitestExecutor(options) {
610
- const state = () => (
611
- // @ts-expect-error injected untyped global
612
- globalThis.__vitest_worker__ || options.state
613
- );
614
- const rpc = () => state().rpc;
615
- process.exit = (code = process.exitCode || 0) => {
616
- throw new Error(`process.exit unexpectedly called with "${code}"`);
617
- };
618
- listenForErrors(state);
619
- const getTransformMode = () => {
620
- return state().environment.transformMode ?? "ssr";
621
- };
622
- return await createVitestExecutor({
623
- async fetchModule(id) {
624
- if (externalizeMap.has(id)) {
625
- return { externalize: externalizeMap.get(id) };
626
- }
627
- if (id.includes(distDir) || id.includes(normalizedDistDir)) {
628
- const { path } = toFilePath(id, state().config.root);
629
- const externalize = pathToFileURL(path).toString();
630
- externalizeMap.set(id, externalize);
631
- return { externalize };
632
- }
633
- if (bareVitestRegexp.test(id)) {
634
- externalizeMap.set(id, id);
635
- return { externalize: id };
636
- }
637
- const result = await rpc().fetch(id, getTransformMode());
638
- if (result.id && !result.externalize) {
639
- const code = readFileSync(result.id, "utf-8");
640
- return { code };
641
- }
642
- return result;
643
- },
644
- resolveId(id, importer) {
645
- return rpc().resolveId(id, importer, getTransformMode());
646
- },
647
- get moduleCache() {
648
- return state().moduleCache;
649
- },
650
- get moduleExecutionInfo() {
651
- return state().moduleExecutionInfo;
652
- },
653
- get interopDefault() {
654
- return state().config.deps.interopDefault;
655
- },
656
- get moduleDirectories() {
657
- return state().config.deps.moduleDirectories;
658
- },
659
- get root() {
660
- return state().config.root;
661
- },
662
- get base() {
663
- return state().config.base;
664
- },
665
- ...options
666
- });
667
- }
668
- function updateStyle(id, css) {
669
- if (typeof document === "undefined") {
670
- return;
671
- }
672
- const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
673
- if (element) {
674
- element.textContent = css;
675
- return;
676
- }
677
- const head = document.querySelector("head");
678
- const style = document.createElement("style");
679
- style.setAttribute("type", "text/css");
680
- style.setAttribute("data-vite-dev-id", id);
681
- style.textContent = css;
682
- head?.appendChild(style);
683
- }
684
- function removeStyle(id) {
685
- if (typeof document === "undefined") {
686
- return;
687
- }
688
- const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
689
- if (sheet) {
690
- document.head.removeChild(sheet);
691
- }
692
- }
693
- function getDefaultRequestStubs(context) {
694
- if (!context) {
695
- const clientStub2 = {
696
- ...DEFAULT_REQUEST_STUBS["@vite/client"],
697
- updateStyle,
698
- removeStyle
699
- };
700
- return {
701
- "/@vite/client": clientStub2,
702
- "@vite/client": clientStub2
703
- };
704
- }
705
- const clientStub = vm.runInContext(
706
- `(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
707
- context
708
- )(DEFAULT_REQUEST_STUBS["@vite/client"]);
709
- return {
710
- "/@vite/client": clientStub,
711
- "@vite/client": clientStub
712
- };
713
- }
714
- class VitestExecutor extends ViteNodeRunner {
715
- constructor(options) {
716
- super({
717
- ...options,
718
- // interop is done inside the external executor instead
719
- interopDefault: options.context ? false : options.interopDefault
720
- });
721
- this.options = options;
722
- this.mocker = new VitestMocker(this);
723
- if (!options.context) {
724
- Object.defineProperty(globalThis, "__vitest_mocker__", {
725
- value: this.mocker,
726
- writable: true,
727
- configurable: true
728
- });
729
- this.primitives = { Object, Reflect, Symbol };
730
- } else if (options.externalModulesExecutor) {
731
- this.primitives = vm.runInContext(
732
- "({ Object, Reflect, Symbol })",
733
- options.context
734
- );
735
- this.externalModules = options.externalModulesExecutor;
736
- } else {
737
- throw new Error(
738
- "When context is provided, externalModulesExecutor must be provided as well."
739
- );
740
- }
741
- }
742
- mocker;
743
- externalModules;
744
- primitives;
745
- getContextPrimitives() {
746
- return this.primitives;
747
- }
748
- get state() {
749
- return globalThis.__vitest_worker__ || this.options.state;
750
- }
751
- get moduleExecutionInfo() {
752
- return this.options.moduleExecutionInfo;
753
- }
754
- shouldResolveId(id, _importee) {
755
- if (isInternalRequest(id) || id.startsWith("data:")) {
756
- return false;
757
- }
758
- const transformMode = this.state.environment?.transformMode ?? "ssr";
759
- return transformMode === "ssr" ? !isNodeBuiltin$1(id) : !id.startsWith("node:");
760
- }
761
- async originalResolveUrl(id, importer) {
762
- return super.resolveUrl(id, importer);
763
- }
764
- async resolveUrl(id, importer) {
765
- if (VitestMocker.pendingIds.length) {
766
- await this.mocker.resolveMocks();
767
- }
768
- if (importer && importer.startsWith("mock:")) {
769
- importer = importer.slice(5);
770
- }
771
- try {
772
- return await super.resolveUrl(id, importer);
773
- } catch (error) {
774
- if (error.code === "ERR_MODULE_NOT_FOUND") {
775
- const { id: id2 } = error[Symbol.for("vitest.error.not_found.data")];
776
- const path = this.mocker.normalizePath(id2);
777
- const mock = this.mocker.getDependencyMock(path);
778
- if (mock !== void 0) {
779
- return [id2, id2];
780
- }
781
- }
782
- throw error;
783
- }
784
- }
785
- async runModule(context, transformed) {
786
- const vmContext = this.options.context;
787
- if (!vmContext || !this.externalModules) {
788
- return super.runModule(context, transformed);
789
- }
790
- const codeDefinition = `'use strict';async (${Object.keys(context).join(
791
- ","
792
- )})=>{{`;
793
- const code = `${codeDefinition}${transformed}
794
- }}`;
795
- const options = {
796
- filename: context.__filename,
797
- lineOffset: 0,
798
- columnOffset: -codeDefinition.length
799
- };
800
- this.options.moduleExecutionInfo?.set(options.filename, { startOffset: codeDefinition.length });
801
- const fn = vm.runInContext(code, vmContext, {
802
- ...options,
803
- // if we encountered an import, it's not inlined
804
- importModuleDynamically: this.externalModules.importModuleDynamically
805
- });
806
- await fn(...Object.values(context));
807
- }
808
- async importExternalModule(path) {
809
- if (this.externalModules) {
810
- return this.externalModules.import(path);
811
- }
812
- return super.importExternalModule(path);
813
- }
814
- async dependencyRequest(id, fsPath, callstack) {
815
- const mocked = await this.mocker.requestWithMock(fsPath, callstack);
816
- if (typeof mocked === "string") {
817
- return super.dependencyRequest(mocked, mocked, callstack);
818
- }
819
- if (mocked && typeof mocked === "object") {
820
- return mocked;
821
- }
822
- return super.dependencyRequest(id, fsPath, callstack);
823
- }
824
- prepareContext(context) {
825
- if (this.state.filepath && normalize$1(this.state.filepath) === normalize$1(context.__filename)) {
826
- const globalNamespace = this.options.context || globalThis;
827
- Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", {
828
- // @ts-expect-error injected untyped global
829
- get: () => globalNamespace.__vitest_index__
830
- });
831
- }
832
- if (this.options.context && this.externalModules) {
833
- context.require = this.externalModules.createRequire(context.__filename);
834
- }
835
- return context;
836
- }
837
- }
838
-
839
- export { VitestExecutor as V, getDefaultRequestStubs as g, startVitestExecutor as s };