vitest 1.1.2 → 1.2.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 (62) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.js +5 -31
  3. package/dist/chunks/{api-setup.mFKdEKxa.js → api-setup.MAoRkVWJ.js} +60 -6
  4. package/dist/chunks/{integrations-globals.tnKXwyh5.js → integrations-globals.VbxbZ7hn.js} +9 -8
  5. package/dist/{entry.js → chunks/runtime-runBaseTests.LWFmrzDk.js} +20 -18
  6. package/dist/cli-wrapper.js +1 -1
  7. package/dist/cli.js +14 -14
  8. package/dist/config.cjs +12 -1
  9. package/dist/config.d.ts +5 -2
  10. package/dist/config.js +12 -2
  11. package/dist/coverage.d.ts +1 -1
  12. package/dist/environments.d.ts +1 -1
  13. package/dist/environments.js +1 -1
  14. package/dist/execute.d.ts +8 -6
  15. package/dist/execute.js +4 -7
  16. package/dist/index.d.ts +4 -3
  17. package/dist/index.js +8 -7
  18. package/dist/node.d.ts +3 -3
  19. package/dist/node.js +12 -12
  20. package/dist/{reporters-xH8_lESK.d.ts → reporters-trlZlObr.d.ts} +113 -27
  21. package/dist/reporters.d.ts +1 -1
  22. package/dist/reporters.js +4 -4
  23. package/dist/runners.d.ts +1 -1
  24. package/dist/runners.js +7 -5
  25. package/dist/{suite-GoqTeX8s.d.ts → suite-6Pt_ep5V.d.ts} +1 -1
  26. package/dist/suite.d.ts +2 -2
  27. package/dist/suite.js +3 -3
  28. package/dist/vendor/base.8wUUWReP.js +38 -0
  29. package/dist/vendor/{base._79unx2z.js → base.dzu0Y6Hj.js} +10 -1
  30. package/dist/vendor/{benchmark.WVm6DARl.js → benchmark.IlKmJkUU.js} +1 -1
  31. package/dist/vendor/{constants.WSvnD_fn.js → constants.i1PoEnhr.js} +9 -1
  32. package/dist/vendor/{coverage.v6aD8iAh.js → coverage.E7sG1b3r.js} +1 -1
  33. package/dist/vendor/{environments.QJtma9XQ.js → environments.sU0TD7wX.js} +19 -7
  34. package/dist/vendor/execute.3_hyGknJ.js +589 -0
  35. package/dist/vendor/{global.L7JRz1qU.js → global.CkGT_TMy.js} +10 -1
  36. package/dist/vendor/{index.IhksUGLR.js → index.3iX2R_Z5.js} +6 -6
  37. package/dist/vendor/{index.h0j9y5vy.js → index.D-jOsMas.js} +5 -5
  38. package/dist/vendor/{index.XU72Rmy8.js → index.rJjbcrrp.js} +1 -1
  39. package/dist/vendor/{node.UBNKMR9Y.js → node.xyYo9ZvH.js} +660 -288
  40. package/dist/vendor/{reporters.oUR9etwS.js → reporters.2PaQ2peU.js} +11 -8
  41. package/dist/vendor/{rpc.Bl-ysZIr.js → rpc.w4v8oCkK.js} +23 -2
  42. package/dist/vendor/{run-once.X3E7xx3F.js → run-once.Olz_Zkd8.js} +2 -2
  43. package/dist/vendor/setup-common.j9IXYrbN.js +29 -0
  44. package/dist/vendor/utils.GbToHGHI.js +41 -0
  45. package/dist/vendor/{vi.DTC--YO5.js → vi.smj1Ggd4.js} +9 -5
  46. package/dist/vendor/vm.vFKXXdo0.js +696 -0
  47. package/dist/worker.js +109 -82
  48. package/dist/workers/forks.js +33 -0
  49. package/dist/{entry-vm.js → workers/runVmTests.js} +20 -16
  50. package/dist/workers/threads.js +26 -0
  51. package/dist/workers/vmForks.js +43 -0
  52. package/dist/workers/vmThreads.js +36 -0
  53. package/dist/workers.d.ts +36 -0
  54. package/dist/workers.js +30 -0
  55. package/package.json +11 -7
  56. package/workers.d.ts +1 -0
  57. package/dist/child.js +0 -125
  58. package/dist/vendor/execute.cedv4NLQ.js +0 -1235
  59. package/dist/vendor/inspector.lFAeuaAt.js +0 -26
  60. package/dist/vendor/loader.L9CYwKn1.js +0 -39
  61. package/dist/vm.js +0 -126
  62. /package/dist/{paths.js → path.js} +0 -0
