vitest 4.0.0-beta.9 → 4.0.1

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 (83) hide show
  1. package/LICENSE.md +86 -102
  2. package/browser/context.d.ts +7 -0
  3. package/browser/context.js +20 -0
  4. package/dist/browser.d.ts +24 -7
  5. package/dist/browser.js +15 -5
  6. package/dist/chunks/{base.CA5N8Af0.js → base.BYPMk0VN.js} +36 -36
  7. package/dist/chunks/{benchmark.CJUa-Hsa.js → benchmark.DHKMYAts.js} +2 -2
  8. package/dist/chunks/{browser.d.DtfyY9yS.d.ts → browser.d.B9iJzZyn.d.ts} +3 -3
  9. package/dist/chunks/{cac.Dt7e1TIu.js → cac.DrF4Gm0S.js} +47 -73
  10. package/dist/chunks/{cli-api.eAzsLIxz.js → cli-api.W2Q-JQoO.js} +1524 -296
  11. package/dist/chunks/{config.d.DacWrqWe.d.ts → config.d.u2CUDWwS.d.ts} +5 -19
  12. package/dist/chunks/{console.7h5kHUIf.js → console.CTJL2nuH.js} +4 -6
  13. package/dist/chunks/{coverage.CDRAMTt7.js → coverage.FU3w4IrQ.js} +125 -1108
  14. package/dist/chunks/{creator.KEg6n5IC.js → creator.DucAaYBz.js} +10 -37
  15. package/dist/chunks/{defaults.CXFFjsi8.js → defaults.BOqNVLsY.js} +0 -1
  16. package/dist/chunks/environment.d.CrsxCzP1.d.ts +29 -0
  17. package/dist/chunks/evaluatedModules.Dg1zASAC.js +17 -0
  18. package/dist/chunks/{global.d.K6uBQHzY.d.ts → global.d.BgJSTpgQ.d.ts} +2 -17
  19. package/dist/chunks/{globals.CJrTTbxC.js → globals.BGT_RUsD.js} +11 -7
  20. package/dist/chunks/{index.BjKEiSn0.js → index.BdSLhLDZ.js} +3 -3
  21. package/dist/chunks/{index.DfviD7lX.js → index.CbWINfS7.js} +49 -21
  22. package/dist/chunks/{index.BIP7prJq.js → index.CcRZ6fUh.js} +1493 -114
  23. package/dist/chunks/{index.X0nbfr6-.js → index.Dc3xnDvT.js} +48 -289
  24. package/dist/chunks/{index.C832ioot.js → index.RwjEGCQ0.js} +4 -4
  25. package/dist/chunks/init-forks.WglB-sfY.js +54 -0
  26. package/dist/chunks/init-threads.Czek6eA5.js +17 -0
  27. package/dist/chunks/init.94FWN9pW.js +213 -0
  28. package/dist/chunks/{inspector.CvQD-Nie.js → inspector.DLZxSeU3.js} +2 -6
  29. package/dist/chunks/{moduleRunner.d.DxTLreRD.d.ts → moduleRunner.d.YtNsMIoJ.d.ts} +9 -14
  30. package/dist/chunks/{node.CyipiPvJ.js → node.BwAWWjHZ.js} +3 -4
  31. package/dist/chunks/{plugin.d.CIk0YiKb.d.ts → plugin.d.DQU1R5px.d.ts} +1 -1
  32. package/dist/chunks/{reporters.d.DmP-iHLr.d.ts → reporters.d.BMKt7f6I.d.ts} +1064 -1021
  33. package/dist/chunks/{resolveSnapshotEnvironment.Bvv2zr69.js → resolveSnapshotEnvironment.DJJKMKxb.js} +7 -8
  34. package/dist/chunks/{rpc.BKr6mtxz.js → rpc.cD77ENhU.js} +13 -14
  35. package/dist/chunks/{setup-common.B7I37Tji.js → setup-common.DR1sucx6.js} +6 -6
  36. package/dist/chunks/{startModuleRunner.BDRvKSdz.js → startModuleRunner.iF1E9Bt4.js} +126 -110
  37. package/dist/chunks/{test.BAlBebnP.js → test.C3RPt8JR.js} +7 -7
  38. package/dist/chunks/{utils.D2R2NiOH.js → utils.CG9h5ccR.js} +2 -5
  39. package/dist/chunks/{vi.BB37KeLx.js → vi.BZvkKVkM.js} +61 -164
  40. package/dist/chunks/{vm.CjLTDaST.js → vm.CuMWYx_F.js} +20 -29
  41. package/dist/chunks/{worker.d.B2r4Ln6p.d.ts → worker.d.BFk-vvBU.d.ts} +42 -6
  42. package/dist/cli.js +12 -11
  43. package/dist/config.cjs +0 -1
  44. package/dist/config.d.ts +11 -13
  45. package/dist/config.js +1 -1
  46. package/dist/coverage.d.ts +7 -6
  47. package/dist/coverage.js +3 -14
  48. package/dist/environments.d.ts +3 -6
  49. package/dist/environments.js +1 -1
  50. package/dist/index.d.ts +20 -25
  51. package/dist/index.js +11 -7
  52. package/dist/module-evaluator.d.ts +5 -4
  53. package/dist/module-evaluator.js +11 -13
  54. package/dist/module-runner.js +5 -5
  55. package/dist/node.d.ts +82 -25
  56. package/dist/node.js +23 -20
  57. package/dist/reporters.d.ts +10 -9
  58. package/dist/reporters.js +12 -11
  59. package/dist/runners.d.ts +1 -1
  60. package/dist/runners.js +9 -7
  61. package/dist/snapshot.js +3 -3
  62. package/dist/suite.js +4 -3
  63. package/dist/worker.d.ts +26 -0
  64. package/dist/worker.js +45 -165
  65. package/dist/workers/forks.js +26 -43
  66. package/dist/workers/runVmTests.js +16 -12
  67. package/dist/workers/threads.js +26 -31
  68. package/dist/workers/vmForks.js +26 -39
  69. package/dist/workers/vmThreads.js +26 -29
  70. package/package.json +48 -32
  71. package/worker.d.ts +1 -0
  72. package/browser.d.ts +0 -1
  73. package/dist/chunks/environment.d.2fYMoz3o.d.ts +0 -66
  74. package/dist/chunks/moduleTransport.I-bgQy0S.js +0 -19
  75. package/dist/chunks/resolver.Bx6lE0iq.js +0 -119
  76. package/dist/chunks/typechecker.DB-fIMaH.js +0 -805
  77. package/dist/chunks/utils.C2YI6McM.js +0 -52
  78. package/dist/chunks/worker.d.DJ6qxO2w.d.ts +0 -8
  79. package/dist/workers.d.ts +0 -38
  80. package/dist/workers.js +0 -49
  81. package/execute.d.ts +0 -1
  82. package/utils.d.ts +0 -1
  83. package/workers.d.ts +0 -1
