vitest 4.0.0-beta.10 → 4.0.0-beta.12

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 (69) hide show
  1. package/LICENSE.md +85 -101
  2. package/dist/browser.d.ts +10 -6
  3. package/dist/browser.js +8 -5
  4. package/dist/chunks/{benchmark.CJUa-Hsa.js → benchmark.DHKMYAts.js} +2 -2
  5. package/dist/chunks/{browser.d.yFAklsD1.d.ts → browser.d.D9YV3JvA.d.ts} +1 -1
  6. package/dist/chunks/{cac.DCxo_nSu.js → cac.r1gel_VZ.js} +18 -11
  7. package/dist/chunks/{cli-api.BJJXh9BV.js → cli-api.CpywZzJV.js} +153 -176
  8. package/dist/chunks/{config.d.B_LthbQq.d.ts → config.d.DGazh2r6.d.ts} +3 -1
  9. package/dist/chunks/{console.7h5kHUIf.js → console.CTJL2nuH.js} +4 -6
  10. package/dist/chunks/{coverage.BCU-r2QL.js → coverage.CiB0fs_7.js} +57 -79
  11. package/dist/chunks/{creator.08Gi-vCA.js → creator.DfXDsUyL.js} +6 -8
  12. package/dist/chunks/{global.d.BK3X7FW1.d.ts → global.d.BcFPD2LN.d.ts} +0 -13
  13. package/dist/chunks/{globals.DG-S3xFe.js → globals.DC4ntO86.js} +8 -6
  14. package/dist/chunks/{index.DIWhzsUh.js → index.Bt-upxGS.js} +6 -12
  15. package/dist/chunks/{index.BIP7prJq.js → index.CHrBLuEH.js} +94 -103
  16. package/dist/chunks/{index.X0nbfr6-.js → index.Dc3xnDvT.js} +48 -289
  17. package/dist/chunks/{index.CMfqw92x.js → index.Dnl38iQ_.js} +2 -2
  18. package/dist/chunks/{index.BjKEiSn0.js → index.uLUz1RDt.js} +3 -3
  19. package/dist/chunks/{inspector.CvQD-Nie.js → inspector.Br76Q2Mb.js} +1 -4
  20. package/dist/chunks/{moduleRunner.d.D9nBoC4p.d.ts → moduleRunner.d.CeYc7nZ0.d.ts} +1 -1
  21. package/dist/chunks/{node.CyipiPvJ.js → node.BwAWWjHZ.js} +3 -4
  22. package/dist/chunks/{plugin.d.BMVSnsGV.d.ts → plugin.d.XreRXLXS.d.ts} +1 -1
  23. package/dist/chunks/{reporters.d.BUWjmRYq.d.ts → reporters.d.CJVTaaWb.d.ts} +54 -13
  24. package/dist/chunks/{resolveSnapshotEnvironment.Bkht6Yor.js → resolveSnapshotEnvironment.BsJpmVZR.js} +7 -8
  25. package/dist/chunks/{rpc.BKr6mtxz.js → rpc.cD77ENhU.js} +13 -14
  26. package/dist/chunks/{setup-common.uiMcU3cv.js → setup-common.BewgbkTd.js} +6 -6
  27. package/dist/chunks/{startModuleRunner.p67gbNo9.js → startModuleRunner.DPBo3mme.js} +65 -56
  28. package/dist/chunks/{test.BiqSKISg.js → test.CTuWuHYH.js} +7 -7
  29. package/dist/chunks/{typechecker.DB-fIMaH.js → typechecker.BfOQ86_a.js} +624 -14
  30. package/dist/chunks/{utils.D2R2NiOH.js → utils.CG9h5ccR.js} +2 -5
  31. package/dist/chunks/{vi.ZPgvtBao.js → vi.B2--mG9U.js} +38 -145
  32. package/dist/{worker.js → chunks/worker.DVTUM2IW.js} +71 -42
  33. package/dist/chunks/{worker.d.BDsXGkwh.d.ts → worker.d.buwuBpBt.d.ts} +2 -77
  34. package/dist/cli.js +7 -5
  35. package/dist/config.d.ts +6 -6
  36. package/dist/coverage.d.ts +5 -5
  37. package/dist/coverage.js +4 -5
  38. package/dist/environments.js +1 -1
  39. package/dist/index.d.ts +8 -8
  40. package/dist/index.js +8 -6
  41. package/dist/module-evaluator.d.ts +3 -3
  42. package/dist/module-evaluator.js +11 -13
  43. package/dist/module-runner.js +5 -5
  44. package/dist/node.d.ts +14 -11
  45. package/dist/node.js +18 -14
  46. package/dist/reporters.d.ts +5 -5
  47. package/dist/reporters.js +7 -5
  48. package/dist/runners.d.ts +1 -1
  49. package/dist/runners.js +9 -7
  50. package/dist/snapshot.js +3 -3
  51. package/dist/suite.js +4 -3
  52. package/dist/{chunks/base.Cjha6usc.js → worker-base.js} +104 -32
  53. package/dist/{chunks/vm.Ca0Y0W5f.js → worker-vm.js} +81 -31
  54. package/dist/workers/runVmTests.js +14 -11
  55. package/package.json +26 -26
  56. package/browser.d.ts +0 -1
  57. package/dist/chunks/moduleTransport.I-bgQy0S.js +0 -19
  58. package/dist/chunks/resolver.Bx6lE0iq.js +0 -119
  59. package/dist/chunks/utils.C2YI6McM.js +0 -52
  60. package/dist/chunks/worker.d.BNcX_2mH.d.ts +0 -8
  61. package/dist/workers/forks.js +0 -67
  62. package/dist/workers/threads.js +0 -55
  63. package/dist/workers/vmForks.js +0 -48
  64. package/dist/workers/vmThreads.js +0 -38
  65. package/dist/workers.d.ts +0 -38
  66. package/dist/workers.js +0 -48
  67. package/execute.d.ts +0 -1
  68. package/utils.d.ts +0 -1
  69. package/workers.d.ts +0 -1
