vitest 4.0.0-beta.1 → 4.0.0-beta.10

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/LICENSE.md +2 -2
  2. package/dist/browser.d.ts +13 -14
  3. package/dist/browser.js +6 -5
  4. package/dist/chunks/base.Cjha6usc.js +129 -0
  5. package/dist/chunks/{benchmark.CYdenmiT.js → benchmark.CJUa-Hsa.js} +6 -8
  6. package/dist/chunks/{benchmark.d.BwvBVTda.d.ts → benchmark.d.DAaHLpsq.d.ts} +4 -4
  7. package/dist/chunks/{browser.d.q8Z0P0q1.d.ts → browser.d.yFAklsD1.d.ts} +5 -5
  8. package/dist/chunks/{cac.D3EzDDZd.js → cac.DCxo_nSu.js} +70 -152
  9. package/dist/chunks/{cli-api.Dn5gKePv.js → cli-api.BJJXh9BV.js} +1330 -1677
  10. package/dist/chunks/{config.d.HJdfX-8k.d.ts → config.d.B_LthbQq.d.ts} +58 -63
  11. package/dist/chunks/{console.CtFJOzRO.js → console.7h5kHUIf.js} +34 -70
  12. package/dist/chunks/{constants.DnKduX2e.js → constants.D_Q9UYh-.js} +1 -9
  13. package/dist/chunks/{coverage.Cwa-XhJt.js → coverage.BCU-r2QL.js} +515 -781
  14. package/dist/chunks/{coverage.DVF1vEu8.js → coverage.D_JHT54q.js} +2 -2
  15. package/dist/chunks/{coverage.d.S9RMNXIe.d.ts → coverage.d.BZtK59WP.d.ts} +10 -8
  16. package/dist/chunks/{creator.GK6I-cL4.js → creator.08Gi-vCA.js} +93 -77
  17. package/dist/chunks/{date.Bq6ZW5rf.js → date.-jtEtIeV.js} +6 -17
  18. package/dist/chunks/{environment.d.CUq4cUgQ.d.ts → environment.d.BsToaxti.d.ts} +27 -6
  19. package/dist/chunks/{git.BVQ8w_Sw.js → git.BFNcloKD.js} +1 -2
  20. package/dist/chunks/{global.d.CVbXEflG.d.ts → global.d.BK3X7FW1.d.ts} +2 -5
  21. package/dist/chunks/{globals.Cxal6MLI.js → globals.DG-S3xFe.js} +8 -8
  22. package/dist/chunks/{index.CZI_8rVt.js → index.BIP7prJq.js} +289 -608
  23. package/dist/chunks/{index.B521nVV-.js → index.Bgo3tNWt.js} +23 -4
  24. package/dist/chunks/{index.TfbsX-3I.js → index.BjKEiSn0.js} +14 -24
  25. package/dist/chunks/{index.BWf_gE5n.js → index.CMfqw92x.js} +7 -6
  26. package/dist/chunks/{index.CmSc2RE5.js → index.DIWhzsUh.js} +72 -118
  27. package/dist/chunks/{inspector.C914Efll.js → inspector.CvQD-Nie.js} +10 -25
  28. package/dist/chunks/moduleRunner.d.D9nBoC4p.d.ts +201 -0
  29. package/dist/chunks/moduleTransport.I-bgQy0S.js +19 -0
  30. package/dist/chunks/{node.fjCdwEIl.js → node.CyipiPvJ.js} +1 -1
  31. package/dist/chunks/{plugin.d.C2EcJUjo.d.ts → plugin.d.BMVSnsGV.d.ts} +1 -1
  32. package/dist/chunks/{reporters.d.DxZg19fy.d.ts → reporters.d.BUWjmRYq.d.ts} +1226 -1291
  33. package/dist/chunks/resolveSnapshotEnvironment.Bkht6Yor.js +81 -0
  34. package/dist/chunks/resolver.Bx6lE0iq.js +119 -0
  35. package/dist/chunks/rpc.BKr6mtxz.js +65 -0
  36. package/dist/chunks/{setup-common.D7ZqXFx-.js → setup-common.uiMcU3cv.js} +17 -29
  37. package/dist/chunks/startModuleRunner.p67gbNo9.js +665 -0
  38. package/dist/chunks/{suite.d.FvehnV49.d.ts → suite.d.BJWk38HB.d.ts} +1 -1
  39. package/dist/chunks/test.BiqSKISg.js +214 -0
  40. package/dist/chunks/{typechecker.CVytUJuF.js → typechecker.DB-fIMaH.js} +144 -213
  41. package/dist/chunks/{utils.CAioKnHs.js → utils.C2YI6McM.js} +5 -14
  42. package/dist/chunks/{utils.XdZDrNZV.js → utils.D2R2NiOH.js} +8 -27
  43. package/dist/chunks/{vi.bdSIJ99Y.js → vi.ZPgvtBao.js} +156 -305
  44. package/dist/chunks/{vm.BThCzidc.js → vm.Ca0Y0W5f.js} +116 -226
  45. package/dist/chunks/{worker.d.DoNjFAiv.d.ts → worker.d.BDsXGkwh.d.ts} +28 -22
  46. package/dist/chunks/{worker.d.CmvJfRGs.d.ts → worker.d.BNcX_2mH.d.ts} +1 -1
  47. package/dist/cli.js +4 -4
  48. package/dist/config.cjs +3 -9
  49. package/dist/config.d.ts +49 -54
  50. package/dist/config.js +1 -1
  51. package/dist/coverage.d.ts +27 -26
  52. package/dist/coverage.js +6 -7
  53. package/dist/environments.d.ts +9 -13
  54. package/dist/environments.js +1 -1
  55. package/dist/index.d.ts +38 -45
  56. package/dist/index.js +7 -9
  57. package/dist/module-evaluator.d.ts +13 -0
  58. package/dist/module-evaluator.js +276 -0
  59. package/dist/module-runner.js +15 -0
  60. package/dist/node.d.ts +40 -41
  61. package/dist/node.js +23 -33
  62. package/dist/reporters.d.ts +12 -13
  63. package/dist/reporters.js +3 -3
  64. package/dist/runners.d.ts +3 -3
  65. package/dist/runners.js +13 -232
  66. package/dist/snapshot.js +2 -2
  67. package/dist/suite.d.ts +2 -2
  68. package/dist/suite.js +2 -2
  69. package/dist/worker.js +90 -47
  70. package/dist/workers/forks.js +34 -10
  71. package/dist/workers/runVmTests.js +36 -56
  72. package/dist/workers/threads.js +34 -10
  73. package/dist/workers/vmForks.js +11 -10
  74. package/dist/workers/vmThreads.js +11 -10
  75. package/dist/workers.d.ts +5 -4
  76. package/dist/workers.js +35 -17
  77. package/globals.d.ts +17 -17
  78. package/package.json +32 -31
  79. package/dist/chunks/base.Bj3pWTr1.js +0 -38
  80. package/dist/chunks/execute.B7h3T_Hc.js +0 -708
  81. package/dist/chunks/index.D-VkfKhf.js +0 -105
  82. package/dist/chunks/rpc.CsFtxqeq.js +0 -83
  83. package/dist/chunks/runBaseTests.BC7ZIH5L.js +0 -129
  84. package/dist/execute.d.ts +0 -148
  85. package/dist/execute.js +0 -13