@@ -1,13 +1,15 @@
1
- import { chai as chai$1, equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
1
+ import { chai, equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
2
2
  import { getCurrentTest } from '@vitest/runner';
3
3
  import { getNames, getTestName } from '@vitest/runner/utils';
4
- import { g as getWorkerState, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.D2R2NiOH.js';
5
- import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
6
- import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
4
+ import { g as getWorkerState, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.CG9h5ccR.js';
5
+ import { getSafeTimers } from '@vitest/utils/timers';
7
6
  import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
8
7
  import '@vitest/utils/error';
8
+ import { assertTypes, createSimpleStackTrace } from '@vitest/utils/helpers';
9
9
  import { fn, spyOn, restoreAllMocks, resetAllMocks, clearAllMocks, isMockFunction } from '@vitest/spy';
10
+ import '@vitest/utils/offset';
10
11
  import { parseSingleStack } from '@vitest/utils/source-map';
12
+ import { c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
11
13
  import { R as RealDate, r as resetDate, m as mockDate } from './date.-jtEtIeV.js';
12
14
 
13
15
  // these matchers are not supported because they don't make sense with poll
@@ -25,13 +27,13 @@ const unsupported = [
25
27
  ];
26
28
  function createExpectPoll(expect) {
27
29
  return function poll(fn, options = {}) {
28
- const state = getWorkerState(), defaults = state.config.expect?.poll ?? {}, { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options, assertion = expect(null, message).withContext({ poll: true });
30
+ const defaults = getWorkerState().config.expect?.poll ?? {}, { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options, assertion = expect(null, message).withContext({ poll: true });
29
31
  fn = fn.bind(assertion);
30
- const test = chai$1.util.flag(assertion, "vitest-test");
32
+ const test = chai.util.flag(assertion, "vitest-test");
31
33
  if (!test) throw new Error("expect.poll() must be called inside a test");
32
34
  const proxy = new Proxy(assertion, { get(target, key, receiver) {
33
35
  const assertionFunction = Reflect.get(target, key, receiver);
34
- if (typeof assertionFunction !== "function") return assertionFunction instanceof chai$1.Assertion ? proxy : assertionFunction;
36
+ if (typeof assertionFunction !== "function") return assertionFunction instanceof chai.Assertion ? proxy : assertionFunction;
35
37
  if (key === "assert") return assertionFunction;
36
38
  if (typeof key === "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
37
39
  return function(...args) {
@@ -39,17 +41,18 @@ function createExpectPoll(expect) {
39
41
  let intervalId, timeoutId, lastError;
40
42
  const { setTimeout, clearTimeout } = getSafeTimers(), check = async () => {
41
43
  try {
42
- chai$1.util.flag(assertion, "_name", key);
44
+ chai.util.flag(assertion, "_name", key);
43
45
  const obj = await fn();
44
- chai$1.util.flag(assertion, "object", obj), resolve(await assertionFunction.call(assertion, ...args)), clearTimeout(intervalId), clearTimeout(timeoutId);
46
+ chai.util.flag(assertion, "object", obj), resolve(await assertionFunction.call(assertion, ...args)), clearTimeout(intervalId), clearTimeout(timeoutId);
45
47
  } catch (err) {
46
- if (lastError = err, !chai$1.util.flag(assertion, "_isLastPollAttempt")) intervalId = setTimeout(check, interval);
48
+ if (lastError = err, !chai.util.flag(assertion, "_isLastPollAttempt")) intervalId = setTimeout(check, interval);
47
49
  }
48
50
  };
49
51
  timeoutId = setTimeout(() => {
50
- clearTimeout(intervalId), chai$1.util.flag(assertion, "_isLastPollAttempt", true);
51
- const rejectWithCause = (cause) => {
52
- reject(copyStackTrace$1(new Error("Matcher did not succeed in time.", { cause }), STACK_TRACE_ERROR));
52
+ clearTimeout(intervalId), chai.util.flag(assertion, "_isLastPollAttempt", true);
53
+ const rejectWithCause = (error) => {
54
+ if (error.cause == null) error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.");
55
+ reject(copyStackTrace$1(error, STACK_TRACE_ERROR));
53
56
  };
54
57
  check().then(() => rejectWithCause(lastError)).catch((e) => rejectWithCause(e));
55
58
  }, timeout), check();
@@ -57,7 +60,7 @@ function createExpectPoll(expect) {
57
60
  let awaited = false;
58
61
  test.onFinished ??= [], test.onFinished.push(() => {
59
62
  if (!awaited) {
60
- const negated = chai$1.util.flag(assertion, "negate") ? "not." : "", name = chai$1.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)", assertionString = `expect.${name}.${negated}${String(key)}()`, error = /* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`);
63
+ const negated = chai.util.flag(assertion, "negate") ? "not." : "", assertionString = `expect.${chai.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`, error = /* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`);
61
64
  throw copyStackTrace$1(error, STACK_TRACE_ERROR);
62
65
  }
63
66
  });
@@ -86,108 +89,9 @@ function copyStackTrace$1(target, source) {
86
89
  return target;
87
90
  }
88
91
 
89
- function commonjsRequire(path) {
90
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
91
- }
92
-
93
- var chaiSubset$1 = {exports: {}};
94
-
95
- var chaiSubset = chaiSubset$1.exports;
96
-
97
- var hasRequiredChaiSubset;
98
-
99
- function requireChaiSubset () {
100
- if (hasRequiredChaiSubset) return chaiSubset$1.exports;
101
- hasRequiredChaiSubset = 1;
102
- (function (module, exports) {
103
- (function() {
104
- (function(chaiSubset) {
105
- if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
106
- return module.exports = chaiSubset;
107
- } else {
108
- return chai.use(chaiSubset);
109
- }
110
- })(function(chai, utils) {
111
- var Assertion = chai.Assertion;
112
- var assertionPrototype = Assertion.prototype;
113
-
114
- Assertion.addMethod('containSubset', function (expected) {
115
- var actual = utils.flag(this, 'object');
116
- var showDiff = chai.config.showDiff;
117
-
118
- assertionPrototype.assert.call(this,
119
- compare(expected, actual),
120
- 'expected #{act} to contain subset #{exp}',
121
- 'expected #{act} to not contain subset #{exp}',
122
- expected,
123
- actual,
124
- showDiff
125
- );
126
- });
127
-
128
- chai.assert.containSubset = function(val, exp, msg) {
129
- new chai.Assertion(val, msg).to.be.containSubset(exp);
130
- };
131
-
132
- function compare(expected, actual) {
133
- if (expected === actual) {
134
- return true;
135
- }
136
- if (typeof(actual) !== typeof(expected)) {
137
- return false;
138
- }
139
- if (typeof(expected) !== 'object' || expected === null) {
140
- return expected === actual;
141
- }
142
- if (!!expected && !actual) {
143
- return false;
144
- }
145
-
146
- if (Array.isArray(expected)) {
147
- if (typeof(actual.length) !== 'number') {
148
- return false;
149
- }
150
- var aa = Array.prototype.slice.call(actual);
151
- return expected.every(function (exp) {
152
- return aa.some(function (act) {
153
- return compare(exp, act);
154
- });
155
- });
156
- }
157
-
158
- if (expected instanceof Date) {
159
- if (actual instanceof Date) {
160
- return expected.getTime() === actual.getTime();
161
- } else {
162
- return false;
163
- }
164
- }
165
-
166
- return Object.keys(expected).every(function (key) {
167
- var eo = expected[key];
168
- var ao = actual[key];
169
- if (typeof(eo) === 'object' && eo !== null && ao !== null) {
170
- return compare(eo, ao);
171
- }
172
- if (typeof(eo) === 'function') {
173
- return eo(ao);
174
- }
175
- return ao === eo;
176
- });
177
- }
178
- });
179
-
180
- }).call(chaiSubset);
181
- } (chaiSubset$1));
182
- return chaiSubset$1.exports;
183
- }
184
-
185
- var chaiSubsetExports = requireChaiSubset();
186
- var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
187
-
188
92
  function createAssertionMessage(util, assertion, hasArgs) {
189
- const not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${"expected" })`, promiseName = util.flag(assertion, "promise"), promise = promiseName ? `.${promiseName}` : "";
190
- return `expect(actual)${promise}.${not}${name}`;
93
+ const not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${"expected" })`, promiseName = util.flag(assertion, "promise");
94
+ return `expect(actual)${promiseName ? `.${promiseName}` : ""}.${not}${name}`;
191
95
  }
192
96
  function recordAsyncExpect(_test, promise, assertion, error) {
193
97
  const test = _test;
@@ -203,7 +107,7 @@ function recordAsyncExpect(_test, promise, assertion, error) {
203
107
  let resolved = false;
204
108
  return test.onFinished ??= [], test.onFinished.push(() => {
205
109
  if (!resolved) {
206
- const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""), stack = processor(error.stack);
110
+ const stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
207
111
  console.warn([
208
112
  `Promise returned by \`${assertion}\` was not awaited. `,
209
113
  "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
@@ -261,9 +165,7 @@ const SnapshotPlugin = (chai, utils) => {
261
165
  return test;
262
166
  }
263
167
  for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
264
- utils.flag(this, "_name", key);
265
- const isNot = utils.flag(this, "negate");
266
- if (isNot) throw new Error(`${key} cannot be used with "not"`);
168
+ if (utils.flag(this, "_name", key), utils.flag(this, "negate")) throw new Error(`${key} cannot be used with "not"`);
267
169
  const expected = utils.flag(this, "object"), test = getTest(key, this);
268
170
  if (typeof properties === "string" && typeof message === "undefined") message = properties, properties = void 0;
269
171
  const errorMessage = utils.flag(this, "message");
@@ -277,9 +179,7 @@ const SnapshotPlugin = (chai, utils) => {
277
179
  });
278
180
  });
279
181
  utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
280
- utils.flag(this, "_name", "toMatchFileSnapshot");
281
- const isNot = utils.flag(this, "negate");
282
- if (isNot) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
182
+ if (utils.flag(this, "_name", "toMatchFileSnapshot"), utils.flag(this, "negate")) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
283
183
  const error = /* @__PURE__ */ new Error("resolves"), expected = utils.flag(this, "object"), test = getTest("toMatchFileSnapshot", this), errorMessage = utils.flag(this, "message"), promise = getSnapshotClient().assertRaw({
284
184
  received: expected,
285
185
  message,
@@ -290,11 +190,9 @@ const SnapshotPlugin = (chai, utils) => {
290
190
  });
291
191
  return recordAsyncExpect(test, promise, createAssertionMessage(utils, this), error);
292
192
  }), utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
293
- utils.flag(this, "_name", "toMatchInlineSnapshot");
294
- const isNot = utils.flag(this, "negate");
295
- if (isNot) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
296
- const test = getTest("toMatchInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
297
- if (isInsideEach) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
193
+ if (utils.flag(this, "_name", "toMatchInlineSnapshot"), utils.flag(this, "negate")) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
194
+ const test = getTest("toMatchInlineSnapshot", this);
195
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
298
196
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error");
299
197
  if (typeof properties === "string") message = inlineSnapshot, inlineSnapshot = properties, properties = void 0;
300
198
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
@@ -310,9 +208,7 @@ const SnapshotPlugin = (chai, utils) => {
310
208
  ...getTestNames(test)
311
209
  });
312
210
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
313
- utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
314
- const isNot = utils.flag(this, "negate");
315
- if (isNot) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
211
+ if (utils.flag(this, "_name", "toThrowErrorMatchingSnapshot"), utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
316
212
  const expected = utils.flag(this, "object"), test = getTest("toThrowErrorMatchingSnapshot", this), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
317
213
  getSnapshotClient().assert({
318
214
  received: getError(expected, promise),
@@ -321,10 +217,9 @@ const SnapshotPlugin = (chai, utils) => {
321
217
  ...getTestNames(test)
322
218
  });
323
219
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
324
- const isNot = utils.flag(this, "negate");
325
- if (isNot) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
326
- const test = getTest("toThrowErrorMatchingInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
327
- if (isInsideEach) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
220
+ if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
221
+ const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
222
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
328
223
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error"), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
329
224
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
330
225
  getSnapshotClient().assert({
@@ -339,16 +234,16 @@ const SnapshotPlugin = (chai, utils) => {
339
234
  }), utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
340
235
  };
341
236
 
342
- chai$1.use(JestExtend), chai$1.use(JestChaiExpect), chai$1.use(Subset), chai$1.use(SnapshotPlugin), chai$1.use(JestAsymmetricMatchers);
237
+ chai.use(JestExtend), chai.use(JestChaiExpect), chai.use(SnapshotPlugin), chai.use(JestAsymmetricMatchers);
343
238
 
344
239
  function createExpect(test) {
345
240
  const expect = ((value, message) => {
346
241
  const { assertionCalls } = getState(expect);
347
242
  setState({ assertionCalls: assertionCalls + 1 }, expect);
348
- const assert = chai$1.expect(value, message), _test = test || getCurrentTest();
243
+ const assert = chai.expect(value, message), _test = test || getCurrentTest();
349
244
  return _test ? assert.withTest(_test) : assert;
350
245
  });
351
- Object.assign(expect, chai$1.expect), Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]), expect.getState = () => getState(expect), expect.setState = (state) => setState(state, expect);
246
+ Object.assign(expect, chai.expect), Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]), expect.getState = () => getState(expect), expect.setState = (state) => setState(state, expect);
352
247
  // @ts-expect-error global is not typed
353
248
  const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
354
249
  setState({
@@ -362,11 +257,11 @@ function createExpect(test) {
362
257
  return getWorkerState().filepath;
363
258
  },
364
259
  currentTestName: test ? getTestName(test) : globalState.currentTestName
365
- }, expect), expect.extend = (matchers) => chai$1.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
260
+ }, expect), expect.assert = chai.assert, expect.extend = (matchers) => chai.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
366
261
  // @ts-expect-error private soft access
367
262
  return expect(...args).withContext({ soft: true });
368
263
  }, expect.poll = createExpectPoll(expect), expect.unreachable = (message) => {
369
- chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
264
+ chai.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
370
265
  };
371
266
  function assertions(expected) {
372
267
  const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
@@ -384,7 +279,7 @@ function createExpect(test) {
384
279
  isExpectingAssertionsError: error
385
280
  });
386
281
  }
387
- return chai$1.util.addMethod(expect, "assertions", assertions), chai$1.util.addMethod(expect, "hasAssertions", hasAssertions), expect.extend(customMatchers), expect;
282
+ return chai.util.addMethod(expect, "assertions", assertions), chai.util.addMethod(expect, "hasAssertions", hasAssertions), expect.extend(customMatchers), expect;
388
283
  }
389
284
  const globalExpect = createExpect();
390
285
  Object.defineProperty(globalThis, GLOBAL_EXPECT, {
@@ -392,16 +287,15 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
392
287
  writable: true,
393
288
  configurable: true
394
289
  });
395
- const assert = chai$1.assert;
396
- const should = chai$1.should;
290
+ const assert = chai.assert;
291
+ const should = chai.should;
397
292
 
398
293
  /**
399
294
  * Gives access to injected context provided from the main thread.
400
295
  * This usually returns a value provided by `globalSetup` or an external library.
401
296
  */
402
297
  function inject(key) {
403
- const workerState = getWorkerState();
404
- return workerState.providedContext[key];
298
+ return getWorkerState().providedContext[key];
405
299
  }
406
300
 
407
301
  var fakeTimersSrc = {};
@@ -3503,9 +3397,9 @@ class FakeTimers {
3503
3397
  // | _fakingTime | _fakingDate |
3504
3398
  // +-------------+-------------+
3505
3399
  // | false | falsy | initial
3506
- // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3400
+ // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3507
3401
  // | true | falsy | vi.useFakeTimers called first
3508
- // | true | truthy | unreachable
3402
+ // | true | truthy | unreachable
3509
3403
  _fakingTime;
3510
3404
  _fakingDate;
3511
3405
  _fakeTimers;
@@ -3561,17 +3455,17 @@ class FakeTimers {
3561
3455
  if (this._fakingTime) this._clock.uninstall(), this._fakingTime = false;
3562
3456
  }
3563
3457
  useFakeTimers() {
3564
- if (this._fakingDate) throw new Error("\"setSystemTime\" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.");
3565
- if (!this._fakingTime) {
3566
- const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3567
- if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
3568
- this._clock = this._fakeTimers.install({
3569
- now: Date.now(),
3570
- ...this._userConfig,
3571
- toFake: this._userConfig?.toFake || toFake,
3572
- ignoreMissingTimers: true
3573
- }), this._fakingTime = true;
3574
- }
3458
+ const fakeDate = this._fakingDate || Date.now();
3459
+ if (this._fakingDate) resetDate(), this._fakingDate = null;
3460
+ if (this._fakingTime) this._clock.uninstall();
3461
+ const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3462
+ if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
3463
+ this._clock = this._fakeTimers.install({
3464
+ now: fakeDate,
3465
+ ...this._userConfig,
3466
+ toFake: this._userConfig?.toFake || toFake,
3467
+ ignoreMissingTimers: true
3468
+ }), this._fakingTime = true;
3575
3469
  }
3576
3470
  reset() {
3577
3471
  if (this._checkFakeTimers()) {
@@ -3600,7 +3494,7 @@ class FakeTimers {
3600
3494
  return this._fakingTime;
3601
3495
  }
3602
3496
  _checkFakeTimers() {
3603
- if (!this._fakingTime) throw new Error("Timers are not mocked. Try calling \"vi.useFakeTimers()\" first.");
3497
+ if (!this._fakingTime) throw new Error("A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.");
3604
3498
  return this._fakingTime;
3605
3499
  }
3606
3500
  }
@@ -3772,13 +3666,16 @@ function createVitest() {
3772
3666
  },
3773
3667
  doUnmock(path) {
3774
3668
  if (typeof path !== "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
3775
- _mocker().queueUnmock(path, getImporter("doUnmock"));
3669
+ const importer = getImporter("doUnmock");
3670
+ _mocker().queueUnmock(path, importer);
3776
3671
  },
3777
3672
  async importActual(path) {
3778
- return _mocker().importActual(path, getImporter("importActual"), _mocker().getMockContext().callstack);
3673
+ const importer = getImporter("importActual");
3674
+ return _mocker().importActual(path, importer, _mocker().getMockContext().callstack);
3779
3675
  },
3780
3676
  async importMock(path) {
3781
- return _mocker().importMock(path, getImporter("importMock"));
3677
+ const importer = getImporter("importMock");
3678
+ return _mocker().importMock(path, importer);
3782
3679
  },
3783
3680
  mockObject(value, options) {
3784
3681
  return _mocker().mockObject({ value }, void 0, options?.spy ? "autospy" : "automock").value;
@@ -3853,10 +3750,10 @@ function _mocker() {
3853
3750
  } });
3854
3751
  }
3855
3752
  function getImporter(name) {
3856
- const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 }), stackArray = stackTrace.split("\n"), importerStackIndex = stackArray.findIndex((stack) => {
3753
+ const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n"), importerStackIndex = stackArray.findLastIndex((stack) => {
3857
3754
  return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
3858
- }), stack = parseSingleStack(stackArray[importerStackIndex + 1]);
3859
- return stack?.file || "";
3755
+ });
3756
+ return parseSingleStack(stackArray[importerStackIndex + 1])?.file || "";
3860
3757
  }
3861
3758
 
3862
3759
  export { getSnapshotClient as a, assert as b, createExpect as c, vitest as d, globalExpect as g, inject as i, should as s, vi as v };
@@ -2,15 +2,16 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
2
2
  import vm, { isContext, runInContext } from 'node:vm';
3
3
  import { dirname, basename, extname, normalize, resolve } from 'pathe';
4
4
  import { distDir } from '../path.js';
5
- import { createCustomConsole } from './console.7h5kHUIf.js';
5
+ import { createCustomConsole } from './console.CTJL2nuH.js';
6
6
  import fs from 'node:fs';
7
7
  import { createRequire, Module, isBuiltin } from 'node:module';
8
- import { CSS_LANGS_RE, KNOWN_ASSET_RE, toArray, isBareImport } from '@vitest/utils';
9
- import { f as findNearestPackageData } from './resolver.Bx6lE0iq.js';
8
+ import { toArray, isBareImport } from '@vitest/utils/helpers';
9
+ import { findNearestPackageData } from '@vitest/utils/resolver';
10
10
  import { dirname as dirname$1 } from 'node:path';
11
+ import { CSS_LANGS_RE, KNOWN_ASSET_RE } from '@vitest/utils/constants';
11
12
  import { getDefaultRequestStubs } from '../module-evaluator.js';
12
- import { s as startVitestModuleRunner, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.BDRvKSdz.js';
13
- import { p as provideWorkerState } from './utils.D2R2NiOH.js';
13
+ import { s as startVitestModuleRunner, c as createNodeImportMeta, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.iF1E9Bt4.js';
14
+ import { p as provideWorkerState } from './utils.CG9h5ccR.js';
14
15
 
15
16
  function interopCommonJsModule(interopDefault, mod) {
16
17
  if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
@@ -35,8 +36,7 @@ function interopCommonJsModule(interopDefault, mod) {
35
36
  };
36
37
  }
37
38
  function isPrimitive(obj) {
38
- const isObject = obj != null && (typeof obj === "object" || typeof obj === "function");
39
- return !isObject;
39
+ return !(obj != null && (typeof obj === "object" || typeof obj === "function"));
40
40
  }
41
41
  const SyntheticModule = vm.SyntheticModule;
42
42
  const SourceTextModule = vm.SourceTextModule;
@@ -105,8 +105,7 @@ class CommonjsExecutor {
105
105
  }
106
106
  // exposed for external use, Node.js does the opposite
107
107
  static _load = (request, parent, _isMain) => {
108
- const require = Module$1.createRequire(parent?.filename ?? request);
109
- return require(request);
108
+ return Module$1.createRequire(parent?.filename ?? request)(request);
110
109
  };
111
110
  static wrap = (script) => {
112
111
  return Module$1.wrapper[0] + script + Module$1.wrapper[1];
@@ -156,8 +155,8 @@ class CommonjsExecutor {
156
155
  };
157
156
  createRequire = (filename) => {
158
157
  const _require = createRequire(filename), require = ((id) => {
159
- const resolved = _require.resolve(id), ext = extname(resolved);
160
- if (ext === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
158
+ const resolved = _require.resolve(id);
159
+ if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
161
160
  const module = new this.Module(resolved);
162
161
  return this.loadCommonJSModule(module, resolved);
163
162
  });
@@ -187,8 +186,8 @@ class CommonjsExecutor {
187
186
  loadCommonJSModule(module, filename) {
188
187
  const cached = this.requireCache.get(filename);
189
188
  if (cached) return cached.exports;
190
- const extension = this.findLongestRegisteredExtension(filename), loader = this.extensions[extension] || this.extensions[".js"];
191
- return loader(module, filename), module.exports;
189
+ const extension = this.findLongestRegisteredExtension(filename);
190
+ return (this.extensions[extension] || this.extensions[".js"])(module, filename), module.exports;
192
191
  }
193
192
  findLongestRegisteredExtension(filename) {
194
193
  const name = basename(filename);
@@ -259,8 +258,7 @@ class CommonjsExecutor {
259
258
  // return namedExports
260
259
  // }
261
260
  require(identifier) {
262
- const ext = extname(identifier);
263
- if (ext === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
261
+ if (extname(identifier) === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
264
262
  const module = new this.Module(identifier);
265
263
  return this.loadCommonJSModule(module, identifier);
266
264
  }
@@ -345,7 +343,8 @@ class EsmExecutor {
345
343
  if (cached) return cached;
346
344
  const wasmModule = await WebAssembly.compile(source), exports = WebAssembly.Module.exports(wasmModule), imports = WebAssembly.Module.imports(wasmModule), moduleLookup = {};
347
345
  for (const { module } of imports) if (moduleLookup[module] === void 0) moduleLookup[module] = await this.executor.resolveModule(module, identifier);
348
- const evaluateModule = (module) => this.evaluateModule(module), syntheticModule = new SyntheticModule(exports.map(({ name }) => name), async function() {
346
+ const evaluateModule = (module) => this.evaluateModule(module);
347
+ return new SyntheticModule(exports.map(({ name }) => name), async function() {
349
348
  const importsObject = {};
350
349
  for (const { module, name } of imports) {
351
350
  if (!importsObject[module]) importsObject[module] = {};
@@ -357,7 +356,6 @@ class EsmExecutor {
357
356
  context: this.context,
358
357
  identifier
359
358
  });
360
- return syntheticModule;
361
359
  }
362
360
  cacheModule(identifier, module) {
363
361
  this.moduleCache.set(identifier, module);
@@ -416,9 +414,7 @@ class ViteExecutor {
416
414
  return this.options.context.__vitest_worker__;
417
415
  }
418
416
  async createViteModule(fileUrl) {
419
- if (fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID) return this.createViteClientModule();
420
- const cached = this.esm.resolveCachedModule(fileUrl);
421
- return cached || this.esm.createEsModule(fileUrl, async () => {
417
+ return fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID ? this.createViteClientModule() : this.esm.resolveCachedModule(fileUrl) || this.esm.createEsModule(fileUrl, async () => {
422
418
  try {
423
419
  const result = await this.options.transform(fileUrl);
424
420
  if (result.code) return result.code;
@@ -529,10 +525,7 @@ class ExternalModulesExecutor {
529
525
  // still experimental on NodeJS --experimental-wasm-modules
530
526
  // cf. ESM_FILE_FORMAT(url) in https://nodejs.org/docs/latest-v20.x/api/esm.html#resolution-algorithm
531
527
  type = "wasm";
532
- else {
533
- const pkgData = findNearestPackageData(normalize(pathUrl));
534
- type = pkgData.type === "module" ? "module" : "commonjs";
535
- }
528
+ else type = findNearestPackageData(normalize(pathUrl)).type === "module" ? "module" : "commonjs";
536
529
  return {
537
530
  type,
538
531
  path: pathUrl,
@@ -555,10 +548,7 @@ class ExternalModulesExecutor {
555
548
  case "module": return this.esm.createEsModule(url, () => this.fs.readFileAsync(path));
556
549
  case "commonjs": return this.cjs.getCjsSyntheticModule(path, identifier);
557
550
  case "network": return this.esm.createNetworkModule(url);
558
- default: {
559
- const _deadend = type;
560
- return _deadend;
561
- }
551
+ default: return type;
562
552
  }
563
553
  }
564
554
  get isNetworkSupported() {
@@ -615,7 +605,8 @@ async function runVmTests(method, state) {
615
605
  context,
616
606
  evaluatedModules: state.evaluatedModules,
617
607
  state,
618
- externalModulesExecutor
608
+ externalModulesExecutor,
609
+ createImportMeta: createNodeImportMeta
619
610
  });
620
611
  if (Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
621
612
  value: {
@@ -1,9 +1,45 @@
1
1
  import { CancelReason, File, TestAnnotation, TaskResultPack, TaskEventPack, FileSpecification, Task } from '@vitest/runner';
2
2
  import { FetchFunctionOptions, FetchResult, EvaluatedModules } from 'vite/module-runner';
3
- import { a as SerializedConfig } from './config.d.DacWrqWe.js';
4
- import { F as FetchCachedFileSystemResult, R as ResolveFunctionResult, U as UserConsoleLog, A as AfterSuiteRunMeta, E as Environment } from './environment.d.2fYMoz3o.js';
3
+ import { S as SerializedConfig } from './config.d.u2CUDWwS.js';
4
+ import { E as Environment } from './environment.d.CrsxCzP1.js';
5
5
  import { SnapshotResult } from '@vitest/snapshot';
6
6
 
7
+ interface AfterSuiteRunMeta {
8
+ coverage?: unknown;
9
+ testFiles: string[];
10
+ environment: string;
11
+ projectName?: string;
12
+ }
13
+ interface UserConsoleLog {
14
+ content: string;
15
+ origin?: string;
16
+ browser?: boolean;
17
+ type: "stdout" | "stderr";
18
+ taskId?: string;
19
+ time: number;
20
+ size: number;
21
+ }
22
+ interface ModuleGraphData {
23
+ graph: Record<string, string[]>;
24
+ externalized: string[];
25
+ inlined: string[];
26
+ }
27
+ interface ProvidedContext {}
28
+ interface ResolveFunctionResult {
29
+ id: string;
30
+ file: string;
31
+ url: string;
32
+ }
33
+ interface FetchCachedFileSystemResult {
34
+ cached: true;
35
+ tmp: string;
36
+ id: string;
37
+ file: string | null;
38
+ url: string;
39
+ invalidate: boolean;
40
+ }
41
+ type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
42
+
7
43
  type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
8
44
  type ReturnType<T> = T extends (...args: any) => infer R ? R : never;
9
45
  type PromisifyFn<T> = ReturnType<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>;
@@ -134,14 +170,14 @@ interface ContextTestEnvironment {
134
170
  type TestExecutionMethod = "run" | "collect";
135
171
  interface ContextRPC {
136
172
  pool: string;
137
- worker: string;
138
- workerId: number;
139
173
  config: SerializedConfig;
140
174
  projectName: string;
141
- files: string[] | FileSpecification[];
175
+ files: FileSpecification[];
142
176
  environment: ContextTestEnvironment;
143
177
  providedContext: Record<string, any>;
144
178
  invalidates?: string[];
179
+ /** Exposed to test runner as `VITEST_WORKER_ID`. Value is unique per each isolated worker. */
180
+ workerId: number;
145
181
  }
146
182
  interface WorkerGlobalState {
147
183
  ctx: ContextRPC;
@@ -172,4 +208,4 @@ interface WorkerGlobalState {
172
208
  onFilterStackTrace?: (trace: string) => string;
173
209
  }
174
210
 
175
- export type { BirpcOptions as B, ContextRPC as C, RuntimeRPC as R, TestExecutionMethod as T, WorkerGlobalState as W, BirpcReturn as a, RunnerRPC as b, ContextTestEnvironment as c };
211
+ export type { AfterSuiteRunMeta as A, BirpcOptions as B, ContextRPC as C, LabelColor as L, ModuleGraphData as M, ProvidedContext as P, RuntimeRPC as R, TestExecutionMethod as T, UserConsoleLog as U, WorkerGlobalState as W, BirpcReturn as a, RunnerRPC as b, ContextTestEnvironment as c, ResolveFunctionResult as d };
package/dist/cli.js CHANGED
@@ -1,27 +1,28 @@
1
- import { c as createCLI } from './chunks/cac.Dt7e1TIu.js';
2
- import '@vitest/utils';
1
+ import { c as createCLI } from './chunks/cac.DrF4Gm0S.js';
2
+ import '@vitest/utils/helpers';
3
3
  import 'events';
4
4
  import 'pathe';
5
5
  import 'tinyrainbow';
6
6
  import './chunks/constants.D_Q9UYh-.js';
7
- import './chunks/index.BIP7prJq.js';
7
+ import './chunks/index.CcRZ6fUh.js';
8
8
  import 'node:fs';
9
9
  import 'node:fs/promises';
10
- import './chunks/typechecker.DB-fIMaH.js';
11
- import 'node:os';
12
10
  import 'node:perf_hooks';
13
- import '@vitest/utils/source-map';
14
- import 'tinyexec';
15
- import './path.js';
16
- import 'node:path';
17
- import 'node:url';
18
11
  import '@vitest/runner/utils';
19
- import 'vite';
12
+ import '@vitest/utils/source-map';
20
13
  import './chunks/env.D4Lgay0q.js';
21
14
  import 'std-env';
22
15
  import 'node:util';
23
16
  import 'node:console';
24
17
  import 'node:stream';
18
+ import '@vitest/utils/display';
19
+ import 'node:os';
20
+ import 'tinyexec';
21
+ import './path.js';
22
+ import 'node:path';
23
+ import 'node:url';
24
+ import 'vite';
25
+ import '@vitest/utils/offset';
25
26
  import 'node:module';
26
27
 
27
28
  createCLI().parse();
package/dist/config.cjs CHANGED
@@ -43,7 +43,6 @@ const configDefaults = Object.freeze({
43
43
  watch: !stdEnv.isCI && process.stdin.isTTY,
44
44
  globals: false,
45
45
  environment: "node",
46
- pool: "forks",
47
46
  clearMocks: false,
48
47
  restoreMocks: false,
49
48
  mockReset: false,