@@ -1,13 +1,10 @@
1
- import { getSafeTimers } from '@vitest/utils';
1
+ import { getSafeTimers } from '@vitest/utils/timers';
2
2
 
3
3
  const NAME_WORKER_STATE = "__vitest_worker__";
4
4
  function getWorkerState() {
5
5
  // @ts-expect-error untyped global
6
6
  const workerState = globalThis[NAME_WORKER_STATE];
7
- if (!workerState) {
8
- const errorMsg = "Vitest failed to access its internal state.\n\nOne of the following is possible:\n- \"vitest\" is imported directly without running \"vitest\" command\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)\n- \"vitest\" is imported inside Vite / Vitest config file\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n";
9
- throw new Error(errorMsg);
10
- }
7
+ if (!workerState) throw new Error("Vitest failed to access its internal state.\n\nOne of the following is possible:\n- \"vitest\" is imported directly without running \"vitest\" command\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)\n- \"vitest\" is imported inside Vite / Vitest config file\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n");
11
8
  return workerState;
12
9
  }
13
10
  function provideWorkerState(context, state) {
@@ -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,15 +41,15 @@ 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);
52
+ clearTimeout(intervalId), chai.util.flag(assertion, "_isLastPollAttempt", true);
51
53
  const rejectWithCause = (error) => {
52
54
  if (error.cause == null) error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.");
53
55
  reject(copyStackTrace$1(error, STACK_TRACE_ERROR));
@@ -58,7 +60,7 @@ function createExpectPoll(expect) {
58
60
  let awaited = false;
59
61
  test.onFinished ??= [], test.onFinished.push(() => {
60
62
  if (!awaited) {
61
- 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`);
62
64
  throw copyStackTrace$1(error, STACK_TRACE_ERROR);
63
65
  }
64
66
  });
@@ -87,108 +89,9 @@ function copyStackTrace$1(target, source) {
87
89
  return target;
88
90
  }
89
91
 
90
- function commonjsRequire(path) {
91
- 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.');
92
- }
93
-
94
- var chaiSubset$1 = {exports: {}};
95
-
96
- var chaiSubset = chaiSubset$1.exports;
97
-
98
- var hasRequiredChaiSubset;
99
-
100
- function requireChaiSubset () {
101
- if (hasRequiredChaiSubset) return chaiSubset$1.exports;
102
- hasRequiredChaiSubset = 1;
103
- (function (module, exports) {
104
- (function() {
105
- (function(chaiSubset) {
106
- if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
107
- return module.exports = chaiSubset;
108
- } else {
109
- return chai.use(chaiSubset);
110
- }
111
- })(function(chai, utils) {
112
- var Assertion = chai.Assertion;
113
- var assertionPrototype = Assertion.prototype;
114
-
115
- Assertion.addMethod('containSubset', function (expected) {
116
- var actual = utils.flag(this, 'object');
117
- var showDiff = chai.config.showDiff;
118
-
119
- assertionPrototype.assert.call(this,
120
- compare(expected, actual),
121
- 'expected #{act} to contain subset #{exp}',
122
- 'expected #{act} to not contain subset #{exp}',
123
- expected,
124
- actual,
125
- showDiff
126
- );
127
- });
128
-
129
- chai.assert.containSubset = function(val, exp, msg) {
130
- new chai.Assertion(val, msg).to.be.containSubset(exp);
131
- };
132
-
133
- function compare(expected, actual) {
134
- if (expected === actual) {
135
- return true;
136
- }
137
- if (typeof(actual) !== typeof(expected)) {
138
- return false;
139
- }
140
- if (typeof(expected) !== 'object' || expected === null) {
141
- return expected === actual;
142
- }
143
- if (!!expected && !actual) {
144
- return false;
145
- }
146
-
147
- if (Array.isArray(expected)) {
148
- if (typeof(actual.length) !== 'number') {
149
- return false;
150
- }
151
- var aa = Array.prototype.slice.call(actual);
152
- return expected.every(function (exp) {
153
- return aa.some(function (act) {
154
- return compare(exp, act);
155
- });
156
- });
157
- }
158
-
159
- if (expected instanceof Date) {
160
- if (actual instanceof Date) {
161
- return expected.getTime() === actual.getTime();
162
- } else {
163
- return false;
164
- }
165
- }
166
-
167
- return Object.keys(expected).every(function (key) {
168
- var eo = expected[key];
169
- var ao = actual[key];
170
- if (typeof(eo) === 'object' && eo !== null && ao !== null) {
171
- return compare(eo, ao);
172
- }
173
- if (typeof(eo) === 'function') {
174
- return eo(ao);
175
- }
176
- return ao === eo;
177
- });
178
- }
179
- });
180
-
181
- }).call(chaiSubset);
182
- } (chaiSubset$1));
183
- return chaiSubset$1.exports;
184
- }
185
-
186
- var chaiSubsetExports = requireChaiSubset();
187
- var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
188
-
189
92
  function createAssertionMessage(util, assertion, hasArgs) {
190
- const not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${"expected" })`, promiseName = util.flag(assertion, "promise"), promise = promiseName ? `.${promiseName}` : "";
191
- 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}`;
192
95
  }
193
96
  function recordAsyncExpect(_test, promise, assertion, error) {
194
97
  const test = _test;
@@ -204,7 +107,7 @@ function recordAsyncExpect(_test, promise, assertion, error) {
204
107
  let resolved = false;
205
108
  return test.onFinished ??= [], test.onFinished.push(() => {
206
109
  if (!resolved) {
207
- const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""), stack = processor(error.stack);
110
+ const stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
208
111
  console.warn([
209
112
  `Promise returned by \`${assertion}\` was not awaited. `,
210
113
  "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
@@ -262,9 +165,7 @@ const SnapshotPlugin = (chai, utils) => {
262
165
  return test;
263
166
  }
264
167
  for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
265
- utils.flag(this, "_name", key);
266
- const isNot = utils.flag(this, "negate");
267
- 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"`);
268
169
  const expected = utils.flag(this, "object"), test = getTest(key, this);
269
170
  if (typeof properties === "string" && typeof message === "undefined") message = properties, properties = void 0;
270
171
  const errorMessage = utils.flag(this, "message");
@@ -278,9 +179,7 @@ const SnapshotPlugin = (chai, utils) => {
278
179
  });
279
180
  });
280
181
  utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
281
- utils.flag(this, "_name", "toMatchFileSnapshot");
282
- const isNot = utils.flag(this, "negate");
283
- 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\"");
284
183
  const error = /* @__PURE__ */ new Error("resolves"), expected = utils.flag(this, "object"), test = getTest("toMatchFileSnapshot", this), errorMessage = utils.flag(this, "message"), promise = getSnapshotClient().assertRaw({
285
184
  received: expected,
286
185
  message,
@@ -291,11 +190,9 @@ const SnapshotPlugin = (chai, utils) => {
291
190
  });
292
191
  return recordAsyncExpect(test, promise, createAssertionMessage(utils, this), error);
293
192
  }), utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