@@ -28,8 +28,8 @@ var node = {
28
28
  // this is largely copied from jest's node environment
29
29
  async setupVM() {
30
30
  const vm = await import('node:vm');
31
- const context = vm.createContext();
32
- const global = vm.runInContext(
31
+ let context = vm.createContext();
32
+ let global = vm.runInContext(
33
33
  "this",
34
34
  context
35
35
  );
@@ -85,6 +85,8 @@ var node = {
85
85
  return context;
86
86
  },
87
87
  teardown() {
88
+ context = void 0;
89
+ global = void 0;
88
90
  }
89
91
  };
90
92
  },
@@ -453,7 +455,7 @@ var jsdom = {
453
455
  cookieJar = false,
454
456
  ...restOptions
455
457
  } = jsdom;
456
- const dom = new JSDOM(
458
+ let dom = new JSDOM(
457
459
  html,
458
460
  {
459
461
  pretendToBeVisual,
@@ -493,6 +495,7 @@ var jsdom = {
493
495
  teardown() {
494
496
  clearWindowErrors();
495
497
  dom.window.close();
498
+ dom = void 0;
496
499
  }
497
500
  };
498
501
  },
@@ -544,12 +547,20 @@ var jsdom = {
544
547
  }
545
548
  };
546
549
 
550
+ async function teardownWindow(win) {
551
+ if (win.close && win.happyDOM.abort) {
552
+ await win.happyDOM.abort();
553
+ win.close();
554
+ } else {
555
+ win.happyDOM.cancelAsync();
556
+ }
557
+ }
547
558
  var happy = {
548
559
  name: "happy-dom",
549
560
  transformMode: "web",
550
561
  async setupVM({ happyDOM = {} }) {
551
562
  const { Window } = await import('happy-dom');
552
- const win = new Window({
563
+ let win = new Window({
553
564
  ...happyDOM,
554
565
  console: console && globalThis.console ? globalThis.console : void 0,
555
566
  url: happyDOM.url || "http://localhost:3000",
@@ -566,7 +577,8 @@ var happy = {
566
577
  return win;
567
578
  },
568
579
  async teardown() {
569
- await win.happyDOM.cancelAsync();
580
+ await teardownWindow(win);
581
+ win = void 0;
570
582
  }
571
583
  };
572
584
  },
@@ -587,8 +599,8 @@ var happy = {
587
599
  additionalKeys: ["Request", "Response"]
588
600
  });
589
601
  return {
590
- teardown(global2) {
591
- win.happyDOM.cancelAsync();
602
+ async teardown(global2) {
603
+ await teardownWindow(win);
592
604
  keys.forEach((key) => delete global2[key]);
593
605
  originals.forEach((v, k) => global2[k] = v);
594
606
  }
@@ -0,0 +1,589 @@
1
+ import vm from 'node:vm';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
4
+ import { isNodeBuiltin, isInternalRequest, toFilePath, isPrimitive } from 'vite-node/utils';
5
+ import { resolve, isAbsolute, dirname, join, basename, extname, relative, normalize } from 'pathe';
6
+ import { processError } from '@vitest/utils/error';
7
+ import { distDir } from '../path.js';
8
+ import { existsSync, readdirSync } from 'node:fs';
9
+ import { highlight, getType } from '@vitest/utils';
10
+ import { e as getAllMockableProperties } from './base.dzu0Y6Hj.js';
11
+
12
+ const spyModulePath = resolve(distDir, "spy.js");
13
+ class RefTracker {
14
+ idMap = /* @__PURE__ */ new Map();
15
+ mockedValueMap = /* @__PURE__ */ new Map();
16
+ getId(value) {
17
+ return this.idMap.get(value);
18
+ }
19
+ getMockedValue(id) {
20
+ return this.mockedValueMap.get(id);
21
+ }
22
+ track(originalValue, mockedValue) {
23
+ const newId = this.idMap.size;
24
+ this.idMap.set(originalValue, newId);
25
+ this.mockedValueMap.set(newId, mockedValue);
26
+ return newId;
27
+ }
28
+ }
29
+ function isSpecialProp(prop, parentType) {
30
+ return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
31
+ }
32
+ class VitestMocker {
33
+ constructor(executor) {
34
+ this.executor = executor;
35
+ const context = this.executor.options.context;
36
+ if (context)
37
+ this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
38
+ else
39
+ this.primitives = { Object, Error, Function, RegExp, Symbol: globalThis.Symbol, Array, Map };
40
+ const Symbol2 = this.primitives.Symbol;
41
+ this.filterPublicKeys = ["__esModule", Symbol2.asyncIterator, Symbol2.hasInstance, Symbol2.isConcatSpreadable, Symbol2.iterator, Symbol2.match, Symbol2.matchAll, Symbol2.replace, Symbol2.search, Symbol2.split, Symbol2.species, Symbol2.toPrimitive, Symbol2.toStringTag, Symbol2.unscopables];
42
+ }
43
+ static pendingIds = [];
44
+ spyModule;
45
+ resolveCache = /* @__PURE__ */ new Map();
46
+ primitives;
47
+ filterPublicKeys;
48
+ mockContext = {
49
+ callstack: null
50
+ };
51
+ get root() {
52
+ return this.executor.options.root;
53
+ }
54
+ get mockMap() {
55
+ return this.executor.options.mockMap;
56
+ }
57
+ get moduleCache() {
58
+ return this.executor.moduleCache;
59
+ }
60
+ get moduleDirectories() {
61
+ return this.executor.options.moduleDirectories || [];
62
+ }
63
+ async initializeSpyModule() {
64
+ this.spyModule = await this.executor.executeId(spyModulePath);
65
+ }
66
+ deleteCachedItem(id) {
67
+ const mockId = this.getMockPath(id);
68
+ if (this.moduleCache.has(mockId))
69
+ this.moduleCache.delete(mockId);
70
+ }
71
+ isAModuleDirectory(path) {
72
+ return this.moduleDirectories.some((dir) => path.includes(dir));
73
+ }
74
+ getSuiteFilepath() {
75
+ return this.executor.state.filepath || "global";
76
+ }
77
+ createError(message, codeFrame) {
78
+ const Error2 = this.primitives.Error;
79
+ const error = new Error2(message);
80
+ Object.assign(error, { codeFrame });
81
+ return error;
82
+ }
83
+ getMocks() {
84
+ const suite = this.getSuiteFilepath();
85
+ const suiteMocks = this.mockMap.get(suite);
86
+ const globalMocks = this.mockMap.get("global");
87
+ return {
88
+ ...globalMocks,
89
+ ...suiteMocks
90
+ };
91
+ }
92
+ async resolvePath(rawId, importer) {
93
+ let id;
94
+ let fsPath;
95
+ try {
96
+ [id, fsPath] = await this.executor.originalResolveUrl(rawId, importer);
97
+ } catch (error) {
98
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
99
+ const { id: unresolvedId } = error[Symbol.for("vitest.error.not_found.data")];
100
+ id = unresolvedId;
101
+ fsPath = unresolvedId;
102
+ } else {
103
+ throw error;
104
+ }
105
+ }
106
+ const external = !isAbsolute(fsPath) || this.isAModuleDirectory(fsPath) ? rawId : null;
107
+ return {
108
+ id,
109
+ fsPath,
110
+ external
111
+ };
112
+ }
113
+ async resolveMocks() {
114
+ if (!VitestMocker.pendingIds.length)
115
+ return;
116
+ await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
117
+ const { fsPath, external } = await this.resolvePath(mock.id, mock.importer);
118
+ if (mock.type === "unmock")
119
+ this.unmockPath(fsPath);
120
+ if (mock.type === "mock")
121
+ this.mockPath(mock.id, fsPath, external, mock.factory, mock.throwIfCached);
122
+ }));
123
+ VitestMocker.pendingIds = [];
124
+ }
125
+ async callFunctionMock(dep, mock) {
126
+ var _a, _b;
127
+ const cached = (_a = this.moduleCache.get(dep)) == null ? void 0 : _a.exports;
128
+ if (cached)
129
+ return cached;
130
+ let exports;
131
+ try {
132
+ exports = await mock();
133
+ } catch (err) {
134
+ const vitestError = this.createError(
135
+ '[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock'
136
+ );
137
+ vitestError.cause = err;
138
+ throw vitestError;
139
+ }
140
+ const filepath = dep.slice(5);
141
+ const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
142
+ if (exports === null || typeof exports !== "object")
143
+ throw this.createError(`[vitest] vi.mock("${mockpath}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
144
+ const moduleExports = new Proxy(exports, {
145
+ get: (target, prop) => {
146
+ const val = target[prop];
147
+ if (prop === "then") {
148
+ if (target instanceof Promise)
149
+ return target.then.bind(target);
150
+ } else if (!(prop in target)) {
151
+ if (this.filterPublicKeys.includes(prop))
152
+ return void 0;
153
+ throw this.createError(
154
+ `[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"?
155
+ If you need to partially mock a module, you can use "importOriginal" helper inside:
156
+ `,
157
+ highlight(`vi.mock("${mockpath}", async (importOriginal) => {
158
+ const actual = await importOriginal()
159
+ return {
160
+ ...actual,
161
+ // your mocked methods
162
+ }
163
+ })`)
164
+ );
165
+ }
166
+ return val;
167
+ }
168
+ });
169
+ this.moduleCache.set(dep, { exports: moduleExports });
170
+ return moduleExports;
171
+ }
172
+ getMockContext() {
173
+ return this.mockContext;
174
+ }
175
+ getMockPath(dep) {
176
+ return `mock:${dep}`;
177
+ }
178
+ getDependencyMock(id) {
179
+ return this.getMocks()[id];
180
+ }
181
+ normalizePath(path) {
182
+ return this.moduleCache.normalizePath(path);
183
+ }
184
+ resolveMockPath(mockPath, external) {
185
+ const path = external || mockPath;
186
+ if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
187
+ const mockDirname = dirname(path);
188
+ const mockFolder = join(this.root, "__mocks__", mockDirname);
189
+ if (!existsSync(mockFolder))
190
+ return null;
191
+ const files = readdirSync(mockFolder);
192
+ const baseOriginal = basename(path);
193
+ for (const file of files) {
194
+ const baseFile = basename(file, extname(file));
195
+ if (baseFile === baseOriginal)
196
+ return resolve(mockFolder, file);
197
+ }
198
+ return null;
199
+ }
200
+ const dir = dirname(path);
201
+ const baseId = basename(path);
202
+ const fullPath = resolve(dir, "__mocks__", baseId);
203
+ return existsSync(fullPath) ? fullPath : null;
204
+ }
205
+ mockObject(object, mockExports = {}) {
206
+ const finalizers = new Array();
207
+ const refs = new RefTracker();
208
+ const define = (container, key, value) => {
209
+ try {
210
+ container[key] = value;
211
+ return true;
212
+ } catch {
213
+ return false;
214
+ }
215
+ };
216
+ const mockPropertiesOf = (container, newContainer) => {
217
+ const containerType = getType(container);
218
+ const isModule = containerType === "Module" || !!container.__esModule;
219
+ for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, this.primitives)) {
220
+ if (!isModule && descriptor.get) {
221
+ try {
222
+ Object.defineProperty(newContainer, property, descriptor);
223
+ } catch (error) {
224
+ }
225
+ continue;
226
+ }
227
+ if (isSpecialProp(property, containerType))
228
+ continue;
229
+ const value = container[property];
230
+ const refId = refs.getId(value);
231
+ if (refId !== void 0) {
232
+ finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
233
+ continue;
234
+ }
235
+ const type = getType(value);
236
+ if (Array.isArray(value)) {
237
+ define(newContainer, property, []);
238
+ continue;
239
+ }
240
+ const isFunction = type.includes("Function") && typeof value === "function";
241
+ if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") {
242
+ define(newContainer, property, value);
243
+ continue;
244
+ }
245
+ if (!define(newContainer, property, isFunction ? value : {}))
246
+ continue;
247
+ if (isFunction) {
248
+ let mockFunction2 = function() {
249
+ if (this instanceof newContainer[property]) {
250
+ for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false, primitives)) {
251
+ if (descriptor2.get)
252
+ continue;
253
+ const value2 = this[key];
254
+ const type2 = getType(value2);
255
+ const isFunction2 = type2.includes("Function") && typeof value2 === "function";
256
+ if (isFunction2) {
257
+ const original = this[key];
258
+ const mock2 = spyModule.spyOn(this, key).mockImplementation(original);
259
+ mock2.mockRestore = () => {
260
+ mock2.mockReset();
261
+ mock2.mockImplementation(original);
262
+ return mock2;
263
+ };
264
+ }
265
+ }
266
+ }
267
+ };
268
+ if (!this.spyModule)
269
+ throw this.createError("[vitest] `spyModule` is not defined. This is Vitest error. Please open a new issue with reproduction.");
270
+ const spyModule = this.spyModule;
271
+ const primitives = this.primitives;
272
+ const mock = spyModule.spyOn(newContainer, property).mockImplementation(mockFunction2);
273
+ mock.mockRestore = () => {
274
+ mock.mockReset();
275
+ mock.mockImplementation(mockFunction2);
276
+ return mock;
277
+ };
278
+ Object.defineProperty(newContainer[property], "length", { value: 0 });
279
+ }
280
+ refs.track(value, newContainer[property]);
281
+ mockPropertiesOf(value, newContainer[property]);
282
+ }
283
+ };
284
+ const mockedObject = mockExports;
285
+ mockPropertiesOf(object, mockedObject);
286
+ for (const finalizer of finalizers)
287
+ finalizer();
288
+ return mockedObject;
289
+ }
290
+ unmockPath(path) {
291
+ const suitefile = this.getSuiteFilepath();
292
+ const id = this.normalizePath(path);
293
+ const mock = this.mockMap.get(suitefile);
294
+ if (mock && id in mock)
295
+ delete mock[id];
296
+ this.deleteCachedItem(id);
297
+ }
298
+ mockPath(originalId, path, external, factory, throwIfExists) {
299
+ var _a, _b, _c, _d;
300
+ const id = this.normalizePath(path);
301
+ const { config } = this.executor.state;
302
+ const isIsolatedThreads = config.pool === "threads" && (((_b = (_a = config.poolOptions) == null ? void 0 : _a.threads) == null ? void 0 : _b.isolate) ?? true);
303
+ const isIsolatedForks = config.pool === "forks" && (((_d = (_c = config.poolOptions) == null ? void 0 : _c.forks) == null ? void 0 : _d.isolate) ?? true);
304
+ if (throwIfExists && (isIsolatedThreads || isIsolatedForks || config.pool === "vmThreads")) {
305
+ const cached = this.moduleCache.has(id) && this.moduleCache.getByModuleId(id);
306
+ if (cached && cached.importers.size)
307
+ throw new Error(`[vitest] Cannot mock "${originalId}" because it is already loaded by "${[...cached.importers.values()].map((i) => relative(this.root, i)).join('", "')}".
308
+
309
+ Please, remove the import if you want static imports to be mocked, or clear module cache by calling "vi.resetModules()" before mocking if you are going to import the file again. See: https://vitest.dev/guide/common-errors.html#cannot-mock-mocked-file-js-because-it-is-already-loaded`);
310
+ }
311
+ const suitefile = this.getSuiteFilepath();
312
+ const mocks = this.mockMap.get(suitefile) || {};
313
+ const resolves = this.resolveCache.get(suitefile) || {};
314
+ mocks[id] = factory || this.resolveMockPath(path, external);
315
+ resolves[id] = originalId;
316
+ this.mockMap.set(suitefile, mocks);
317
+ this.resolveCache.set(suitefile, resolves);
318
+ this.deleteCachedItem(id);
319
+ }
320
+ async importActual(rawId, importer, callstack) {
321
+ const { id, fsPath } = await this.resolvePath(rawId, importer);
322
+ const result = await this.executor.cachedRequest(id, fsPath, callstack || [importer]);
323
+ return result;
324
+ }
325
+ async importMock(rawId, importee) {
326
+ const { id, fsPath, external } = await this.resolvePath(rawId, importee);
327
+ const normalizedId = this.normalizePath(fsPath);
328
+ let mock = this.getDependencyMock(normalizedId);
329
+ if (mock === void 0)
330
+ mock = this.resolveMockPath(fsPath, external);
331
+ if (mock === null) {
332
+ const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
333
+ return this.mockObject(mod);
334
+ }
335
+ if (typeof mock === "function")
336
+ return this.callFunctionMock(fsPath, mock);
337
+ return this.executor.dependencyRequest(mock, mock, [importee]);
338
+ }
339
+ async requestWithMock(url, callstack) {
340
+ const id = this.normalizePath(url);
341
+ const mock = this.getDependencyMock(id);
342
+ const mockPath = this.getMockPath(id);
343
+ if (mock === null) {
344
+ const cache = this.moduleCache.get(mockPath);
345
+ if (cache.exports)
346
+ return cache.exports;
347
+ const exports = {};
348
+ this.moduleCache.set(mockPath, { exports });
349
+ const mod = await this.executor.directRequest(url, url, callstack);
350
+ this.mockObject(mod, exports);
351
+ return exports;
352
+ }
353
+ if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) {
354
+ try {
355
+ callstack.push(mockPath);
356
+ this.mockContext.callstack = callstack;
357
+ return await this.callFunctionMock(mockPath, mock);
358
+ } finally {
359
+ this.mockContext.callstack = null;
360
+ const indexMock = callstack.indexOf(mockPath);
361
+ callstack.splice(indexMock, 1);
362
+ }
363
+ }
364
+ if (typeof mock === "string" && !callstack.includes(mock))
365
+ return mock;
366
+ }
367
+ queueMock(id, importer, factory, throwIfCached = false) {
368
+ VitestMocker.pendingIds.push({ type: "mock", id, importer, factory, throwIfCached });
369
+ }
370
+ queueUnmock(id, importer, throwIfCached = false) {
371
+ VitestMocker.pendingIds.push({ type: "unmock", id, importer, throwIfCached });
372
+ }
373
+ }
374
+
375
+ async function createVitestExecutor(options) {
376
+ const runner = new VitestExecutor(options);
377
+ await runner.executeId("/@vite/env");
378
+ await runner.mocker.initializeSpyModule();
379
+ return runner;
380
+ }
381
+ const externalizeMap = /* @__PURE__ */ new Map();
382
+ const bareVitestRegexp = /^@?vitest(\/|$)/;
383
+ async function startVitestExecutor(options) {
384
+ const state = () => globalThis.__vitest_worker__ || options.state;
385
+ const rpc = () => state().rpc;
386
+ process.exit = (code = process.exitCode || 0) => {
387
+ throw new Error(`process.exit unexpectedly called with "${code}"`);
388
+ };
389
+ function catchError(err, type) {
390
+ var _a;
391
+ const worker = state();
392
+ const error = processError(err);
393
+ if (!isPrimitive(error)) {
394
+ error.VITEST_TEST_NAME = (_a = worker.current) == null ? void 0 : _a.name;
395
+ if (worker.filepath)
396
+ error.VITEST_TEST_PATH = relative(state().config.root, worker.filepath);
397
+ error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
398
+ }
399
+ rpc().onUnhandledError(error, type);
400
+ }
401
+ process.setMaxListeners(25);
402
+ process.on("uncaughtException", (e) => catchError(e, "Uncaught Exception"));
403
+ process.on("unhandledRejection", (e) => catchError(e, "Unhandled Rejection"));
404
+ const getTransformMode = () => {
405
+ return state().environment.transformMode ?? "ssr";
406
+ };
407
+ return await createVitestExecutor({
408
+ async fetchModule(id) {
409
+ if (externalizeMap.has(id))
410
+ return { externalize: externalizeMap.get(id) };
411
+ if (id.includes(distDir)) {
412
+ const { path } = toFilePath(id, state().config.root);
413
+ const externalize = pathToFileURL(path).toString();
414
+ externalizeMap.set(id, externalize);
415
+ return { externalize };
416
+ }
417
+ if (bareVitestRegexp.test(id)) {
418
+ externalizeMap.set(id, id);
419
+ return { externalize: id };
420
+ }
421
+ return rpc().fetch(id, getTransformMode());
422
+ },
423
+ resolveId(id, importer) {
424
+ return rpc().resolveId(id, importer, getTransformMode());
425
+ },
426
+ get moduleCache() {
427
+ return state().moduleCache;
428
+ },
429
+ get mockMap() {
430
+ return state().mockMap;
431
+ },
432
+ get interopDefault() {
433
+ return state().config.deps.interopDefault;
434
+ },
435
+ get moduleDirectories() {
436
+ return state().config.deps.moduleDirectories;
437
+ },
438
+ get root() {
439
+ return state().config.root;
440
+ },
441
+ get base() {
442
+ return state().config.base;
443
+ },
444
+ ...options
445
+ });
446
+ }
447
+ function updateStyle(id, css) {
448
+ if (typeof document === "undefined")
449
+ return;
450
+ const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
451
+ if (element) {
452
+ element.textContent = css;
453
+ return;
454
+ }
455
+ const head = document.querySelector("head");
456
+ const style = document.createElement("style");
457
+ style.setAttribute("type", "text/css");
458
+ style.setAttribute("data-vite-dev-id", id);
459
+ style.textContent = css;
460
+ head == null ? void 0 : head.appendChild(style);
461
+ }
462
+ function removeStyle(id) {
463
+ if (typeof document === "undefined")
464
+ return;
465
+ const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
466
+ if (sheet)
467
+ document.head.removeChild(sheet);
468
+ }
469
+ function getDefaultRequestStubs(context) {
470
+ if (!context) {
471
+ const clientStub2 = { ...DEFAULT_REQUEST_STUBS["@vite/client"], updateStyle, removeStyle };
472
+ return {
473
+ "/@vite/client": clientStub2,
474
+ "@vite/client": clientStub2
475
+ };
476
+ }
477
+ const clientStub = vm.runInContext(
478
+ `(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
479
+ context
480
+ )(DEFAULT_REQUEST_STUBS["@vite/client"]);
481
+ return {
482
+ "/@vite/client": clientStub,
483
+ "@vite/client": clientStub
484
+ };
485
+ }
486
+ class VitestExecutor extends ViteNodeRunner {
487
+ constructor(options) {
488
+ super({
489
+ ...options,
490
+ // interop is done inside the external executor instead
491
+ interopDefault: options.context ? false : options.interopDefault
492
+ });
493
+ this.options = options;
494
+ this.mocker = new VitestMocker(this);
495
+ if (!options.context) {
496
+ Object.defineProperty(globalThis, "__vitest_mocker__", {
497
+ value: this.mocker,
498
+ writable: true,
499
+ configurable: true
500
+ });
501
+ this.primitives = { Object, Reflect, Symbol };
502
+ } else if (options.externalModulesExecutor) {
503
+ this.primitives = vm.runInContext("({ Object, Reflect, Symbol })", options.context);
504
+ this.externalModules = options.externalModulesExecutor;
505
+ } else {
506
+ throw new Error("When context is provided, externalModulesExecutor must be provided as well.");
507
+ }
508
+ }
509
+ mocker;
510
+ externalModules;
511
+ primitives;
512
+ getContextPrimitives() {
513
+ return this.primitives;
514
+ }
515
+ get state() {
516
+ return globalThis.__vitest_worker__ || this.options.state;
517
+ }
518
+ shouldResolveId(id, _importee) {
519
+ var _a;
520
+ if (isInternalRequest(id) || id.startsWith("data:"))
521
+ return false;
522
+ const transformMode = ((_a = this.state.environment) == null ? void 0 : _a.transformMode) ?? "ssr";
523
+ return transformMode === "ssr" ? !isNodeBuiltin(id) : !id.startsWith("node:");
524
+ }
525
+ async originalResolveUrl(id, importer) {
526
+ return super.resolveUrl(id, importer);
527
+ }
528
+ async resolveUrl(id, importer) {
529
+ if (VitestMocker.pendingIds.length)
530
+ await this.mocker.resolveMocks();
531
+ if (importer && importer.startsWith("mock:"))
532
+ importer = importer.slice(5);
533
+ try {
534
+ return await super.resolveUrl(id, importer);
535
+ } catch (error) {
536
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
537
+ const { id: id2 } = error[Symbol.for("vitest.error.not_found.data")];
538
+ const path = this.mocker.normalizePath(id2);
539
+ const mock = this.mocker.getDependencyMock(path);
540
+ if (mock !== void 0)
541
+ return [id2, id2];
542
+ }
543
+ throw error;
544
+ }
545
+ }
546
+ async runModule(context, transformed) {
547
+ const vmContext = this.options.context;
548
+ if (!vmContext || !this.externalModules)
549
+ return super.runModule(context, transformed);
550
+ const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
551
+ const code = `${codeDefinition}${transformed}
552
+ }}`;
553
+ const options = {
554
+ filename: context.__filename,
555
+ lineOffset: 0,
556
+ columnOffset: -codeDefinition.length
557
+ };
558
+ const fn = vm.runInContext(code, vmContext, {
559
+ ...options,
560
+ // if we encountered an import, it's not inlined
561
+ importModuleDynamically: this.externalModules.importModuleDynamically
562
+ });
563
+ await fn(...Object.values(context));
564
+ }
565
+ async importExternalModule(path) {
566
+ if (this.externalModules)
567
+ return this.externalModules.import(path);
568
+ return super.importExternalModule(path);
569
+ }
570
+ async dependencyRequest(id, fsPath, callstack) {
571
+ const mocked = await this.mocker.requestWithMock(fsPath, callstack);
572
+ if (typeof mocked === "string")
573
+ return super.dependencyRequest(mocked, mocked, callstack);
574
+ if (mocked && typeof mocked === "object")
575
+ return mocked;
576
+ return super.dependencyRequest(id, fsPath, callstack);
577
+ }
578
+ prepareContext(context) {
579
+ if (this.state.filepath && normalize(this.state.filepath) === normalize(context.__filename)) {
580
+ const globalNamespace = this.options.context || globalThis;
581
+ Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalNamespace.__vitest_index__ });
582
+ }
583
+ if (this.options.context && this.externalModules)
584
+ context.require = this.externalModules.createRequire(context.__filename);
585
+ return context;
586
+ }
587
+ }
588
+
589
+ export { VitestExecutor as V, getDefaultRequestStubs as g, startVitestExecutor as s };
@@ -6,9 +6,18 @@ function getWorkerState() {
6
6
  }
7
7
  return workerState;
8
8
  }
9
+ function provideWorkerState(context, state) {
10
+ Object.defineProperty(context, "__vitest_worker__", {
11
+ value: state,
12
+ configurable: true,
13
+ writable: true,
14
+ enumerable: false
15
+ });
16
+ return state;
17
+ }
9
18
  function getCurrentEnvironment() {
10
19
  const state = getWorkerState();
11
20
  return state == null ? void 0 : state.environment.name;
12
21
  }
13
22
 
14
- export { getCurrentEnvironment as a, getWorkerState as g };
23
+ export { getCurrentEnvironment as a, getWorkerState as g, provideWorkerState as p };