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
@@ -1,1235 +0,0 @@
1
- import { pathToFileURL, fileURLToPath } from 'node:url';
2
- import vm from 'node:vm';
3
- import { ModuleCacheMap, ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
4
- import { isNodeBuiltin, isPrimitive, toArray, getCachedData, setCacheData, isInternalRequest, toFilePath } from 'vite-node/utils';
5
- import { resolve, isAbsolute, dirname, join, basename, extname, normalize, relative } from 'pathe';
6
- import { processError } from '@vitest/utils/error';
7
- import { distDir } from '../paths.js';
8
- import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
9
- import { getColors, getType } from '@vitest/utils';
10
- import { b as getAllMockableProperties } from './base._79unx2z.js';
11
- import { dirname as dirname$1 } from 'node:path';
12
- import { createRequire, Module } from 'node:module';
13
- import { CSS_LANGS_RE, KNOWN_ASSET_RE } from 'vite-node/constants';
14
-
15
- const spyModulePath = resolve(distDir, "spy.js");
16
- class RefTracker {
17
- idMap = /* @__PURE__ */ new Map();
18
- mockedValueMap = /* @__PURE__ */ new Map();
19
- getId(value) {
20
- return this.idMap.get(value);
21
- }
22
- getMockedValue(id) {
23
- return this.mockedValueMap.get(id);
24
- }
25
- track(originalValue, mockedValue) {
26
- const newId = this.idMap.size;
27
- this.idMap.set(originalValue, newId);
28
- this.mockedValueMap.set(newId, mockedValue);
29
- return newId;
30
- }
31
- }
32
- function isSpecialProp(prop, parentType) {
33
- return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
34
- }
35
- class VitestMocker {
36
- constructor(executor) {
37
- this.executor = executor;
38
- const context = this.executor.options.context;
39
- if (context)
40
- this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
41
- else
42
- this.primitives = { Object, Error, Function, RegExp, Symbol: globalThis.Symbol, Array, Map };
43
- const Symbol2 = this.primitives.Symbol;
44
- 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];
45
- }
46
- static pendingIds = [];
47
- spyModule;
48
- resolveCache = /* @__PURE__ */ new Map();
49
- primitives;
50
- filterPublicKeys;
51
- mockContext = {
52
- callstack: null
53
- };
54
- get root() {
55
- return this.executor.options.root;
56
- }
57
- get mockMap() {
58
- return this.executor.options.mockMap;
59
- }
60
- get moduleCache() {
61
- return this.executor.moduleCache;
62
- }
63
- get moduleDirectories() {
64
- return this.executor.options.moduleDirectories || [];
65
- }
66
- async initializeSpyModule() {
67
- this.spyModule = await this.executor.executeId(spyModulePath);
68
- }
69
- deleteCachedItem(id) {
70
- const mockId = this.getMockPath(id);
71
- if (this.moduleCache.has(mockId))
72
- this.moduleCache.delete(mockId);
73
- }
74
- isAModuleDirectory(path) {
75
- return this.moduleDirectories.some((dir) => path.includes(dir));
76
- }
77
- getSuiteFilepath() {
78
- return this.executor.state.filepath || "global";
79
- }
80
- createError(message) {
81
- const Error2 = this.primitives.Error;
82
- return new Error2(message);
83
- }
84
- getMocks() {
85
- const suite = this.getSuiteFilepath();
86
- const suiteMocks = this.mockMap.get(suite);
87
- const globalMocks = this.mockMap.get("global");
88
- return {
89
- ...globalMocks,
90
- ...suiteMocks
91
- };
92
- }
93
- async resolvePath(rawId, importer) {
94
- let id;
95
- let fsPath;
96
- try {
97
- [id, fsPath] = await this.executor.originalResolveUrl(rawId, importer);
98
- } catch (error) {
99
- if (error.code === "ERR_MODULE_NOT_FOUND") {
100
- const { id: unresolvedId } = error[Symbol.for("vitest.error.not_found.data")];
101
- id = unresolvedId;
102
- fsPath = unresolvedId;
103
- } else {
104
- throw error;
105
- }
106
- }
107
- const external = !isAbsolute(fsPath) || this.isAModuleDirectory(fsPath) ? rawId : null;
108
- return {
109
- id,
110
- fsPath,
111
- external
112
- };
113
- }
114
- async resolveMocks() {
115
- if (!VitestMocker.pendingIds.length)
116
- return;
117
- await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
118
- const { fsPath, external } = await this.resolvePath(mock.id, mock.importer);
119
- if (mock.type === "unmock")
120
- this.unmockPath(fsPath);
121
- if (mock.type === "mock")
122
- this.mockPath(mock.id, fsPath, external, mock.factory, mock.throwIfCached);
123
- }));
124
- VitestMocker.pendingIds = [];
125
- }
126
- async callFunctionMock(dep, mock) {
127
- var _a, _b;
128
- const cached = (_a = this.moduleCache.get(dep)) == null ? void 0 : _a.exports;
129
- if (cached)
130
- return cached;
131
- let exports;
132
- try {
133
- exports = await mock();
134
- } catch (err) {
135
- const vitestError = this.createError(
136
- '[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'
137
- );
138
- vitestError.cause = err;
139
- throw vitestError;
140
- }
141
- const filepath = dep.slice(5);
142
- const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
143
- if (exports === null || typeof exports !== "object")
144
- 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?`);
145
- const moduleExports = new Proxy(exports, {
146
- get: (target, prop) => {
147
- const val = target[prop];
148
- if (prop === "then") {
149
- if (target instanceof Promise)
150
- return target.then.bind(target);
151
- } else if (!(prop in target)) {
152
- if (this.filterPublicKeys.includes(prop))
153
- return void 0;
154
- const c = getColors();
155
- throw this.createError(
156
- `[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"?
157
- If you need to partially mock a module, you can use "importOriginal" helper inside:
158
-
159
- ${c.green(`vi.mock("${mockpath}", async (importOriginal) => {
160
- const actual = await importOriginal()
161
- return {
162
- ...actual,
163
- // your mocked methods
164
- }
165
- })`)}
166
- `
167
- );
168
- }
169
- return val;
170
- }
171
- });
172
- this.moduleCache.set(dep, { exports: moduleExports });
173
- return moduleExports;
174
- }
175
- getMockContext() {
176
- return this.mockContext;
177
- }
178
- getMockPath(dep) {
179
- return `mock:${dep}`;
180
- }
181
- getDependencyMock(id) {
182
- return this.getMocks()[id];
183
- }
184
- normalizePath(path) {
185
- return this.moduleCache.normalizePath(path);
186
- }
187
- resolveMockPath(mockPath, external) {
188
- const path = external || mockPath;
189
- if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
190
- const mockDirname = dirname(path);
191
- const mockFolder = join(this.root, "__mocks__", mockDirname);
192
- if (!existsSync(mockFolder))
193
- return null;
194
- const files = readdirSync(mockFolder);
195
- const baseOriginal = basename(path);
196
- for (const file of files) {
197
- const baseFile = basename(file, extname(file));
198
- if (baseFile === baseOriginal)
199
- return resolve(mockFolder, file);
200
- }
201
- return null;
202
- }
203
- const dir = dirname(path);
204
- const baseId = basename(path);
205
- const fullPath = resolve(dir, "__mocks__", baseId);
206
- return existsSync(fullPath) ? fullPath : null;
207
- }
208
- mockObject(object, mockExports = {}) {
209
- const finalizers = new Array();
210
- const refs = new RefTracker();
211
- const define = (container, key, value) => {
212
- try {
213
- container[key] = value;
214
- return true;
215
- } catch {
216
- return false;
217
- }
218
- };
219
- const mockPropertiesOf = (container, newContainer) => {
220
- const containerType = getType(container);
221
- const isModule = containerType === "Module" || !!container.__esModule;
222
- for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, this.primitives)) {
223
- if (!isModule && descriptor.get) {
224
- try {
225
- Object.defineProperty(newContainer, property, descriptor);
226
- } catch (error) {
227
- }
228
- continue;
229
- }
230
- if (isSpecialProp(property, containerType))
231
- continue;
232
- const value = container[property];
233
- const refId = refs.getId(value);
234
- if (refId !== void 0) {
235
- finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
236
- continue;
237
- }
238
- const type = getType(value);
239
- if (Array.isArray(value)) {
240
- define(newContainer, property, []);
241
- continue;
242
- }
243
- const isFunction = type.includes("Function") && typeof value === "function";
244
- if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") {
245
- define(newContainer, property, value);
246
- continue;
247
- }
248
- if (!define(newContainer, property, isFunction ? value : {}))
249
- continue;
250
- if (isFunction) {
251
- let mockFunction2 = function() {
252
- if (this instanceof newContainer[property]) {
253
- for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false, primitives)) {
254
- if (descriptor2.get)
255
- continue;
256
- const value2 = this[key];
257
- const type2 = getType(value2);
258
- const isFunction2 = type2.includes("Function") && typeof value2 === "function";
259
- if (isFunction2) {
260
- const original = this[key];
261
- const mock2 = spyModule.spyOn(this, key).mockImplementation(original);
262
- mock2.mockRestore = () => {
263
- mock2.mockReset();
264
- mock2.mockImplementation(original);
265
- return mock2;
266
- };
267
- }
268
- }
269
- }
270
- };
271
- if (!this.spyModule)
272
- throw this.createError("[vitest] `spyModule` is not defined. This is Vitest error. Please open a new issue with reproduction.");
273
- const spyModule = this.spyModule;
274
- const primitives = this.primitives;
275
- const mock = spyModule.spyOn(newContainer, property).mockImplementation(mockFunction2);
276
- mock.mockRestore = () => {
277
- mock.mockReset();
278
- mock.mockImplementation(mockFunction2);
279
- return mock;
280
- };
281
- Object.defineProperty(newContainer[property], "length", { value: 0 });
282
- }
283
- refs.track(value, newContainer[property]);
284
- mockPropertiesOf(value, newContainer[property]);
285
- }
286
- };
287
- const mockedObject = mockExports;
288
- mockPropertiesOf(object, mockedObject);
289
- for (const finalizer of finalizers)
290
- finalizer();
291
- return mockedObject;
292
- }
293
- unmockPath(path) {
294
- const suitefile = this.getSuiteFilepath();
295
- const id = this.normalizePath(path);
296
- const mock = this.mockMap.get(suitefile);
297
- if (mock && id in mock)
298
- delete mock[id];
299
- this.deleteCachedItem(id);
300
- }
301
- mockPath(originalId, path, external, factory, throwIfExists) {
302
- const id = this.normalizePath(path);
303
- if (throwIfExists && this.moduleCache.has(id))
304
- throw new Error(`[vitest] Cannot mock "${originalId}" because it is already loaded. Did you import it in a setup file?
305
-
306
- 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`);
307
- const suitefile = this.getSuiteFilepath();
308
- const mocks = this.mockMap.get(suitefile) || {};
309
- const resolves = this.resolveCache.get(suitefile) || {};
310
- mocks[id] = factory || this.resolveMockPath(path, external);
311
- resolves[id] = originalId;
312
- this.mockMap.set(suitefile, mocks);
313
- this.resolveCache.set(suitefile, resolves);
314
- this.deleteCachedItem(id);
315
- }
316
- async importActual(rawId, importer, callstack) {
317
- const { id, fsPath } = await this.resolvePath(rawId, importer);
318
- const result = await this.executor.cachedRequest(id, fsPath, callstack || [importer]);
319
- return result;
320
- }
321
- async importMock(rawId, importee) {
322
- const { id, fsPath, external } = await this.resolvePath(rawId, importee);
323
- const normalizedId = this.normalizePath(fsPath);
324
- let mock = this.getDependencyMock(normalizedId);
325
- if (mock === void 0)
326
- mock = this.resolveMockPath(fsPath, external);
327
- if (mock === null) {
328
- const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
329
- return this.mockObject(mod);
330
- }
331
- if (typeof mock === "function")
332
- return this.callFunctionMock(fsPath, mock);
333
- return this.executor.dependencyRequest(mock, mock, [importee]);
334
- }
335
- async requestWithMock(url, callstack) {
336
- const id = this.normalizePath(url);
337
- const mock = this.getDependencyMock(id);
338
- const mockPath = this.getMockPath(id);
339
- if (mock === null) {
340
- const cache = this.moduleCache.get(mockPath);
341
- if (cache.exports)
342
- return cache.exports;
343
- const exports = {};
344
- this.moduleCache.set(mockPath, { exports });
345
- const mod = await this.executor.directRequest(url, url, callstack);
346
- this.mockObject(mod, exports);
347
- return exports;
348
- }
349
- if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) {
350
- try {
351
- callstack.push(mockPath);
352
- this.mockContext.callstack = callstack;
353
- return await this.callFunctionMock(mockPath, mock);
354
- } finally {
355
- this.mockContext.callstack = null;
356
- const indexMock = callstack.indexOf(mockPath);
357
- callstack.splice(indexMock, 1);
358
- }
359
- }
360
- if (typeof mock === "string" && !callstack.includes(mock))
361
- return mock;
362
- }
363
- queueMock(id, importer, factory, throwIfCached = false) {
364
- VitestMocker.pendingIds.push({ type: "mock", id, importer, factory, throwIfCached });
365
- }
366
- queueUnmock(id, importer, throwIfCached = false) {
367
- VitestMocker.pendingIds.push({ type: "unmock", id, importer, throwIfCached });
368
- }
369
- }
370
-
371
- const _require = createRequire(import.meta.url);
372
- const requiresCache = /* @__PURE__ */ new WeakMap();
373
- class CommonjsExecutor {
374
- context;
375
- requireCache = /* @__PURE__ */ new Map();
376
- publicRequireCache = this.createProxyCache();
377
- moduleCache = /* @__PURE__ */ new Map();
378
- builtinCache = /* @__PURE__ */ Object.create(null);
379
- extensions = /* @__PURE__ */ Object.create(null);
380
- fs;
381
- Module;
382
- constructor(options) {
383
- this.context = options.context;
384
- this.fs = options.fileMap;
385
- const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
386
- const executor = this;
387
- this.Module = class Module$1 {
388
- exports;
389
- isPreloading = false;
390
- id;
391
- filename;
392
- loaded;
393
- parent;
394
- children = [];
395
- path;
396
- paths = [];
397
- constructor(id = "", parent) {
398
- this.exports = primitives.Object.create(Object.prototype);
399
- this.path = dirname(id);
400
- this.id = id;
401
- this.filename = id;
402
- this.loaded = false;
403
- this.parent = parent;
404
- }
405
- get require() {
406
- const require = requiresCache.get(this);
407
- if (require)
408
- return require;
409
- const _require2 = Module$1.createRequire(this.id);
410
- requiresCache.set(this, _require2);
411
- return _require2;
412
- }
413
- _compile(code, filename) {
414
- const cjsModule = Module$1.wrap(code);
415
- const script = new vm.Script(cjsModule, {
416
- filename,
417
- importModuleDynamically: options.importModuleDynamically
418
- });
419
- script.identifier = filename;
420
- const fn = script.runInContext(executor.context);
421
- const __dirname = dirname(filename);
422
- executor.requireCache.set(filename, this);
423
- try {
424
- fn(this.exports, this.require, this, filename, __dirname);
425
- return this.exports;
426
- } finally {
427
- this.loaded = true;
428
- }
429
- }
430
- // exposed for external use, Node.js does the opposite
431
- static _load = (request, parent, _isMain) => {
432
- const require = Module$1.createRequire((parent == null ? void 0 : parent.filename) ?? request);
433
- return require(request);
434
- };
435
- static wrap = (script) => {
436
- return Module$1.wrapper[0] + script + Module$1.wrapper[1];
437
- };
438
- static wrapper = new primitives.Array(
439
- "(function (exports, require, module, __filename, __dirname) { ",
440
- "\n});"
441
- );
442
- static builtinModules = Module.builtinModules;
443
- static findSourceMap = Module.findSourceMap;
444
- static SourceMap = Module.SourceMap;
445
- static syncBuiltinESMExports = Module.syncBuiltinESMExports;
446
- static _cache = executor.moduleCache;
447
- static _extensions = executor.extensions;
448
- static createRequire = (filename) => {
449
- return executor.createRequire(filename);
450
- };
451
- static runMain = () => {
452
- throw new primitives.Error('[vitest] "runMain" is not implemented.');
453
- };
454
- // @ts-expect-error not typed
455
- static _resolveFilename = Module._resolveFilename;
456
- // @ts-expect-error not typed
457
- static _findPath = Module._findPath;
458
- // @ts-expect-error not typed
459
- static _initPaths = Module._initPaths;
460
- // @ts-expect-error not typed
461
- static _preloadModules = Module._preloadModules;
462
- // @ts-expect-error not typed
463
- static _resolveLookupPaths = Module._resolveLookupPaths;
464
- // @ts-expect-error not typed
465
- static globalPaths = Module.globalPaths;
466
- static isBuiltin = Module.isBuiltin;
467
- static Module = Module$1;
468
- };
469
- this.extensions[".js"] = this.requireJs;
470
- this.extensions[".json"] = this.requireJson;
471
- }
472
- requireJs = (m, filename) => {
473
- const content = this.fs.readFile(filename);
474
- m._compile(content, filename);
475
- };
476
- requireJson = (m, filename) => {
477
- const code = this.fs.readFile(filename);
478
- m.exports = JSON.parse(code);
479
- };
480
- createRequire = (filename) => {
481
- const _require2 = createRequire(filename);
482
- const require = (id) => {
483
- const resolved = _require2.resolve(id);
484
- const ext = extname(resolved);
485
- if (ext === ".node" || isNodeBuiltin(resolved))
486
- return this.requireCoreModule(resolved);
487
- const module = new this.Module(resolved);
488
- return this.loadCommonJSModule(module, resolved);
489
- };
490
- require.resolve = _require2.resolve;
491
- Object.defineProperty(require, "extensions", {
492
- get: () => this.extensions,
493
- set: () => {
494
- },
495
- configurable: true
496
- });
497
- require.main = void 0;
498
- require.cache = this.publicRequireCache;
499
- return require;
500
- };
501
- createProxyCache() {
502
- return new Proxy(/* @__PURE__ */ Object.create(null), {
503
- defineProperty: () => true,
504
- deleteProperty: () => true,
505
- set: () => true,
506
- get: (_, key) => this.requireCache.get(key),
507
- has: (_, key) => this.requireCache.has(key),
508
- ownKeys: () => Array.from(this.requireCache.keys()),
509
- getOwnPropertyDescriptor() {
510
- return {
511
- configurable: true,
512
- enumerable: true
513
- };
514
- }
515
- });
516
- }
517
- // very naive implementation for Node.js require
518
- loadCommonJSModule(module, filename) {
519
- const cached = this.requireCache.get(filename);
520
- if (cached)
521
- return cached.exports;
522
- const extension = this.findLongestRegisteredExtension(filename);
523
- const loader = this.extensions[extension] || this.extensions[".js"];
524
- loader(module, filename);
525
- return module.exports;
526
- }
527
- findLongestRegisteredExtension(filename) {
528
- const name = basename(filename);
529
- let currentExtension;
530
- let index;
531
- let startIndex = 0;
532
- while ((index = name.indexOf(".", startIndex)) !== -1) {
533
- startIndex = index + 1;
534
- if (index === 0)
535
- continue;
536
- currentExtension = name.slice(index);
537
- if (this.extensions[currentExtension])
538
- return currentExtension;
539
- }
540
- return ".js";
541
- }
542
- require(identifier) {
543
- const ext = extname(identifier);
544
- if (ext === ".node" || isNodeBuiltin(identifier))
545
- return this.requireCoreModule(identifier);
546
- const module = new this.Module(identifier);
547
- return this.loadCommonJSModule(module, identifier);
548
- }
549
- requireCoreModule(identifier) {
550
- const normalized = identifier.replace(/^node:/, "");
551
- if (this.builtinCache[normalized])
552
- return this.builtinCache[normalized].exports;
553
- const moduleExports = _require(identifier);
554
- if (identifier === "node:module" || identifier === "module") {
555
- const module = new this.Module("/module.js");
556
- module.exports = this.Module;
557
- this.builtinCache[normalized] = module;
558
- return module.exports;
559
- }
560
- this.builtinCache[normalized] = _require.cache[normalized];
561
- return moduleExports;
562
- }
563
- }
564
-
565
- function interopCommonJsModule(interopDefault, mod) {
566
- if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) {
567
- return {
568
- keys: [],
569
- moduleExports: {},
570
- defaultExport: mod
571
- };
572
- }
573
- if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
574
- const defaultKets = Object.keys(mod.default);
575
- const moduleKeys = Object.keys(mod);
576
- const allKeys = /* @__PURE__ */ new Set([...defaultKets, ...moduleKeys]);
577
- allKeys.delete("default");
578
- return {
579
- keys: Array.from(allKeys),
580
- moduleExports: new Proxy(mod, {
581
- get(mod2, prop) {
582
- var _a;
583
- return mod2[prop] ?? ((_a = mod2.default) == null ? void 0 : _a[prop]);
584
- }
585
- }),
586
- defaultExport: mod
587
- };
588
- }
589
- return {
590
- keys: Object.keys(mod).filter((key) => key !== "default"),
591
- moduleExports: mod,
592
- defaultExport: mod
593
- };
594
- }
595
- const SyntheticModule$1 = vm.SyntheticModule;
596
- const SourceTextModule = vm.SourceTextModule;
597
-
598
- const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
599
- class EsmExecutor {
600
- constructor(executor, options) {
601
- this.executor = executor;
602
- this.context = options.context;
603
- }
604
- moduleCache = /* @__PURE__ */ new Map();
605
- esmLinkMap = /* @__PURE__ */ new WeakMap();
606
- context;
607
- async evaluateModule(m) {
608
- if (m.status === "unlinked") {
609
- this.esmLinkMap.set(
610
- m,
611
- m.link(
612
- (identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier)
613
- )
614
- );
615
- }
616
- await this.esmLinkMap.get(m);
617
- if (m.status === "linked")
618
- await m.evaluate();
619
- return m;
620
- }
621
- async createEsModule(fileUrl, code) {
622
- const cached = this.moduleCache.get(fileUrl);
623
- if (cached)
624
- return cached;
625
- if (fileUrl.endsWith(".json")) {
626
- const m2 = new SyntheticModule$1(
627
- ["default"],
628
- () => {
629
- const result = JSON.parse(code);
630
- m2.setExport("default", result);
631
- }
632
- );
633
- this.moduleCache.set(fileUrl, m2);
634
- return m2;
635
- }
636
- const m = new SourceTextModule(
637
- code,
638
- {
639
- identifier: fileUrl,
640
- context: this.context,
641
- importModuleDynamically: this.executor.importModuleDynamically,
642
- initializeImportMeta: (meta, mod) => {
643
- meta.url = mod.identifier;
644
- meta.resolve = (specifier, importer) => {
645
- return this.executor.resolve(specifier, importer ?? mod.identifier);
646
- };
647
- }
648
- }
649
- );
650
- this.moduleCache.set(fileUrl, m);
651
- return m;
652
- }
653
- async loadWebAssemblyModule(source, identifier) {
654
- const cached = this.moduleCache.get(identifier);
655
- if (cached)
656
- return cached;
657
- const wasmModule = await WebAssembly.compile(source);
658
- const exports = WebAssembly.Module.exports(wasmModule);
659
- const imports = WebAssembly.Module.imports(wasmModule);
660
- const moduleLookup = {};
661
- for (const { module } of imports) {
662
- if (moduleLookup[module] === void 0) {
663
- const resolvedModule = await this.executor.resolveModule(
664
- module,
665
- identifier
666
- );
667
- moduleLookup[module] = await this.evaluateModule(resolvedModule);
668
- }
669
- }
670
- const syntheticModule = new SyntheticModule$1(
671
- exports.map(({ name }) => name),
672
- () => {
673
- const importsObject = {};
674
- for (const { module, name } of imports) {
675
- if (!importsObject[module])
676
- importsObject[module] = {};
677
- importsObject[module][name] = moduleLookup[module].namespace[name];
678
- }
679
- const wasmInstance = new WebAssembly.Instance(
680
- wasmModule,
681
- importsObject
682
- );
683
- for (const { name } of exports)
684
- syntheticModule.setExport(name, wasmInstance.exports[name]);
685
- },
686
- { context: this.context, identifier }
687
- );
688
- return syntheticModule;
689
- }
690
- cacheModule(identifier, module) {
691
- this.moduleCache.set(identifier, module);
692
- }
693
- resolveCachedModule(identifier) {
694
- return this.moduleCache.get(identifier);
695
- }
696
- async createDataModule(identifier) {
697
- const cached = this.moduleCache.get(identifier);
698
- if (cached)
699
- return cached;
700
- const match = identifier.match(dataURIRegex);
701
- if (!match || !match.groups)
702
- throw new Error("Invalid data URI");
703
- const mime = match.groups.mime;
704
- const encoding = match.groups.encoding;
705
- if (mime === "application/wasm") {
706
- if (!encoding)
707
- throw new Error("Missing data URI encoding");
708
- if (encoding !== "base64")
709
- throw new Error(`Invalid data URI encoding: ${encoding}`);
710
- const module = await this.loadWebAssemblyModule(
711
- Buffer.from(match.groups.code, "base64"),
712
- identifier
713
- );
714
- this.moduleCache.set(identifier, module);
715
- return module;
716
- }
717
- let code = match.groups.code;
718
- if (!encoding || encoding === "charset=utf-8")
719
- code = decodeURIComponent(code);
720
- else if (encoding === "base64")
721
- code = Buffer.from(code, "base64").toString();
722
- else
723
- throw new Error(`Invalid data URI encoding: ${encoding}`);
724
- if (mime === "application/json") {
725
- const module = new SyntheticModule$1(
726
- ["default"],
727
- () => {
728
- const obj = JSON.parse(code);
729
- module.setExport("default", obj);
730
- },
731
- { context: this.context, identifier }
732
- );
733
- this.moduleCache.set(identifier, module);
734
- return module;
735
- }
736
- return this.createEsModule(identifier, code);
737
- }
738
- }
739
-
740
- const CLIENT_ID = "/@vite/client";
741
- const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
742
- class ViteExecutor {
743
- constructor(options) {
744
- this.options = options;
745
- this.esm = options.esmExecutor;
746
- }
747
- esm;
748
- resolve = (identifier, parent) => {
749
- if (identifier === CLIENT_ID) {
750
- if (this.workerState.environment.transformMode === "web")
751
- return identifier;
752
- const packageName = this.getPackageName(parent);
753
- throw new Error(
754
- `[vitest] Vitest cannot handle ${CLIENT_ID} imported in ${parent} when running in SSR environment. Add "${packageName}" to "ssr.noExternal" if you are using Vite SSR, or to "server.deps.inline" if you are using Vite Node.`
755
- );
756
- }
757
- };
758
- get workerState() {
759
- return this.options.context.__vitest_worker__;
760
- }
761
- getPackageName(modulePath) {
762
- const path = normalize(modulePath);
763
- let name = path.split("/node_modules/").pop() || "";
764
- if (name == null ? void 0 : name.startsWith("@"))
765
- name = name.split("/").slice(0, 2).join("/");
766
- else
767
- name = name.split("/")[0];
768
- return name;
769
- }
770
- async createViteModule(fileUrl) {
771
- if (fileUrl === CLIENT_FILE)
772
- return this.createViteClientModule();
773
- const cached = this.esm.resolveCachedModule(fileUrl);
774
- if (cached)
775
- return cached;
776
- const result = await this.options.transform(fileUrl, "web");
777
- if (!result.code)
778
- throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
779
- return this.esm.createEsModule(fileUrl, result.code);
780
- }
781
- createViteClientModule() {
782
- const identifier = CLIENT_ID;
783
- const cached = this.esm.resolveCachedModule(identifier);
784
- if (cached)
785
- return cached;
786
- const stub = this.options.viteClientModule;
787
- const moduleKeys = Object.keys(stub);
788
- const module = new SyntheticModule$1(
789
- moduleKeys,
790
- () => {
791
- moduleKeys.forEach((key) => {
792
- module.setExport(key, stub[key]);
793
- });
794
- },
795
- { context: this.options.context, identifier }
796
- );
797
- this.esm.cacheModule(identifier, module);
798
- return module;
799
- }
800
- canResolve = (fileUrl) => {
801
- var _a;
802
- const transformMode = this.workerState.environment.transformMode;
803
- if (transformMode !== "web")
804
- return false;
805
- if (fileUrl === CLIENT_FILE)
806
- return true;
807
- const config = ((_a = this.workerState.config.deps) == null ? void 0 : _a.web) || {};
808
- const [modulePath] = fileUrl.split("?");
809
- if (config.transformCss && CSS_LANGS_RE.test(modulePath))
810
- return true;
811
- if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath))
812
- return true;
813
- if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath)))
814
- return true;
815
- return false;
816
- };
817
- }
818
-
819
- const SyntheticModule = vm.SyntheticModule;
820
- const nativeResolve = import.meta.resolve;
821
- class ExternalModulesExecutor {
822
- constructor(options) {
823
- this.options = options;
824
- this.context = options.context;
825
- this.fs = options.fileMap;
826
- this.esm = new EsmExecutor(this, {
827
- context: this.context
828
- });
829
- this.cjs = new CommonjsExecutor({
830
- context: this.context,
831
- importModuleDynamically: this.importModuleDynamically,
832
- fileMap: options.fileMap
833
- });
834
- this.vite = new ViteExecutor({
835
- esmExecutor: this.esm,
836
- context: this.context,
837
- transform: options.transform,
838
- viteClientModule: options.requestStubs["/@vite/client"]
839
- });
840
- this.resolvers = [this.vite.resolve];
841
- }
842
- cjs;
843
- esm;
844
- vite;
845
- context;
846
- fs;
847
- resolvers = [];
848
- // dynamic import can be used in both ESM and CJS, so we have it in the executor
849
- importModuleDynamically = async (specifier, referencer) => {
850
- const module = await this.resolveModule(specifier, referencer.identifier);
851
- return this.esm.evaluateModule(module);
852
- };
853
- resolveModule = async (specifier, referencer) => {
854
- const identifier = await this.resolve(specifier, referencer);
855
- return await this.createModule(identifier);
856
- };
857
- async resolve(specifier, parent) {
858
- for (const resolver of this.resolvers) {
859
- const id = resolver(specifier, parent);
860
- if (id)
861
- return id;
862
- }
863
- return nativeResolve(specifier, parent);
864
- }
865
- findNearestPackageData(basedir) {
866
- var _a;
867
- const originalBasedir = basedir;
868
- const packageCache = this.options.packageCache;
869
- while (basedir) {
870
- const cached = getCachedData(packageCache, basedir, originalBasedir);
871
- if (cached)
872
- return cached;
873
- const pkgPath = join(basedir, "package.json");
874
- try {
875
- if ((_a = statSync(pkgPath, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile()) {
876
- const pkgData = JSON.parse(this.fs.readFile(pkgPath));
877
- if (packageCache)
878
- setCacheData(packageCache, pkgData, basedir, originalBasedir);
879
- return pkgData;
880
- }
881
- } catch {
882
- }
883
- const nextBasedir = dirname$1(basedir);
884
- if (nextBasedir === basedir)
885
- break;
886
- basedir = nextBasedir;
887
- }
888
- return {};
889
- }
890
- wrapCoreSynteticModule(identifier, exports) {
891
- const moduleKeys = Object.keys(exports);
892
- const m = new SyntheticModule(
893
- [...moduleKeys, "default"],
894
- () => {
895
- for (const key of moduleKeys)
896
- m.setExport(key, exports[key]);
897
- m.setExport("default", exports);
898
- },
899
- {
900
- context: this.context,
901
- identifier
902
- }
903
- );
904
- return m;
905
- }
906
- wrapCommonJsSynteticModule(identifier, exports) {
907
- const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.options.interopDefault, exports);
908
- const m = new SyntheticModule(
909
- [...keys, "default"],
910
- () => {
911
- for (const key of keys)
912
- m.setExport(key, moduleExports[key]);
913
- m.setExport("default", defaultExport);
914
- },
915
- {
916
- context: this.context,
917
- identifier
918
- }
919
- );
920
- return m;
921
- }
922
- getModuleInformation(identifier) {
923
- if (identifier.startsWith("data:"))
924
- return { type: "data", url: identifier, path: identifier };
925
- const extension = extname(identifier);
926
- if (extension === ".node" || isNodeBuiltin(identifier))
927
- return { type: "builtin", url: identifier, path: identifier };
928
- const isFileUrl = identifier.startsWith("file://");
929
- const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
930
- const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
931
- let type;
932
- if (this.vite.canResolve(fileUrl)) {
933
- type = "vite";
934
- } else if (extension === ".mjs") {
935
- type = "module";
936
- } else if (extension === ".cjs") {
937
- type = "commonjs";
938
- } else {
939
- const pkgData = this.findNearestPackageData(normalize(pathUrl));
940
- type = pkgData.type === "module" ? "module" : "commonjs";
941
- }
942
- return { type, path: pathUrl, url: fileUrl };
943
- }
944
- async createModule(identifier) {
945
- const { type, url, path } = this.getModuleInformation(identifier);
946
- switch (type) {
947
- case "data":
948
- return this.esm.createDataModule(identifier);
949
- case "builtin": {
950
- const exports = this.require(identifier);
951
- return this.wrapCoreSynteticModule(identifier, exports);
952
- }
953
- case "vite":
954
- return await this.vite.createViteModule(url);
955
- case "module":
956
- return await this.esm.createEsModule(url, this.fs.readFile(path));
957
- case "commonjs": {
958
- const exports = this.require(path);
959
- return this.wrapCommonJsSynteticModule(identifier, exports);
960
- }
961
- default: {
962
- const _deadend = type;
963
- return _deadend;
964
- }
965
- }
966
- }
967
- async import(identifier) {
968
- const module = await this.createModule(identifier);
969
- await this.esm.evaluateModule(module);
970
- return module.namespace;
971
- }
972
- require(identifier) {
973
- return this.cjs.require(identifier);
974
- }
975
- createRequire(identifier) {
976
- return this.cjs.createRequire(identifier);
977
- }
978
- }
979
-
980
- class FileMap {
981
- fsCache = /* @__PURE__ */ new Map();
982
- fsBufferCache = /* @__PURE__ */ new Map();
983
- readFile(path) {
984
- const cached = this.fsCache.get(path);
985
- if (cached)
986
- return cached;
987
- const source = readFileSync(path, "utf-8");
988
- this.fsCache.set(path, source);
989
- return source;
990
- }
991
- readBuffer(path) {
992
- const cached = this.fsBufferCache.get(path);
993
- if (cached)
994
- return cached;
995
- const buffer = readFileSync(path);
996
- this.fsBufferCache.set(path, buffer);
997
- return buffer;
998
- }
999
- }
1000
-
1001
- const entryUrl = pathToFileURL(resolve(distDir, "entry.js")).href;
1002
- async function createVitestExecutor(options) {
1003
- const runner = new VitestExecutor(options);
1004
- await runner.executeId("/@vite/env");
1005
- await runner.mocker.initializeSpyModule();
1006
- return runner;
1007
- }
1008
- let _viteNode;
1009
- const packageCache = /* @__PURE__ */ new Map();
1010
- const moduleCache = new ModuleCacheMap();
1011
- const mockMap = /* @__PURE__ */ new Map();
1012
- const fileMap = new FileMap();
1013
- const externalizeMap = /* @__PURE__ */ new Map();
1014
- async function startViteNode(options) {
1015
- if (_viteNode)
1016
- return _viteNode;
1017
- const executor = await startVitestExecutor(options);
1018
- const { run } = await import(entryUrl);
1019
- _viteNode = { run, executor };
1020
- return _viteNode;
1021
- }
1022
- const bareVitestRegexp = /^@?vitest(\/|$)/;
1023
- async function startVitestExecutor(options) {
1024
- const state = () => globalThis.__vitest_worker__ || options.state;
1025
- const rpc = () => state().rpc;
1026
- const processExit = process.exit;
1027
- process.exit = (code = process.exitCode || 0) => {
1028
- const error = new Error(`process.exit called with "${code}"`);
1029
- rpc().onWorkerExit(error, code);
1030
- return processExit(code);
1031
- };
1032
- function catchError(err, type) {
1033
- var _a;
1034
- const worker = state();
1035
- const error = processError(err);
1036
- if (!isPrimitive(error)) {
1037
- error.VITEST_TEST_NAME = (_a = worker.current) == null ? void 0 : _a.name;
1038
- if (worker.filepath)
1039
- error.VITEST_TEST_PATH = relative(state().config.root, worker.filepath);
1040
- error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
1041
- }
1042
- rpc().onUnhandledError(error, type);
1043
- }
1044
- process.setMaxListeners(25);
1045
- process.on("uncaughtException", (e) => catchError(e, "Uncaught Exception"));
1046
- process.on("unhandledRejection", (e) => catchError(e, "Unhandled Rejection"));
1047
- const getTransformMode = () => {
1048
- return state().environment.transformMode ?? "ssr";
1049
- };
1050
- return await createVitestExecutor({
1051
- async fetchModule(id) {
1052
- if (externalizeMap.has(id))
1053
- return { externalize: externalizeMap.get(id) };
1054
- if (id.includes(distDir)) {
1055
- const { path } = toFilePath(id, state().config.root);
1056
- const externalize = pathToFileURL(path).toString();
1057
- externalizeMap.set(id, externalize);
1058
- return { externalize };
1059
- }
1060
- if (bareVitestRegexp.test(id)) {
1061
- externalizeMap.set(id, id);
1062
- return { externalize: id };
1063
- }
1064
- return rpc().fetch(id, getTransformMode());
1065
- },
1066
- resolveId(id, importer) {
1067
- return rpc().resolveId(id, importer, getTransformMode());
1068
- },
1069
- transform(id) {
1070
- return rpc().transform(id, "web");
1071
- },
1072
- packageCache,
1073
- moduleCache,
1074
- mockMap,
1075
- get interopDefault() {
1076
- return state().config.deps.interopDefault;
1077
- },
1078
- get moduleDirectories() {
1079
- return state().config.deps.moduleDirectories;
1080
- },
1081
- get root() {
1082
- return state().config.root;
1083
- },
1084
- get base() {
1085
- return state().config.base;
1086
- },
1087
- ...options
1088
- });
1089
- }
1090
- function updateStyle(id, css) {
1091
- if (typeof document === "undefined")
1092
- return;
1093
- const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
1094
- if (element) {
1095
- element.textContent = css;
1096
- return;
1097
- }
1098
- const head = document.querySelector("head");
1099
- const style = document.createElement("style");
1100
- style.setAttribute("type", "text/css");
1101
- style.setAttribute("data-vite-dev-id", id);
1102
- style.textContent = css;
1103
- head == null ? void 0 : head.appendChild(style);
1104
- }
1105
- function removeStyle(id) {
1106
- if (typeof document === "undefined")
1107
- return;
1108
- const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
1109
- if (sheet)
1110
- document.head.removeChild(sheet);
1111
- }
1112
- class VitestExecutor extends ViteNodeRunner {
1113
- constructor(options) {
1114
- super({
1115
- ...options,
1116
- // interop is done inside the external executor instead
1117
- interopDefault: options.context ? false : options.interopDefault
1118
- });
1119
- this.options = options;
1120
- this.mocker = new VitestMocker(this);
1121
- if (!options.context) {
1122
- Object.defineProperty(globalThis, "__vitest_mocker__", {
1123
- value: this.mocker,
1124
- writable: true,
1125
- configurable: true
1126
- });
1127
- const clientStub = { ...DEFAULT_REQUEST_STUBS["@vite/client"], updateStyle, removeStyle };
1128
- this.options.requestStubs = {
1129
- "/@vite/client": clientStub,
1130
- "@vite/client": clientStub
1131
- };
1132
- this.primitives = {
1133
- Object,
1134
- Reflect,
1135
- Symbol
1136
- };
1137
- } else {
1138
- const clientStub = vm.runInContext(
1139
- `(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
1140
- options.context
1141
- )(DEFAULT_REQUEST_STUBS["@vite/client"]);
1142
- this.options.requestStubs = {
1143
- "/@vite/client": clientStub,
1144
- "@vite/client": clientStub
1145
- };
1146
- this.primitives = vm.runInContext("({ Object, Reflect, Symbol })", options.context);
1147
- this.externalModules = new ExternalModulesExecutor({
1148
- ...options,
1149
- fileMap,
1150
- context: options.context,
1151
- packageCache: options.packageCache
1152
- });
1153
- }
1154
- }
1155
- mocker;
1156
- externalModules;
1157
- primitives;
1158
- getContextPrimitives() {
1159
- return this.primitives;
1160
- }
1161
- get state() {
1162
- return globalThis.__vitest_worker__ || this.options.state;
1163
- }
1164
- shouldResolveId(id, _importee) {
1165
- var _a;
1166
- if (isInternalRequest(id) || id.startsWith("data:"))
1167
- return false;
1168
- const transformMode = ((_a = this.state.environment) == null ? void 0 : _a.transformMode) ?? "ssr";
1169
- return transformMode === "ssr" ? !isNodeBuiltin(id) : !id.startsWith("node:");
1170
- }
1171
- async originalResolveUrl(id, importer) {
1172
- return super.resolveUrl(id, importer);
1173
- }
1174
- async resolveUrl(id, importer) {
1175
- if (VitestMocker.pendingIds.length)
1176
- await this.mocker.resolveMocks();
1177
- if (importer && importer.startsWith("mock:"))
1178
- importer = importer.slice(5);
1179
- try {
1180
- return await super.resolveUrl(id, importer);
1181
- } catch (error) {
1182
- if (error.code === "ERR_MODULE_NOT_FOUND") {
1183
- const { id: id2 } = error[Symbol.for("vitest.error.not_found.data")];
1184
- const path = this.mocker.normalizePath(id2);
1185
- const mock = this.mocker.getDependencyMock(path);
1186
- if (mock !== void 0)
1187
- return [id2, id2];
1188
- }
1189
- throw error;
1190
- }
1191
- }
1192
- async runModule(context, transformed) {
1193
- const vmContext = this.options.context;
1194
- if (!vmContext || !this.externalModules)
1195
- return super.runModule(context, transformed);
1196
- const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
1197
- const code = `${codeDefinition}${transformed}
1198
- }}`;
1199
- const options = {
1200
- filename: context.__filename,
1201
- lineOffset: 0,
1202
- columnOffset: -codeDefinition.length
1203
- };
1204
- const fn = vm.runInContext(code, vmContext, {
1205
- ...options,
1206
- // if we encountered an import, it's not inlined
1207
- importModuleDynamically: this.externalModules.importModuleDynamically
1208
- });
1209
- await fn(...Object.values(context));
1210
- }
1211
- async importExternalModule(path) {
1212
- if (this.externalModules)
1213
- return this.externalModules.import(path);
1214
- return super.importExternalModule(path);
1215
- }
1216
- async dependencyRequest(id, fsPath, callstack) {
1217
- const mocked = await this.mocker.requestWithMock(fsPath, callstack);
1218
- if (typeof mocked === "string")
1219
- return super.dependencyRequest(mocked, mocked, callstack);
1220
- if (mocked && typeof mocked === "object")
1221
- return mocked;
1222
- return super.dependencyRequest(id, fsPath, callstack);
1223
- }
1224
- prepareContext(context) {
1225
- if (this.state.filepath && normalize(this.state.filepath) === normalize(context.__filename)) {
1226
- const globalNamespace = this.options.context || globalThis;
1227
- Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalNamespace.__vitest_index__ });
1228
- }
1229
- if (this.options.context && this.externalModules)
1230
- context.require = this.externalModules.createRequire(context.__filename);
1231
- return context;
1232
- }
1233
- }
1234
-
1235
- export { VitestExecutor as V, mockMap as a, startVitestExecutor as b, moduleCache as m, startViteNode as s };