294
- utils.flag(this, "_name", "toMatchInlineSnapshot");
295
- const isNot = utils.flag(this, "negate");
296
- if (isNot) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
297
- const test = getTest("toMatchInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
298
- 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");
299
196
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error");
300
197
  if (typeof properties === "string") message = inlineSnapshot, inlineSnapshot = properties, properties = void 0;
301
198
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
@@ -311,9 +208,7 @@ const SnapshotPlugin = (chai, utils) => {
311
208
  ...getTestNames(test)
312
209
  });
313
210
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
314
- utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
315
- const isNot = utils.flag(this, "negate");
316
- 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\"");
317
212
  const expected = utils.flag(this, "object"), test = getTest("toThrowErrorMatchingSnapshot", this), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
318
213
  getSnapshotClient().assert({
319
214
  received: getError(expected, promise),
@@ -322,10 +217,9 @@ const SnapshotPlugin = (chai, utils) => {
322
217
  ...getTestNames(test)
323
218
  });
324
219
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
325
- const isNot = utils.flag(this, "negate");
326
- if (isNot) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
327
- const test = getTest("toThrowErrorMatchingInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
328
- 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");
329
223
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error"), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
330
224
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
331
225
  getSnapshotClient().assert({
@@ -340,16 +234,16 @@ const SnapshotPlugin = (chai, utils) => {
340
234
  }), utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
341
235
  };
342
236
 
343
- 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);
344
238
 
345
239
  function createExpect(test) {
346
240
  const expect = ((value, message) => {
347
241
  const { assertionCalls } = getState(expect);
348
242
  setState({ assertionCalls: assertionCalls + 1 }, expect);
349
- const assert = chai$1.expect(value, message), _test = test || getCurrentTest();
243
+ const assert = chai.expect(value, message), _test = test || getCurrentTest();
350
244
  return _test ? assert.withTest(_test) : assert;
351
245
  });
352
- 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);
353
247
  // @ts-expect-error global is not typed
354
248
  const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
355
249
  setState({
@@ -363,11 +257,11 @@ function createExpect(test) {
363
257
  return getWorkerState().filepath;
364
258
  },
365
259
  currentTestName: test ? getTestName(test) : globalState.currentTestName
366
- }, expect), expect.extend = (matchers) => chai$1.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
260
+ }, expect), expect.extend = (matchers) => chai.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
367
261
  // @ts-expect-error private soft access