@@ -0,0 +1,665 @@
1
+ import fs from 'node:fs';
2
+ import { builtinModules, isBuiltin } from 'node:module';
3
+ import { highlight, isBareImport } from '@vitest/utils';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { normalize as normalize$1, join as join$1 } from 'pathe';
6
+ import { distDir } from '../path.js';
7
+ import { processError } from '@vitest/utils/error';
8
+ import { VitestModuleEvaluator, unwrapId } from '../module-evaluator.js';
9
+ import { resolve as resolve$1, isAbsolute as isAbsolute$1 } from 'node:path';
10
+ import vm from 'node:vm';
11
+ import { MockerRegistry, mockObject, RedirectedModule, AutomockedModule } from '@vitest/mocker';
12
+ import * as viteModuleRunner from 'vite/module-runner';
13
+ import { V as VitestTransport } from './moduleTransport.I-bgQy0S.js';
14
+
15
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
16
+ function normalizeWindowsPath(input = "") {
17
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
18
+ }
19
+ const _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _EXTNAME_RE = /.(\.[^./]+|\.)$/, normalize = function(path) {
20
+ if (path.length === 0) return ".";
21
+ path = normalizeWindowsPath(path);
22
+ const isUNCPath = path.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path), trailingSeparator = path[path.length - 1] === "/";
23
+ if (path = normalizeString(path, !isPathAbsolute), path.length === 0) return isPathAbsolute ? "/" : trailingSeparator ? "./" : ".";
24
+ if (trailingSeparator) path += "/";
25
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
26
+ return isUNCPath ? isPathAbsolute ? `//${path}` : `//./${path}` : isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
27
+ }, join = function(...segments) {
28
+ let path = "";
29
+ for (const seg of segments) {
30
+ if (!seg) continue;
31
+ if (path.length > 0) {
32
+ const pathTrailing = path[path.length - 1] === "/", segLeading = seg[0] === "/", both = pathTrailing && segLeading;
33
+ if (both) path += seg.slice(1);
34
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
35
+ } else path += seg;
36
+ }
37
+ return normalize(path);
38
+ };
39
+ function cwd$1() {
40
+ return typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd().replace(/\\/g, "/") : "/";
41
+ }
42
+ const resolve = function(...arguments_) {
43
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
44
+ let resolvedPath = "", resolvedAbsolute = false;
45
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
46
+ const path = index >= 0 ? arguments_[index] : cwd$1();
47
+ !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
48
+ }
49
+ return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
50
+ };
51
+ function normalizeString(path, allowAboveRoot) {
52
+ let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
53
+ for (let index = 0; index <= path.length; ++index) {
54
+ if (index < path.length) char = path[index];
55
+ else if (char === "/") break;
56
+ else char = "/";
57
+ if (char === "/") {
58
+ if (lastSlash === index - 1 || dots === 1);
59
+ else if (dots === 2) {
60
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
61
+ if (res.length > 2) {
62
+ const lastSlashIndex = res.lastIndexOf("/");
63
+ if (lastSlashIndex === -1) res = "", lastSegmentLength = 0;
64
+ else res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
65
+ lastSlash = index, dots = 0;
66
+ continue;
67
+ } else if (res.length > 0) {
68
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
69
+ continue;
70
+ }
71
+ }
72
+ if (allowAboveRoot) res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2;
73
+ } else {
74
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
75
+ else res = path.slice(lastSlash + 1, index);
76
+ lastSegmentLength = index - lastSlash - 1;
77
+ }
78
+ lastSlash = index, dots = 0;
79
+ } else if (char === "." && dots !== -1) ++dots;
80
+ else dots = -1;
81
+ }
82
+ return res;
83
+ }
84
+ const isAbsolute = function(p) {
85
+ return _IS_ABSOLUTE_RE.test(p);
86
+ }, extname = function(p) {
87
+ if (p === "..") return "";
88
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
89
+ return match && match[1] || "";
90
+ }, dirname = function(p) {
91
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
92
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
93
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
94
+ }, basename = function(p, extension) {
95
+ const segments = normalizeWindowsPath(p).split("/");
96
+ let lastSegment = "";
97
+ for (let i = segments.length - 1; i >= 0; i--) {
98
+ const val = segments[i];
99
+ if (val) {
100
+ lastSegment = val;
101
+ break;
102
+ }
103
+ }
104
+ return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
105
+ };
106
+
107
+ const { existsSync, readdirSync, statSync } = fs;
108
+ function findMockRedirect(root, mockPath, external) {
109
+ const path = external || mockPath;
110
+ // it's a node_module alias
111
+ // all mocks should be inside <root>/__mocks__
112
+ if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
113
+ const mockDirname = dirname(path), mockFolder = join(root, "__mocks__", mockDirname);
114
+ if (!existsSync(mockFolder)) return null;
115
+ const baseOriginal = basename(path);
116
+ function findFile(mockFolder, baseOriginal) {
117
+ const files = readdirSync(mockFolder);
118
+ for (const file of files) {
119
+ const baseFile = basename(file, extname(file));
120
+ if (baseFile === baseOriginal) {
121
+ const path = resolve(mockFolder, file);
122
+ // if the same name, return the file
123
+ if (statSync(path).isFile()) return path;
124
+ {
125
+ // find folder/index.{js,ts}
126
+ const indexFile = findFile(path, "index");
127
+ if (indexFile) return indexFile;
128
+ }
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ return findFile(mockFolder, baseOriginal);
134
+ }
135
+ const dir = dirname(path), baseId = basename(path), fullPath = resolve(dir, "__mocks__", baseId);
136
+ return existsSync(fullPath) ? fullPath : null;
137
+ }
138
+ const builtins = new Set([
139
+ ...builtinModules,
140
+ "assert/strict",
141
+ "diagnostics_channel",
142
+ "dns/promises",
143
+ "fs/promises",
144
+ "path/posix",
145
+ "path/win32",
146
+ "readline/promises",
147
+ "stream/consumers",
148
+ "stream/promises",
149
+ "stream/web",
150
+ "timers/promises",
151
+ "util/types",
152
+ "wasi"
153
+ ]), prefixedBuiltins$1 = new Set([
154
+ "node:sea",
155
+ "node:sqlite",
156
+ "node:test",
157
+ "node:test/reporters"
158
+ ]), NODE_BUILTIN_NAMESPACE = "node:";
159
+ function isNodeBuiltin(id) {
160
+ return prefixedBuiltins$1.has(id) ? true : builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(5) : id);
161
+ }
162
+
163
+ const spyModulePath = resolve$1(distDir, "spy.js");
164
+ class VitestMocker {
165
+ static pendingIds = [];
166
+ spyModule;
167
+ primitives;
168
+ filterPublicKeys;
169
+ registries = /* @__PURE__ */ new Map();
170
+ mockContext = { callstack: null };
171
+ constructor(moduleRunner, options) {
172
+ this.moduleRunner = moduleRunner, this.options = options;
173
+ const context = this.options.context;
174
+ if (context) this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
175
+ else this.primitives = {
176
+ Object,
177
+ Error,
178
+ Function,
179
+ RegExp,
180
+ Symbol: globalThis.Symbol,
181
+ Array,
182
+ Map
183
+ };
184
+ if (options.spyModule) this.spyModule = options.spyModule;
185
+ const Symbol = this.primitives.Symbol;
186
+ this.filterPublicKeys = [
187
+ "__esModule",
188
+ Symbol.asyncIterator,
189
+ Symbol.hasInstance,
190
+ Symbol.isConcatSpreadable,
191
+ Symbol.iterator,
192
+ Symbol.match,
193
+ Symbol.matchAll,
194
+ Symbol.replace,
195
+ Symbol.search,
196
+ Symbol.split,
197
+ Symbol.species,
198
+ Symbol.toPrimitive,
199
+ Symbol.toStringTag,
200
+ Symbol.unscopables
201
+ ];
202
+ }
203
+ get root() {
204
+ return this.options.root;
205
+ }
206
+ get evaluatedModules() {
207
+ return this.moduleRunner.evaluatedModules;
208
+ }
209
+ get moduleDirectories() {
210
+ return this.options.moduleDirectories || [];
211
+ }
212
+ async initializeSpyModule() {
213
+ this.spyModule ||= await this.moduleRunner.import(spyModulePath);
214
+ }
215
+ getMockerRegistry() {
216
+ const suite = this.getSuiteFilepath();
217
+ if (!this.registries.has(suite)) this.registries.set(suite, new MockerRegistry());
218
+ return this.registries.get(suite);
219
+ }
220
+ reset() {
221
+ this.registries.clear();
222
+ }
223
+ invalidateModuleById(id) {
224
+ const mockId = this.getMockPath(id), node = this.evaluatedModules.getModuleById(mockId);
225
+ if (node) this.evaluatedModules.invalidateModule(node), node.mockedExports = void 0;
226
+ }
227
+ isModuleDirectory(path) {
228
+ return this.moduleDirectories.some((dir) => path.includes(dir));
229
+ }
230
+ getSuiteFilepath() {
231
+ return this.options.getCurrentTestFilepath() || "global";
232
+ }
233
+ createError(message, codeFrame) {
234
+ const Error = this.primitives.Error, error = new Error(message);
235
+ return Object.assign(error, { codeFrame }), error;
236
+ }
237
+ async resolveId(rawId, importer) {
238
+ const result = await this.options.resolveId(rawId, importer);
239
+ if (!result) {
240
+ const id = normalizeModuleId(rawId);
241
+ return {
242
+ id,
243
+ url: rawId,
244
+ external: id
245
+ };
246
+ }
247
+ // external is node_module or unresolved module
248
+ // for example, some people mock "vscode" and don't have it installed
249
+ const external = !isAbsolute$1(result.file) || this.isModuleDirectory(result.file) ? normalizeModuleId(rawId) : null;
250
+ return {
251
+ ...result,
252
+ id: normalizeModuleId(result.id),
253
+ external
254
+ };
255
+ }
256
+ async resolveMocks() {
257
+ VitestMocker.pendingIds.length && (await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
258
+ const { id, url, external } = await this.resolveId(mock.id, mock.importer);
259
+ if (mock.action === "unmock") this.unmockPath(id);
260
+ if (mock.action === "mock") this.mockPath(mock.id, id, url, external, mock.type, mock.factory);
261
+ })), VitestMocker.pendingIds = []);
262
+ }
263
+ ensureModule(id, url) {
264
+ const node = this.evaluatedModules.ensureModule(id, url);
265
+ return node.meta = {
266
+ id,
267
+ url,
268
+ code: "",
269
+ file: null,
270
+ invalidate: false
271
+ }, node;
272
+ }
273
+ async callFunctionMock(id, url, mock) {
274
+ const node = this.ensureModule(id, url);
275
+ if (node.exports) return node.exports;
276
+ const exports = await mock.resolve(), moduleExports = new Proxy(exports, { get: (target, prop) => {
277
+ const val = target[prop];
278
+ // 'then' can exist on non-Promise objects, need nested instanceof check for logic to work
279
+ if (prop === "then") {
280
+ if (target instanceof Promise) return target.then.bind(target);
281
+ } else if (!(prop in target)) {
282
+ if (this.filterPublicKeys.includes(prop)) return void 0;
283
+ throw this.createError(`[vitest] No "${String(prop)}" export is defined on the "${mock.raw}" mock. Did you forget to return it from "vi.mock"?
284
+ If you need to partially mock a module, you can use "importOriginal" helper inside:
285
+ `, highlight(`vi.mock(import("${mock.raw}"), async (importOriginal) => {
286
+ const actual = await importOriginal()
287
+ return {
288
+ ...actual,
289
+ // your mocked methods
290
+ }
291
+ })`));
292
+ }
293
+ return val;
294
+ } });
295
+ return node.exports = moduleExports, moduleExports;
296
+ }
297
+ // public method to avoid circular dependency
298
+ getMockContext() {
299
+ return this.mockContext;
300
+ }
301
+ // path used to store mocked dependencies
302
+ getMockPath(dep) {
303
+ return `mock:${dep}`;
304
+ }
305
+ getDependencyMock(id) {
306
+ const registry = this.getMockerRegistry();
307
+ return registry.getById(fixLeadingSlashes(id));
308
+ }
309
+ findMockRedirect(mockPath, external) {
310
+ return findMockRedirect(this.root, mockPath, external);
311
+ }
312
+ mockObject(object, mockExports = {}, behavior = "automock") {
313
+ const createMockInstance = this.spyModule?.createMockInstance;
314
+ if (!createMockInstance) throw this.createError("[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
315
+ return mockObject({
316
+ globalConstructors: this.primitives,
317
+ createMockInstance,
318
+ type: behavior
319
+ }, object, mockExports);
320
+ }
321
+ unmockPath(id) {
322
+ const registry = this.getMockerRegistry();
323
+ registry.deleteById(id), this.invalidateModuleById(id);
324
+ }
325
+ mockPath(originalId, id, url, external, mockType, factory) {
326
+ const registry = this.getMockerRegistry();
327
+ if (mockType === "manual") registry.register("manual", originalId, id, url, factory);
328
+ else if (mockType === "autospy") registry.register("autospy", originalId, id, url);
329
+ else {
330
+ const redirect = this.findMockRedirect(id, external);
331
+ if (redirect) registry.register("redirect", originalId, id, url, redirect);
332
+ else registry.register("automock", originalId, id, url);
333
+ }
334
+ // every time the mock is registered, we remove the previous one from the cache
335
+ this.invalidateModuleById(id);
336
+ }
337
+ async importActual(rawId, importer, callstack) {
338
+ const { url } = await this.resolveId(rawId, importer), node = await this.moduleRunner.fetchModule(url, importer), result = await this.moduleRunner.cachedRequest(node.url, node, callstack || [importer], void 0, true);
339
+ return result;
340
+ }
341
+ async importMock(rawId, importer) {
342
+ const { id, url, external } = await this.resolveId(rawId, importer);
343
+ let mock = this.getDependencyMock(id);
344
+ if (!mock) {
345
+ const redirect = this.findMockRedirect(id, external);
346
+ if (redirect) mock = new RedirectedModule(rawId, id, rawId, redirect);
347
+ else mock = new AutomockedModule(rawId, id, rawId);
348
+ }
349
+ if (mock.type === "automock" || mock.type === "autospy") {
350
+ const node = await this.moduleRunner.fetchModule(url, importer), mod = await this.moduleRunner.cachedRequest(url, node, [importer], void 0, true), Object = this.primitives.Object;
351
+ return this.mockObject(mod, Object.create(Object.prototype), mock.type);
352
+ }
353
+ if (mock.type === "manual") return this.callFunctionMock(id, url, mock);
354
+ const node = await this.moduleRunner.fetchModule(mock.redirect);
355
+ return this.moduleRunner.cachedRequest(mock.redirect, node, [importer], void 0, true);
356
+ }
357
+ async requestWithMockedModule(url, evaluatedNode, callstack, mock) {
358
+ const mockId = this.getMockPath(evaluatedNode.id);
359
+ if (mock.type === "automock" || mock.type === "autospy") {
360
+ const cache = this.evaluatedModules.getModuleById(mockId);
361
+ if (cache && cache.mockedExports) return cache.mockedExports;
362
+ const Object = this.primitives.Object, exports = Object.create(null);
363
+ Object.defineProperty(exports, Symbol.toStringTag, {
364
+ value: "Module",
365
+ configurable: true,
366
+ writable: true
367
+ });
368
+ const node = this.ensureModule(mockId, this.getMockPath(evaluatedNode.url));
369
+ node.meta = evaluatedNode.meta, node.file = evaluatedNode.file, node.mockedExports = exports;
370
+ const mod = await this.moduleRunner.cachedRequest(url, node, callstack, void 0, true);
371
+ return this.mockObject(mod, exports, mock.type), exports;
372
+ }
373
+ if (mock.type === "manual" && !callstack.includes(mockId) && !callstack.includes(url)) try {
374
+ return callstack.push(mockId), this.mockContext.callstack = callstack, await this.callFunctionMock(mockId, this.getMockPath(url), mock);
375
+ } finally {
376
+ this.mockContext.callstack = null;
377
+ const indexMock = callstack.indexOf(mockId);
378
+ callstack.splice(indexMock, 1);
379
+ }
380
+ else if (mock.type === "redirect" && !callstack.includes(mock.redirect)) return mock.redirect;
381
+ }
382
+ async mockedRequest(url, evaluatedNode, callstack) {
383
+ const mock = this.getDependencyMock(evaluatedNode.id);
384
+ if (mock) return this.requestWithMockedModule(url, evaluatedNode, callstack, mock);
385
+ }
386
+ queueMock(id, importer, factoryOrOptions) {
387
+ const mockType = getMockType(factoryOrOptions);
388
+ VitestMocker.pendingIds.push({
389
+ action: "mock",
390
+ id,
391
+ importer,
392
+ factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
393
+ type: mockType
394
+ });
395
+ }
396
+ queueUnmock(id, importer) {
397
+ VitestMocker.pendingIds.push({
398
+ action: "unmock",
399
+ id,
400
+ importer
401
+ });
402
+ }
403
+ }
404
+ function getMockType(factoryOrOptions) {
405
+ return factoryOrOptions ? typeof factoryOrOptions === "function" ? "manual" : factoryOrOptions.spy ? "autospy" : "automock" : "automock";
406
+ }
407
+ // unique id that is not available as "$bare_import" like "test"
408
+ // https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
409
+ const prefixedBuiltins = new Set([
410
+ "node:sea",
411
+ "node:sqlite",
412
+ "node:test",
413
+ "node:test/reporters"
414
+ ]), isWindows$1 = process.platform === "win32";
415
+ // transform file url to id
416
+ // virtual:custom -> virtual:custom
417
+ // \0custom -> \0custom
418
+ // /root/id -> /id
419
+ // /root/id.js -> /id.js
420
+ // C:/root/id.js -> /id.js
421
+ // C:\root\id.js -> /id.js
422
+ // TODO: expose this in vite/module-runner
423
+ function normalizeModuleId(file) {
424
+ if (prefixedBuiltins.has(file)) return file;
425
+ // unix style, but Windows path still starts with the drive letter to check the root
426
+ const unixFile = slash(file).replace(/^\/@fs\//, isWindows$1 ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
427
+ // if it's not in the root, keep it as a path, not a URL
428
+ return unixFile.replace(/^file:\//, "/");
429
+ }
430
+ const windowsSlashRE = /\\/g;
431
+ function slash(p) {
432
+ return p.replace(windowsSlashRE, "/");
433
+ }
434
+ const multipleSlashRe = /^\/+/;
435
+ // module-runner incorrectly replaces file:///path with `///path`
436
+ function fixLeadingSlashes(id) {
437
+ return id.startsWith("//") ? id.replace(multipleSlashRe, "/") : id;
438
+ }
439
+
440
+ // eslint-disable-next-line ts/ban-ts-comment
441
+ // @ts-ignore
442
+ const createNodeImportMeta = viteModuleRunner.createNodeImportMeta;
443
+ // @ts-expect-error overriding private method
444
+ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
445
+ mocker;
446
+ moduleExecutionInfo;
447
+ constructor(vitestOptions) {
448
+ const options = vitestOptions, transport = new VitestTransport(options.transport), evaluatedModules = options.evaluatedModules;
449
+ if (super({
450
+ transport,
451
+ hmr: false,
452
+ evaluatedModules,
453
+ sourcemapInterceptor: "prepareStackTrace",
454
+ createImportMeta: vitestOptions.createImportMeta
455
+ }, options.evaluator), this.vitestOptions = vitestOptions, this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo, this.mocker = options.mocker || new VitestMocker(this, {
456
+ spyModule: options.spyModule,
457
+ context: options.vm?.context,
458
+ resolveId: options.transport.resolveId,
459
+ get root() {
460
+ return options.getWorkerState().config.root;
461
+ },
462
+ get moduleDirectories() {
463
+ return options.getWorkerState().config.deps.moduleDirectories || [];
464
+ },
465
+ getCurrentTestFilepath() {
466
+ return options.getWorkerState().filepath;
467
+ }
468
+ }), options.vm) options.vm.context.__vitest_mocker__ = this.mocker;
469
+ else Object.defineProperty(globalThis, "__vitest_mocker__", {
470
+ configurable: true,
471
+ writable: true,
472
+ value: this.mocker
473
+ });
474
+ }
475
+ async import(rawId) {
476
+ const resolved = await this.vitestOptions.transport.resolveId(rawId);
477
+ return resolved ? super.import(resolved.url) : super.import(rawId);
478
+ }
479
+ async fetchModule(url, importer) {
480
+ const module = await this.cachedModule(url, importer);
481
+ return module;
482
+ }
483
+ _cachedRequest(url, module, callstack = [], metadata) {
484
+ // @ts-expect-error "cachedRequest" is private
485
+ return super.cachedRequest(url, module, callstack, metadata);
486
+ }
487
+ /**
488
+ * @internal
489
+ */
490
+ async cachedRequest(url, mod, callstack = [], metadata, ignoreMock = false) {
491
+ if (ignoreMock) return this._cachedRequest(url, mod, callstack, metadata);
492
+ let mocked;
493
+ if (mod.meta && "mockedModule" in mod.meta) mocked = await this.mocker.requestWithMockedModule(url, mod, callstack, mod.meta.mockedModule);
494
+ else mocked = await this.mocker.mockedRequest(url, mod, callstack);
495
+ if (typeof mocked === "string") {
496
+ const node = await this.fetchModule(mocked);
497
+ return this._cachedRequest(mocked, node, callstack, metadata);
498
+ }
499
+ return mocked != null && typeof mocked === "object" ? mocked : this._cachedRequest(url, mod, callstack, metadata);
500
+ }
501
+ /** @internal */
502
+ _invalidateSubTreeById(ids, invalidated = /* @__PURE__ */ new Set()) {
503
+ for (const id of ids) {
504
+ if (invalidated.has(id)) continue;
505
+ const node = this.evaluatedModules.getModuleById(id);
506
+ if (!node) continue;
507
+ invalidated.add(id);
508
+ const subIds = Array.from(this.evaluatedModules.idToModuleMap).filter(([, mod]) => mod.importers.has(id)).map(([key]) => key);
509
+ if (subIds.length) this._invalidateSubTreeById(subIds, invalidated);
510
+ this.evaluatedModules.invalidateModule(node);
511
+ }
512
+ }
513
+ }
514
+
515
+ const bareVitestRegexp = /^@?vitest(?:\/|$)/, normalizedDistDir = normalize$1(distDir), relativeIds = {}, externalizeMap = /* @__PURE__ */ new Map();
516
+ // all Vitest imports always need to be externalized
517
+ function getCachedVitestImport(id, state) {
518
+ if (id.startsWith("/@fs/") || id.startsWith("\\@fs\\")) id = id.slice(process.platform === "win32" ? 5 : 4);
519
+ if (externalizeMap.has(id)) return {
520
+ externalize: externalizeMap.get(id),
521
+ type: "module"
522
+ };
523
+ // always externalize Vitest because we import from there before running tests
524
+ // so we already have it cached by Node.js
525
+ const root = state().config.root, relativeRoot = relativeIds[root] ?? (relativeIds[root] = normalizedDistDir.slice(root.length));
526
+ if (id.includes(distDir) || id.includes(normalizedDistDir)) {
527
+ const externalize = id.startsWith("file://") ? id : pathToFileURL(id).toString();
528
+ return externalizeMap.set(id, externalize), {
529
+ externalize,
530
+ type: "module"
531
+ };
532
+ }
533
+ if (relativeRoot && relativeRoot !== "/" && id.startsWith(relativeRoot)) {
534
+ const path = join$1(root, id), externalize = pathToFileURL(path).toString();
535
+ return externalizeMap.set(id, externalize), {
536
+ externalize,
537
+ type: "module"
538
+ };
539
+ }
540
+ return bareVitestRegexp.test(id) ? (externalizeMap.set(id, id), {
541
+ externalize: id,
542
+ type: "module"
543
+ }) : null;
544
+ }
545
+
546
+ const dispose = [];
547
+ function listenForErrors(state) {
548
+ dispose.forEach((fn) => fn()), dispose.length = 0;
549
+ function catchError(err, type, event) {
550
+ const worker = state(), listeners = process.listeners(event);
551
+ // if there is another listener, assume that it's handled by user code
552
+ // one is Vitest's own listener
553
+ if (listeners.length > 1) return;
554
+ const error = processError(err);
555
+ if (typeof error === "object" && error != null) {
556
+ if (error.VITEST_TEST_NAME = worker.current?.type === "test" ? worker.current.name : void 0, worker.filepath) error.VITEST_TEST_PATH = worker.filepath;
557
+ error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
558
+ }
559
+ state().rpc.onUnhandledError(error, type);
560
+ }
561
+ const uncaughtException = (e) => catchError(e, "Uncaught Exception", "uncaughtException"), unhandledRejection = (e) => catchError(e, "Unhandled Rejection", "unhandledRejection");
562
+ process.on("uncaughtException", uncaughtException), process.on("unhandledRejection", unhandledRejection), dispose.push(() => {
563
+ process.off("uncaughtException", uncaughtException), process.off("unhandledRejection", unhandledRejection);
564
+ });
565
+ }
566
+
567
+ const { readFileSync } = fs, browserExternalId = "__vite-browser-external", browserExternalLength = 24;
568
+ const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
569
+ const cwd = process.cwd(), isWindows = process.platform === "win32";
570
+ function startVitestModuleRunner(options) {
571
+ const state = () => globalThis.__vitest_worker__ || options.state, rpc = () => state().rpc;
572
+ process.exit = (code = process.exitCode || 0) => {
573
+ throw new Error(`process.exit unexpectedly called with "${code}"`);
574
+ }, listenForErrors(state);
575
+ const environment = () => {
576
+ const environment = state().environment;
577
+ return environment.viteEnvironment || environment.name;
578
+ }, vm = options.context && options.externalModulesExecutor ? {
579
+ context: options.context,
580
+ externalModulesExecutor: options.externalModulesExecutor
581
+ } : void 0, evaluator = options.evaluator || new VitestModuleEvaluator(vm, {
582
+ get moduleExecutionInfo() {
583
+ return state().moduleExecutionInfo;
584
+ },
585
+ get interopDefault() {
586
+ return state().config.deps.interopDefault;
587
+ },
588
+ getCurrentTestFilepath: () => state().filepath
589
+ }), moduleRunner = new VitestModuleRunner({
590
+ spyModule: options.spyModule,
591
+ evaluatedModules: options.evaluatedModules,
592
+ evaluator,
593
+ mocker: options.mocker,
594
+ transport: {
595
+ async fetchModule(id, importer, options) {
596
+ const resolvingModules = state().resolvingModules;
597
+ if (isWindows) {
598
+ if (id[1] === ":") {
599
+ // The drive letter is different for whatever reason, we need to normalize it to CWD
600
+ if (id[0] !== cwd[0] && id[0].toUpperCase() === cwd[0].toUpperCase()) {
601
+ const isUpperCase = cwd[0].toUpperCase() === cwd[0];
602
+ id = (isUpperCase ? id[0].toUpperCase() : id[0].toLowerCase()) + id.slice(1);
603
+ }
604
+ // always mark absolute windows paths, otherwise Vite will externalize it
605
+ id = `/@id/${id}`;
606
+ }
607
+ }
608
+ const vitest = getCachedVitestImport(id, state);
609
+ if (vitest) return vitest;
610
+ const rawId = unwrapId(id);
611
+ resolvingModules.add(rawId);
612
+ try {
613
+ if (VitestMocker.pendingIds.length) await moduleRunner.mocker.resolveMocks();
614
+ const resolvedMock = moduleRunner.mocker.getDependencyMock(rawId);
615
+ if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {
616
+ code: "",
617
+ file: null,
618
+ id,
619
+ url: id,
620
+ invalidate: false,
621
+ mockedModule: resolvedMock
622
+ };
623
+ if (isBuiltin(rawId) || rawId.startsWith(browserExternalId)) return {
624
+ externalize: toBuiltin(rawId),
625
+ type: "builtin"
626
+ };
627
+ const result = await rpc().fetch(id, importer, environment(), options);
628
+ if ("cached" in result) {
629
+ const code = readFileSync(result.tmp, "utf-8");
630
+ return {
631
+ code,
632
+ ...result
633
+ };
634
+ }
635
+ return result;
636
+ } catch (cause) {
637
+ // rethrow vite error if it cannot load the module because it's not resolved
638
+ if (typeof cause === "object" && cause != null && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url") || typeof cause?.message === "string" && cause.message.startsWith("Cannot find module '")) {
639
+ const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from '${importer}'` : ""}`, { cause });
640
+ throw error.code = "ERR_MODULE_NOT_FOUND", error;
641
+ }
642
+ throw cause;
643
+ } finally {
644
+ resolvingModules.delete(rawId);
645
+ }
646
+ },
647
+ resolveId(id, importer) {
648
+ return rpc().resolve(id, importer, environment());
649
+ }
650
+ },
651
+ getWorkerState: state,
652
+ vm,
653
+ createImportMeta: options.createImportMeta
654
+ });
655
+ // await moduleRunner.import('/@vite/env')
656
+ // await moduleRunner.mocker.initializeSpyModule()
657
+ return moduleRunner;
658
+ }
659
+ function toBuiltin(id) {
660
+ if (id.startsWith(browserExternalId)) id = id.slice(browserExternalLength);
661
+ if (!id.startsWith("node:")) id = `node:${id}`;
662
+ return id;
663
+ }
664
+
665
+ export { VitestModuleRunner as V, VITEST_VM_CONTEXT_SYMBOL as a, createNodeImportMeta as c, startVitestModuleRunner as s };
@@ -1,5 +1,5 @@
1
1
  import { Test } from '@vitest/runner';
2
- import { c as BenchmarkAPI, a as BenchFunction } from './benchmark.d.BwvBVTda.js';
2
+ import { c as BenchmarkAPI, a as BenchFunction } from './benchmark.d.DAaHLpsq.js';
3
3
  import { Options } from 'tinybench';
4
4
  import '@vitest/runner/utils';
5
5