368
262
  return expect(...args).withContext({ soft: true });
369
263
  }, expect.poll = createExpectPoll(expect), expect.unreachable = (message) => {
370
- chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
264
+ chai.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
371
265
  };
372
266
  function assertions(expected) {
373
267
  const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
@@ -385,7 +279,7 @@ function createExpect(test) {
385
279
  isExpectingAssertionsError: error
386
280
  });
387
281
  }
388
- 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;
389
283
  }
390
284
  const globalExpect = createExpect();
391
285
  Object.defineProperty(globalThis, GLOBAL_EXPECT, {
@@ -393,16 +287,15 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
393
287
  writable: true,
394
288
  configurable: true
395
289
  });
396
- const assert = chai$1.assert;
397
- const should = chai$1.should;
290
+ const assert = chai.assert;
291
+ const should = chai.should;
398
292
 
399
293
  /**
400
294
  * Gives access to injected context provided from the main thread.
401
295
  * This usually returns a value provided by `globalSetup` or an external library.
402
296
  */
403
297
  function inject(key) {
404
- const workerState = getWorkerState();
405
- return workerState.providedContext[key];
298
+ return getWorkerState().providedContext[key];
406
299
  }
407
300
 
408
301
  var fakeTimersSrc = {};
@@ -3857,10 +3750,10 @@ function _mocker() {
3857
3750
  } });
3858
3751
  }
3859
3752
  function getImporter(name) {
3860
- const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 }), stackArray = stackTrace.split("\n"), importerStackIndex = stackArray.findLastIndex((stack) => {
3753
+ const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n"), importerStackIndex = stackArray.findLastIndex((stack) => {
3861
3754
  return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
3862
- }), stack = parseSingleStack(stackArray[importerStackIndex + 1]);
3863
- return stack?.file || "";
3755
+ });
3756
+ return parseSingleStack(stackArray[importerStackIndex + 1])?.file || "";
3864
3757
  }
3865
3758
 
3866
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 };
@@ -1,18 +1,14 @@
1
- import { pathToFileURL } from 'node:url';
2
1
  import { createStackString, parseStacktrace } from '@vitest/utils/source-map';
3
2
  import { ModuleRunner, EvaluatedModules } from 'vite/module-runner';
4
3
  import { readFileSync } from 'node:fs';
5
4
  import { isBuiltin } from 'node:module';
5
+ import { pathToFileURL } from 'node:url';
6
6
  import { resolve } from 'pathe';
7
- import { V as VitestTransport } from './chunks/moduleTransport.I-bgQy0S.js';
8
- import { e as environments } from './chunks/index.DIWhzsUh.js';
9
- import { s as setupInspect } from './chunks/inspector.CvQD-Nie.js';
10
- import { c as createRuntimeRpc, a as rpcDone } from './chunks/rpc.BKr6mtxz.js';
11
- import { i as isChildProcess } from './chunks/utils.D2R2NiOH.js';
12
- import { d as disposeInternalListeners } from './chunks/utils.C2YI6McM.js';
13
- import 'node:console';
14
- import '@vitest/utils';
15
- import './chunks/index.Bgo3tNWt.js';
7
+ import { b as VitestTransport } from './startModuleRunner.DPBo3mme.js';
8
+ import { e as environments } from './index.Bt-upxGS.js';
9
+ import { s as setupInspect } from './inspector.Br76Q2Mb.js';
10
+ import { c as createRuntimeRpc, a as rpcDone } from './rpc.cD77ENhU.js';
11
+ import { i as isChildProcess } from './utils.CG9h5ccR.js';
16
12
 
17
13
  function isBuiltinEnvironment(env) {
18
14
  return env in environments;
@@ -28,13 +24,10 @@ async function createEnvironmentLoader(root, rpc) {
28
24
  transport: new VitestTransport({
29
25
  async fetchModule(id, importer, options) {
30
26
  const result = await rpc.fetch(id, importer, "__vitest__", options);
31
- if ("cached" in result) {
32
- const code = readFileSync(result.tmp, "utf-8");
33
- return {
34
- code,
35
- ...result
36
- };
37
- }
27
+ if ("cached" in result) return {
28
+ code: readFileSync(result.tmp, "utf-8"),
29
+ ...result
30
+ };
38
31
  if (isWindows && "externalize" in result)
39
32
  // TODO: vitest returns paths for external modules, but Vite returns file://
40
33
  // https://github.com/vitejs/vite/pull/20449
@@ -66,26 +59,72 @@ async function loadEnvironment(ctx, rpc) {
66
59
  };
67
60
  }
68
61
 
69
- const listeners = /* @__PURE__ */ new Set();
70
- function addCleanupListener(listener) {
71
- listeners.add(listener);
62
+ const REGEXP_WRAP_PREFIX = "$$vitest:", processSend = process.send?.bind(process), processOn = process.on?.bind(process), processOff = process.off?.bind(process), dispose = [];
63
+ function createThreadsRpcOptions({ port }) {
64
+ return {
65
+ post: (v) => {
66
+ port.postMessage(v);
67
+ },
68
+ on: (fn) => {
69
+ port.addListener("message", fn);
70
+ }
71
+ };
72
72
  }
73
- async function cleanup() {
74
- const promises = [...listeners].map((l) => l());
75
- await Promise.all(promises);
73
+ function disposeInternalListeners() {
74
+ for (const fn of dispose) try {
75
+ fn();
76
+ } catch {}
77
+ dispose.length = 0;
78
+ }
79
+ function createForksRpcOptions(nodeV8) {
80
+ return {
81
+ serialize: nodeV8.serialize,
82
+ deserialize: (v) => nodeV8.deserialize(Buffer.from(v)),
83
+ post(v) {
84
+ processSend(v);
85
+ },
86
+ on(fn) {
87
+ const handler = (message, ...extras) => {
88
+ if (!message?.__tinypool_worker_message__) return fn(message, ...extras);
89
+ };
90
+ processOn("message", handler), dispose.push(() => processOff("message", handler));
91
+ }
92
+ };
93
+ }
94
+ /**
95
+ * Reverts the wrapping done by `utils/config-helpers.ts`'s `wrapSerializableConfig`
96
+ */
97
+ function unwrapSerializableConfig(config) {
98
+ if (config.testNamePattern && typeof config.testNamePattern === "string") {
99
+ const testNamePattern = config.testNamePattern;
100
+ if (testNamePattern.startsWith(REGEXP_WRAP_PREFIX)) config.testNamePattern = parseRegexp(testNamePattern.slice(9));
101
+ }
102
+ if (config.defines && Array.isArray(config.defines.keys) && config.defines.original) {
103
+ const { keys, original } = config.defines, defines = {};
104
+ // Apply all keys from the original. Entries which had undefined value are missing from original now
105
+ for (const key of keys) defines[key] = original[key];
106
+ config.defines = defines;
107
+ }
108
+ return config;
109
+ }
110
+ function parseRegexp(input) {
111
+ // Parse input
112
+ // eslint-disable-next-line regexp/no-misleading-capturing-group
113
+ const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
114
+ // Create the regular expression
115
+ return m ? m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3]) ? new RegExp(input) : new RegExp(m[2], m[3]) : /$^/;
76
116
  }
77
117
 
78
118
  if (isChildProcess()) {
79
- const isProfiling = process.execArgv.some((execArg) => execArg.startsWith("--prof") || execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof") || execArg.startsWith("--diagnostic-dir"));
80
- if (isProfiling)
119
+ if (process.execArgv.some((execArg) => execArg.startsWith("--prof") || execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof") || execArg.startsWith("--diagnostic-dir")))
81
120
  // Work-around for nodejs/node#55094
82
121
  process.on("SIGTERM", () => {
83
122
  process.exit();
84
123
  });
85
124
  }
86
- const resolvingModules = /* @__PURE__ */ new Set();
125
+ const resolvingModules = /* @__PURE__ */ new Set(), globalListeners = /* @__PURE__ */ new Set();
87
126
  // this is what every pool executes when running tests
88
- async function execute(method, ctx) {
127
+ async function execute(method, ctx, worker) {
89
128
  disposeInternalListeners();
90
129
  const prepareStart = performance.now(), cleanups = [setupInspect(ctx)];
91
130
  process.env.VITEST_WORKER_ID = String(ctx.workerId);
@@ -93,11 +132,6 @@ async function execute(method, ctx) {
93
132
  process.env.VITEST_POOL_ID = String(poolId);
94
133
  let environmentLoader;
95
134
  try {
96
- // worker is a filepath or URL to a file that exposes a default export with "getRpcOptions" and "runTests" methods
97
- if (ctx.worker[0] === ".") throw new Error(`Path to the test runner cannot be relative, received "${ctx.worker}"`);
98
- const file = ctx.worker.startsWith("file:") ? ctx.worker : pathToFileURL(ctx.worker).toString(), testRunnerModule = await import(file);
99
- if (!testRunnerModule.default || typeof testRunnerModule.default !== "object") throw new TypeError(`Test worker object should be exposed as a default export. Received "${typeof testRunnerModule.default}"`);
100
- const worker = testRunnerModule.default;
101
135
  if (!worker.getRpcOptions || typeof worker.getRpcOptions !== "function") throw new TypeError(`Test worker should expose "getRpcOptions" method. Received "${typeof worker.getRpcOptions}".`);
102
136
  // RPC is used to communicate between worker (be it a thread worker or child process or a custom implementation) and the main thread
103
137
  const { rpc, onCancel } = createRuntimeRpc(worker.getRpcOptions(ctx));
@@ -122,7 +156,7 @@ async function execute(method, ctx) {
122
156
  prepare: prepareStart
123
157
  },
124
158
  rpc,
125
- onCleanup: (listener) => addCleanupListener(listener),
159
+ onCleanup: (listener) => globalListeners.add(listener),
126
160
  providedContext: ctx.providedContext,
127
161
  onFilterStackTrace(stack) {
128
162
  return createStackString(parseStacktrace(stack));
@@ -135,14 +169,9 @@ async function execute(method, ctx) {
135
169
  await Promise.all(cleanups.map((fn) => fn())), await rpcDone().catch(() => {}), environmentLoader?.close();
136
170
  }
137
171
  }
138
- function run(ctx) {
139
- return execute("run", ctx);
140
- }
141
- function collect(ctx) {
142
- return execute("collect", ctx);
143
- }
144
172
  async function teardown() {
145
- return cleanup();
173
+ const promises = [...globalListeners].map((l) => l());
174
+ await Promise.all(promises);
146
175
  }
147
176
  function createImportMetaEnvProxy() {
148
177
  // packages/vitest/src/node/plugins/index.ts:146
@@ -153,7 +182,7 @@ function createImportMetaEnvProxy() {
153
182
  ];
154
183
  return new Proxy(process.env, {
155
184
  get(_, key) {
156
- return typeof key === "string" ? booleanKeys.includes(key) ? !!process.env[key] : process.env[key] : void 0;
185
+ if (typeof key === "string") return booleanKeys.includes(key) ? !!process.env[key] : process.env[key];
157
186
  },
158
187
  set(_, key, value) {
159
188
  if (typeof key !== "string") return true;
@@ -164,4 +193,4 @@ function createImportMetaEnvProxy() {
164
193
  });
165
194
  }
166
195
 
167
- export { collect, run, teardown };
196
+ export { createThreadsRpcOptions as a, createForksRpcOptions as c, execute as e, teardown as t, unwrapSerializableConfig as u };
@@ -1,86 +1,12 @@
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.B_LthbQq.js';
3
+ import { a as SerializedConfig } from './config.d.DGazh2r6.js';
4
4
  import { F as FetchCachedFileSystemResult, R as ResolveFunctionResult, U as UserConsoleLog, A as AfterSuiteRunMeta, E as Environment } from './environment.d.BsToaxti.js';
5
5
  import { SnapshotResult } from '@vitest/snapshot';
6
6
 
7
7
  type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
8
8
  type ReturnType<T> = T extends (...args: any) => infer R ? R : never;
9
9
  type PromisifyFn<T> = ReturnType<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>;
10
- type BirpcResolver = (name: string, resolved: (...args: unknown[]) => unknown) => ((...args: unknown[]) => unknown) | undefined;
11
- interface ChannelOptions {
12
- /**
13
- * Function to post raw message
14
- */
15
- post: (data: any, ...extras: any[]) => any | Promise<any>;
16
- /**
17
- * Listener to receive raw message
18
- */
19
- on: (fn: (data: any, ...extras: any[]) => void) => any | Promise<any>;
20
- /**
21
- * Clear the listener when `$close` is called
22
- */
23
- off?: (fn: (data: any, ...extras: any[]) => void) => any | Promise<any>;
24
- /**
25
- * Custom function to serialize data
26
- *
27
- * by default it passes the data as-is
28
- */
29
- serialize?: (data: any) => any;
30
- /**
31
- * Custom function to deserialize data
32
- *
33
- * by default it passes the data as-is
34
- */
35
- deserialize?: (data: any) => any;
36
- /**
37
- * Call the methods with the RPC context or the original functions object
38
- */
39
- bind?: 'rpc' | 'functions';
40
- }
41
- interface EventOptions<Remote> {
42
- /**
43
- * Names of remote functions that do not need response.
44
- */
45
- eventNames?: (keyof Remote)[];
46
- /**
47
- * Maximum timeout for waiting for response, in milliseconds.
48
- *
49
- * @default 60_000
50
- */
51
- timeout?: number;
52
- /**
53
- * Custom resolver to resolve function to be called
54
- *
55
- * For advanced use cases only
56
- */
57
- resolver?: BirpcResolver;
58
- /**
59
- * Custom error handler
60
- *
61
- * @deprecated use `onFunctionError` and `onGeneralError` instead
62
- */
63
- onError?: (error: Error, functionName: string, args: any[]) => boolean | void;
64
- /**
65
- * Custom error handler for errors occurred in local functions being called
66
- *
67
- * @returns `true` to prevent the error from being thrown
68
- */
69
- onFunctionError?: (error: Error, functionName: string, args: any[]) => boolean | void;
70
- /**
71
- * Custom error handler for errors occurred during serialization or messsaging
72
- *
73
- * @returns `true` to prevent the error from being thrown
74
- */
75
- onGeneralError?: (error: Error, functionName?: string, args?: any[]) => boolean | void;
76
- /**
77
- * Custom error handler for timeouts
78
- *
79
- * @returns `true` to prevent the error from being thrown
80
- */
81
- onTimeoutError?: (functionName: string, args: any[]) => boolean | void;
82
- }
83
- type BirpcOptions<Remote> = EventOptions<Remote> & ChannelOptions;
84
10
  type BirpcFn<T> = PromisifyFn<T> & {
85
11
  /**
86
12
  * Send event without asking for response
@@ -134,7 +60,6 @@ interface ContextTestEnvironment {
134
60
  type TestExecutionMethod = "run" | "collect";
135
61
  interface ContextRPC {
136
62
  pool: string;
137
- worker: string;
138
63
  workerId: number;
139
64
  config: SerializedConfig;
140
65
  projectName: string;
@@ -172,4 +97,4 @@ interface WorkerGlobalState {
172
97
  onFilterStackTrace?: (trace: string) => string;
173
98
  }
174
99
 
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 };
100
+ export type { BirpcReturn as B, ContextRPC as C, RunnerRPC as R, TestExecutionMethod as T, WorkerGlobalState as W, RuntimeRPC as a, ContextTestEnvironment as b };
package/dist/cli.js CHANGED
@@ -1,27 +1,29 @@
1
- import { c as createCLI } from './chunks/cac.DCxo_nSu.js';
2
- import '@vitest/utils';
1
+ import { c as createCLI } from './chunks/cac.r1gel_VZ.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.CHrBLuEH.js';
8
8
  import 'node:fs';
9
9
  import 'node:fs/promises';
10
- import './chunks/typechecker.DB-fIMaH.js';
10
+ import './chunks/typechecker.BfOQ86_a.js';
11
11
  import 'node:os';
12
12
  import 'node:perf_hooks';
13
- import '@vitest/utils/source-map';
14
13
  import 'tinyexec';
15
14
  import './path.js';
16
15
  import 'node:path';
17
16
  import 'node:url';
18
17
  import '@vitest/runner/utils';
19
18
  import 'vite';
19
+ import '@vitest/utils/source-map';
20
20
  import './chunks/env.D4Lgay0q.js';
21
21
  import 'std-env';
22
22
  import 'node:util';
23
23
  import 'node:console';
24
24
  import 'node:stream';
25
+ import '@vitest/utils/display';
26
+ import '@vitest/utils/offset';
25
27
  import 'node:module';
26
28
 
27
29
  createCLI().parse();