vitest 5.1.0-beta.1 → 5.1.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 (68) hide show
  1. package/dist/browser.d.ts +8 -6
  2. package/dist/browser.js +10 -10
  3. package/dist/chunks/{base.PJyN9N0u.js → base.C2su7_N0.js} +16 -21
  4. package/dist/chunks/{browser.d.D7a15z82.d.ts → browser.d.B-QwH_F6.d.ts} +3 -3
  5. package/dist/chunks/{cac.Ccf5Je_F.js → cac.BK306qhQ.js} +29 -22
  6. package/dist/chunks/{cli-api.DE22LIzq.js → cli-api.D6E8EtSi.js} +990 -166
  7. package/dist/chunks/{config.d.BgktgHfG.d.ts → config.d.BpJq6tRA.d.ts} +43 -2
  8. package/dist/chunks/{console.DrMPSuFo.js → console.VJUxd1rM.js} +3 -3
  9. package/dist/chunks/{coverage.-bm5IxnW.js → coverage.9iqXE2gN.js} +1 -1
  10. package/dist/chunks/{coverage.cTDc4uSS.js → coverage.jGCktcGP.js} +1 -1
  11. package/dist/chunks/{creator.BQ3onxbh.js → creator.CoOCr85O.js} +17 -15
  12. package/dist/chunks/{display.BlTmubjj.js → display.Cj2h2zsY.js} +1 -1
  13. package/dist/chunks/{doctor.CPlMs7-y.js → doctor.SRjZIZuA.js} +2 -2
  14. package/dist/chunks/{environment.d.CbTLsZSj.d.ts → environment.d.rlpAM-ON.d.ts} +1 -1
  15. package/dist/chunks/{globals.TipXUFcZ.js → globals.Mxora3_v.js} +11 -10
  16. package/dist/chunks/{index.BFXLpwll.js → index.C7Nn66Gy.js} +79 -41
  17. package/dist/chunks/{index.DmDMHCg8.js → index.CAmut2NG.js} +25 -1
  18. package/dist/chunks/{index.BXttT2gP.js → index.DNcttN5a.js} +288 -437
  19. package/dist/chunks/{index.B03wg4V0.js → index.Da_szXbS.js} +5 -5
  20. package/dist/chunks/{index.D14IAvnE.js → index.ER9afepi.js} +269 -141
  21. package/dist/chunks/{index.D0heQG4v.js → index.Or9psEGe.js} +1 -1
  22. package/dist/chunks/{init-forks.BL1E3__4.js → init-forks.q4IoGYZe.js} +7 -1
  23. package/dist/chunks/{init-threads.CYXAGzKQ.js → init-threads.Bf1Frg9S.js} +1 -1
  24. package/dist/chunks/{init.DVorxUyL.js → init.dGO4K2C0.js} +17 -9
  25. package/dist/chunks/{inspector.CvyFGlXm.js → inspector.D6o1NPo1.js} +12 -1
  26. package/dist/chunks/{module-dependencies.CwNPkcV4.js → module-dependencies._2Eei3FO.js} +1 -1
  27. package/dist/chunks/{modules.BJuCwlRJ.js → moduleSourceMap.Dp1WduWi.js} +31 -1
  28. package/dist/chunks/{native.cdzHIdmv.js → native.D5q1ylZC.js} +3 -2
  29. package/dist/chunks/{nativeModuleMocker.3uBcOd84.js → nativeModuleMocker.ihb3q7Cg.js} +6 -4
  30. package/dist/chunks/{nativeModuleRunner.xi64Afb2.js → nativeModuleRunner.9xPIMzi7.js} +1 -1
  31. package/dist/chunks/{node.uQulW0ei.js → node.B9mkVmLH.js} +1 -1
  32. package/dist/chunks/{pathe.M-eThtNZ.Ba-7h1rE.js → pathe.M-eThtNZ.zq3TM4NT.js} +1 -1
  33. package/dist/chunks/{plugin.d.olEn8IL9.d.ts → plugin.d.Du7hHZwb.d.ts} +115 -41
  34. package/dist/chunks/{plugins.DPQHVT0p.js → plugins.BPruPOR8.js} +1 -1
  35. package/dist/chunks/rawSnapshot.DvoRLRNr.js +356 -0
  36. package/dist/chunks/{resolver.CtCcxIy1.js → resolver.BzpmeQeT.js} +1 -1
  37. package/dist/chunks/{rpc.BV0XpJ5q.js → rpc.CNYWPa97.js} +3 -19
  38. package/dist/chunks/{rpc.d.DGFP7vWr.d.ts → rpc.d.DHfuwqP0.d.ts} +2 -2
  39. package/dist/chunks/{run.BfrMbGVD.js → run.zBhXlcZQ.js} +118 -51
  40. package/dist/chunks/{setup-common.llxJkJaD.js → setup-common.wwc_NYRJ.js} +3 -3
  41. package/dist/chunks/{source-map.BjWcsIL9.js → source-map.DPHGMWvM.js} +14 -14
  42. package/dist/chunks/{source-map.d.C5A_Tr6V.d.ts → source-map.d.xB6_75fl.d.ts} +2 -1
  43. package/dist/chunks/{spy.DDMXghXv.js → spy.BO0hTE3G.js} +76 -53
  44. package/dist/chunks/{task-utils.d.BUh7ylUT.d.ts → task-utils.d.DgSjIb7r.d.ts} +1 -1
  45. package/dist/chunks/{utils.DSfl_w8V.js → utils.sAsh2ClK.js} +7 -8
  46. package/dist/chunks/{vm.Cwj01UFE.js → vm.agn4qnmT.js} +15 -13
  47. package/dist/chunks/{worker.d.gsA26mmR.d.ts → worker.d.BigfbIsH.d.ts} +3 -3
  48. package/dist/cli.js +2 -2
  49. package/dist/config.d.ts +8 -8
  50. package/dist/index.d.ts +17 -12
  51. package/dist/index.js +11 -10
  52. package/dist/module-evaluator.d.ts +3 -3
  53. package/dist/module-evaluator.js +1 -1
  54. package/dist/node.d.ts +12 -11
  55. package/dist/node.js +23 -19
  56. package/dist/runtime.d.ts +5 -4
  57. package/dist/runtime.js +7 -5
  58. package/dist/spy.js +1 -1
  59. package/dist/task-utils.js +7 -3
  60. package/dist/worker.d.ts +4 -4
  61. package/dist/worker.js +23 -21
  62. package/dist/workers/forks.js +24 -22
  63. package/dist/workers/runVmTests.js +20 -17
  64. package/dist/workers/threads.js +24 -22
  65. package/dist/workers/vmForks.js +16 -15
  66. package/dist/workers/vmThreads.js +16 -15
  67. package/dist/workers/watchdog.js +20 -0
  68. package/package.json +21 -21
@@ -1,370 +1,21 @@
1
- import { b as printDiffOrStringify, d as diff, a as processError, T as TestSyntaxError, g as getCurrentTest, c as createTaskCollector, e as getCurrentSuite, f as createChainable, h as getHooks, i as getFn, m as matchesTags, j as afterAll, k as afterEach, l as aroundAll, n as aroundEach, o as beforeAll, q as beforeEach, r as describe, t as it, u as onTestFailed, v as onTestFinished, w as recordArtifact, x as suite, y as test } from './run.BfrMbGVD.js';
1
+ import { b as printDiffOrStringify, d as diff, a as processError, r as replaceAsymmetricMatcher, g as getRunningTests, c as getCurrentTest, e as recordArtifact, T as TestSyntaxError, f as createTaskCollector, h as getCurrentSuite, i as createChainable, j as getHooks, k as getFn, m as matchesTags, l as afterAll, n as afterEach, o as aroundAll, q as aroundEach, t as beforeAll, u as beforeEach, v as describe, w as it, x as onTestFailed, y as onTestFinished, z as suite, A as test } from './run.zBhXlcZQ.js';
2
2
  import { i as isChildProcess, r as resetModules, g as getWorkerState } from './utils.DYj33du9.js';
3
- import { e as parseErrorStacktrace, a as getSafeTimers, f as parseSingleStack, h as delay } from './source-map.BjWcsIL9.js';
4
- import { i as isMockFunction, f as fn, a as spyOn, r as restoreAllMocks, b as resetAllMocks, c as clearAllMocks } from './spy.DDMXghXv.js';
5
- import { u as isObject, B as getCallLastIndex, g as getType, D as noop, x as assertTypes, w as ordinal, E as createSimpleStackTrace, i as isAbsolute, a as relative, n as normalize } from './pathe.M-eThtNZ.Ba-7h1rE.js';
6
- import { g as getDefaultExportFromCjs, f as format, a as commonjsGlobal } from './index.D0heQG4v.js';
7
- import { s as stringify, i as inspect } from './display.BlTmubjj.js';
3
+ import { e as parseErrorStacktrace, a as getSafeTimers, f as parseSingleStack, h as delay } from './source-map.DPHGMWvM.js';
4
+ import { i as isMockFunction, f as fn, a as spyOn, r as restoreAllMocks, b as resetAllMocks, c as clearAllMocks } from './spy.BO0hTE3G.js';
5
+ import { g as getType, f as isObject, D as noop, y as assertTypes, x as ordinal, u as deepClone, E as createSimpleStackTrace, i as isAbsolute, a as relative, n as normalize } from './pathe.M-eThtNZ.zq3TM4NT.js';
6
+ import { a as commonjsGlobal } from './index.Or9psEGe.js';
7
+ import { s as stringify, i as inspect } from './display.Cj2h2zsY.js';
8
8
  import { $ } from './tinyrainbow.Do8I1XRG.js';
9
9
  import * as chai from 'chai';
10
- import { use, util } from 'chai';
10
+ import { util } from 'chai';
11
11
  import { getNames, getTests, getTestName, createFileTask } from '../task-utils.js';
12
- import { g as getSerializers, a as addSerializer } from './plugins.DPQHVT0p.js';
13
- import { p as positionToOffset, o as offsetToLineNumber, l as lineSplitRE } from './offset.Dy-5Fdfn.js';
14
- import { r as rpc, V as VitestEvaluatedModules } from './rpc.BV0XpJ5q.js';
12
+ import { a as addSerializer } from './plugins.BPruPOR8.js';
13
+ import { C as CounterMap, D as DefaultMap, e as evaluateSnapshotFile, k as keyToTestName, s as saveSnapshotFile, a as saveInlineSnapshots, b as saveRawSnapshots, t as testNameToKey, c as serialize, d as addExtraLineBreaks, n as normalizeNewlines, r as removeExtraLineBreaks, f as deepMergeSnapshot, g as stripSnapshotIndentation } from './rawSnapshot.DvoRLRNr.js';
14
+ import { V as VitestEvaluatedModules } from './index.CAmut2NG.js';
15
15
  import { Bench } from 'tinybench';
16
+ import { r as rpc } from './rpc.CNYWPa97.js';
16
17
  import { expectTypeOf } from 'expect-type';
17
18
 
18
- var naturalCompare$1 = {exports: {}};
19
-
20
- var hasRequiredNaturalCompare;
21
-
22
- function requireNaturalCompare () {
23
- if (hasRequiredNaturalCompare) return naturalCompare$1.exports;
24
- hasRequiredNaturalCompare = 1;
25
- /*
26
- * @version 1.4.0
27
- * @date 2015-10-26
28
- * @stability 3 - Stable
29
- * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
30
- * @license MIT License
31
- */
32
-
33
-
34
- var naturalCompare = function(a, b) {
35
- var i, codeA
36
- , codeB = 1
37
- , posA = 0
38
- , posB = 0
39
- , alphabet = String.alphabet;
40
-
41
- function getCode(str, pos, code) {
42
- if (code) {
43
- for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
44
- return +str.slice(pos - 1, i)
45
- }
46
- code = alphabet && alphabet.indexOf(str.charAt(pos));
47
- return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
48
- : code < 46 ? 65 // -
49
- : code < 48 ? code - 1
50
- : code < 58 ? code + 18 // 0-9
51
- : code < 65 ? code - 11
52
- : code < 91 ? code + 11 // A-Z
53
- : code < 97 ? code - 37
54
- : code < 123 ? code + 5 // a-z
55
- : code - 63
56
- }
57
-
58
-
59
- if ((a+="") != (b+="")) for (;codeB;) {
60
- codeA = getCode(a, posA++);
61
- codeB = getCode(b, posB++);
62
-
63
- if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
64
- codeA = getCode(a, posA, posA);
65
- codeB = getCode(b, posB, posA = i);
66
- posB = i;
67
- }
68
-
69
- if (codeA != codeB) return (codeA < codeB) ? -1 : 1
70
- }
71
- return 0
72
- };
73
-
74
- try {
75
- naturalCompare$1.exports = naturalCompare;
76
- } catch (e) {
77
- String.naturalCompare = naturalCompare;
78
- }
79
- return naturalCompare$1.exports;
80
- }
81
-
82
- var naturalCompareExports = requireNaturalCompare();
83
- var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports);
84
-
85
- // TODO: rewrite and clean up
86
- function testNameToKey(testName, count) {
87
- return `${testName} ${count}`;
88
- }
89
- function keyToTestName(key) {
90
- if (!/ \d+$/.test(key)) throw new Error("Snapshot keys must end with a number.");
91
- return key.replace(/ \d+$/, "");
92
- }
93
- // Evaluate a snapshot file's content into its snapshot key/value pairs.
94
- function evaluateSnapshotFile(filepath, content) {
95
- const data = Object.create(null);
96
- try {
97
- new Function("exports", content)(data);
98
- } catch (cause) {
99
- throw new Error(`Invalid snapshot file, please manually fix or delete it: ${filepath}`, { cause });
100
- }
101
- return data;
102
- }
103
- // Add extra line breaks at beginning and end of multiline snapshot
104
- // to make the content easier to read.
105
- function addExtraLineBreaks(string) {
106
- return string.includes("\n") ? `\n${string}\n` : string;
107
- }
108
- // Remove extra line breaks at beginning and end of multiline snapshot.
109
- // Instead of trim, which can remove additional newlines or spaces
110
- // at beginning or end of the content from a custom serializer.
111
- function removeExtraLineBreaks(string) {
112
- return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string;
113
- }
114
- // export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => {
115
- // const lines = stack.split('\n')
116
- // for (let i = 0; i < lines.length; i += 1) {
117
- // // It's a function name specified in `packages/expect/src/index.ts`
118
- // // for external custom matchers.
119
- // if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__'))
120
- // return lines.slice(i + 1).join('\n')
121
- // }
122
- // return stack
123
- // }
124
- const escapeRegex = true;
125
- const printFunctionName = false;
126
- function serialize(val, indent = 2, formatOverrides = {}) {
127
- return normalizeNewlines(format(val, {
128
- escapeRegex,
129
- indent,
130
- plugins: getSerializers(),
131
- printFunctionName,
132
- ...formatOverrides
133
- }));
134
- }
135
- function escapeBacktickString(str) {
136
- // a raw CR inside a template literal is read back as LF
137
- return str.replace(/`|\\|\$\{/g, "\\$&").replace(/\r/g, "\\r");
138
- }
139
- function printBacktickString(str) {
140
- return `\`${escapeBacktickString(str)}\``;
141
- }
142
- function normalizeNewlines(string) {
143
- return string.replace(/\r\n|\r/g, "\n");
144
- }
145
- async function saveSnapshotFile(environment, snapshotData, snapshotPath) {
146
- const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
147
- const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`;
148
- const oldContent = await environment.readSnapshotFile(snapshotPath);
149
- if (oldContent != null && oldContent === content) return;
150
- await environment.saveSnapshotFile(snapshotPath, content);
151
- }
152
- function deepMergeArray(target = [], source = []) {
153
- const mergedOutput = Array.from(target);
154
- source.forEach((sourceElement, index) => {
155
- const targetElement = mergedOutput[index];
156
- if (Array.isArray(target[index])) mergedOutput[index] = deepMergeArray(target[index], sourceElement);
157
- else if (isObject(targetElement)) mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
158
- else
159
- // Source does not exist in target or target is primitive and cannot be deep merged
160
- mergedOutput[index] = sourceElement;
161
- });
162
- return mergedOutput;
163
- }
164
- /**
165
- * Deep merge, but considers asymmetric matchers. Unlike base util's deep merge,
166
- * will merge any object-like instance.
167
- * Compatible with Jest's snapshot matcher. Should not be used outside of snapshot.
168
- *
169
- * @example
170
- * ```ts
171
- * toMatchSnapshot({
172
- * name: expect.stringContaining('text')
173
- * })
174
- * ```
175
- */
176
- function deepMergeSnapshot(target, source) {
177
- if (isObject(target) && isObject(source)) {
178
- const mergedOutput = { ...target };
179
- Object.keys(source).forEach((key) => {
180
- if (isObject(source[key]) && !source[key].$$typeof) {
181
- if (!(key in target)) Object.assign(mergedOutput, { [key]: source[key] });
182
- else mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
183
- } else if (Array.isArray(source[key])) mergedOutput[key] = deepMergeArray(target[key], source[key]);
184
- else Object.assign(mergedOutput, { [key]: source[key] });
185
- });
186
- return mergedOutput;
187
- } else if (Array.isArray(target) && Array.isArray(source)) return deepMergeArray(target, source);
188
- return target;
189
- }
190
- class DefaultMap extends Map {
191
- defaultFn;
192
- constructor(defaultFn, entries) {
193
- super(entries);
194
- this.defaultFn = defaultFn;
195
- }
196
- get(key) {
197
- if (!this.has(key)) this.set(key, this.defaultFn(key));
198
- return super.get(key);
199
- }
200
- }
201
- class CounterMap extends DefaultMap {
202
- constructor() {
203
- super(() => 0);
204
- }
205
- // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322
206
- // `valueOf` and `Snapshot.added` setter allows
207
- // snapshotState.added = snapshotState.added + 1
208
- // to function as
209
- // snapshotState.added.total_ = snapshotState.added.total() + 1
210
- _total;
211
- valueOf() {
212
- return this._total = this.total();
213
- }
214
- increment(key) {
215
- if (typeof this._total !== "undefined") this._total++;
216
- this.set(key, this.get(key) + 1);
217
- }
218
- total() {
219
- if (typeof this._total !== "undefined") return this._total;
220
- let total = 0;
221
- for (const x of this.values()) total += x;
222
- return total;
223
- }
224
- }
225
- /* @__NO_SIDE_EFFECTS__ */
226
- function memo(fn) {
227
- const cache = /* @__PURE__ */ new Map();
228
- return (arg) => {
229
- if (!cache.has(arg)) cache.set(arg, fn(arg));
230
- return cache.get(arg);
231
- };
232
- }
233
-
234
- async function saveInlineSnapshots(environment, snapshots) {
235
- const MagicString = (await import('magic-string')).default;
236
- const files = new Set(snapshots.map((i) => i.file));
237
- await Promise.all(Array.from(files).map(async (file) => {
238
- const snaps = snapshots.filter((i) => i.file === file);
239
- const code = await environment.readSnapshotFile(file);
240
- if (code == null) throw new Error(`cannot read ${file} when saving inline snapshot`);
241
- const s = new MagicString(code);
242
- for (const snap of snaps) replaceInlineSnap(code, s, positionToOffset(code, snap.line, snap.column), snap.snapshot, snap.assertionName);
243
- const transformed = s.toString();
244
- if (transformed !== code) await environment.saveSnapshotFile(file, transformed);
245
- }));
246
- }
247
- const defaultStartObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/;
248
- function escapeRegExp(s) {
249
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
250
- }
251
- const buildStartObjectRegex = memo((assertionName) => {
252
- const replaced = defaultStartObjectRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
253
- return new RegExp(replaced);
254
- });
255
- function replaceObjectSnap(code, s, index, newSnap, assertionName) {
256
- let _code = code.slice(index);
257
- const startMatch = (assertionName ? buildStartObjectRegex(assertionName) : defaultStartObjectRegex).exec(_code);
258
- if (!startMatch) return false;
259
- _code = _code.slice(startMatch.index);
260
- let callEnd = getCallLastIndex(_code);
261
- if (callEnd === null) return false;
262
- callEnd += index + startMatch.index;
263
- const shapeEnd = getObjectShapeEndIndex(code, index + startMatch.index + startMatch[0].length);
264
- const snap = `, ${prepareSnapString(newSnap, code, index)}`;
265
- if (shapeEnd === callEnd)
266
- // toMatchInlineSnapshot({ foo: expect.any(String) })
267
- s.appendLeft(callEnd, snap);
268
- else
269
- // toMatchInlineSnapshot({ foo: expect.any(String) }, ``)
270
- s.overwrite(shapeEnd, callEnd, snap);
271
- return true;
272
- }
273
- function getObjectShapeEndIndex(code, index) {
274
- let startBraces = 1;
275
- let endBraces = 0;
276
- while (startBraces !== endBraces && index < code.length) {
277
- const s = code[index++];
278
- if (s === "{") startBraces++;
279
- else if (s === "}") endBraces++;
280
- }
281
- return index;
282
- }
283
- function prepareSnapString(snap, source, index) {
284
- const lineNumber = offsetToLineNumber(source, index);
285
- const indent = source.split(lineSplitRE)[lineNumber - 1].match(/^\s*/)[0] || "";
286
- const indentNext = indent.includes(" ") ? `${indent}\t` : `${indent} `;
287
- const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
288
- const isOneline = lines.length <= 1;
289
- const quote = "`";
290
- if (isOneline) return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`;
291
- return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`;
292
- }
293
- const defaultMethodNames = ["toMatchInlineSnapshot", "toThrowErrorMatchingInlineSnapshot"];
294
- // on webkit, the line number is at the end of the method, not at the start
295
- function getCodeStartingAtIndex(code, index, methodNames) {
296
- for (const name of methodNames) {
297
- const adjusted = index - name.length;
298
- if (adjusted >= 0 && code.slice(adjusted, index) === name) return {
299
- code: code.slice(adjusted),
300
- index: adjusted
301
- };
302
- }
303
- return {
304
- code: code.slice(index),
305
- index
306
- };
307
- }
308
- const defaultStartRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/;
309
- const buildStartRegex = memo((assertionName) => {
310
- const replaced = defaultStartRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
311
- return new RegExp(replaced);
312
- });
313
- function replaceInlineSnap(code, s, currentIndex, newSnap, assertionName) {
314
- const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex, assertionName ? [assertionName] : defaultMethodNames);
315
- const startMatch = (assertionName ? buildStartRegex(assertionName) : defaultStartRegex).exec(codeStartingAtIndex);
316
- const firstKeywordMatch = (assertionName ? new RegExp(escapeRegExp(assertionName)) : /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/).exec(codeStartingAtIndex);
317
- if (!startMatch || startMatch.index !== firstKeywordMatch?.index) return replaceObjectSnap(code, s, index, newSnap, assertionName);
318
- const quote = startMatch[1];
319
- const startIndex = index + startMatch.index + startMatch[0].length;
320
- const snapString = prepareSnapString(newSnap, code, index);
321
- if (quote === ")") {
322
- s.appendRight(startIndex - 1, snapString);
323
- return true;
324
- }
325
- const endMatch = new RegExp(`(?:^|[^\\\\])${quote}`).exec(code.slice(startIndex));
326
- if (!endMatch) return false;
327
- const endIndex = startIndex + endMatch.index + endMatch[0].length;
328
- s.overwrite(startIndex - 1, endIndex, snapString);
329
- return true;
330
- }
331
- const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
332
- function stripSnapshotIndentation(inlineSnapshot) {
333
- // Find indentation if exists.
334
- const match = inlineSnapshot.match(INDENTATION_REGEX);
335
- if (!match || !match[1])
336
- // No indentation.
337
- return inlineSnapshot;
338
- const indentation = match[1];
339
- const lines = inlineSnapshot.split(/\n/g);
340
- if (lines.length <= 2)
341
- // Must be at least 3 lines.
342
- return inlineSnapshot;
343
- if (lines[0].trim() !== "" || lines.at(-1)?.trim() !== "")
344
- // If not blank first and last lines, abort.
345
- return inlineSnapshot;
346
- for (let i = 1; i < lines.length - 1; i++) if (lines[i] !== "") {
347
- if (lines[i].indexOf(indentation) !== 0)
348
- // All lines except first and last should either be blank or have the same
349
- // indent as the first line (or more). If this isn't the case we don't
350
- // want to touch the snapshot at all.
351
- return inlineSnapshot;
352
- lines[i] = lines[i].substring(indentation.length);
353
- }
354
- // Last line is a special case because it won't have the same indent as others
355
- // but may still have been given some indent to line up.
356
- lines[lines.length - 1] = "";
357
- // Return inline snapshot, now at indent 0.
358
- inlineSnapshot = lines.join("\n");
359
- return inlineSnapshot;
360
- }
361
-
362
- async function saveRawSnapshots(environment, snapshots) {
363
- await Promise.all(snapshots.map(async (snap) => {
364
- if (!snap.readonly) await environment.saveSnapshotFile(snap.file, snap.snapshot);
365
- }));
366
- }
367
-
368
19
  function isSameStackPosition(x, y) {
369
20
  return x.file === y.file && x.column === y.column && x.line === y.line;
370
21
  }
@@ -608,7 +259,8 @@ class SnapshotState {
608
259
  count: opts.count,
609
260
  expected: opts.expectedDisplay,
610
261
  key: opts.key,
611
- pass: false
262
+ pass: false,
263
+ update: this._createUpdate(opts)
612
264
  };
613
265
  } else {
614
266
  this.matched.increment(opts.testId);
@@ -621,6 +273,29 @@ class SnapshotState {
621
273
  };
622
274
  }
623
275
  }
276
+ _createUpdate(opts) {
277
+ if (opts.stack) return {
278
+ type: "inline",
279
+ file: opts.stack.file,
280
+ line: opts.stack.line,
281
+ column: opts.stack.column,
282
+ snapshot: opts.addValue,
283
+ testId: opts.testId,
284
+ assertionName: opts.assertionName
285
+ };
286
+ if (opts.rawSnapshot) return {
287
+ type: "raw",
288
+ file: opts.rawSnapshot.file,
289
+ readonly: opts.rawSnapshot.readonly,
290
+ snapshot: opts.addValue
291
+ };
292
+ return {
293
+ type: "file",
294
+ file: this.snapshotPath,
295
+ key: opts.key,
296
+ snapshot: opts.addValue
297
+ };
298
+ }
624
299
  async save() {
625
300
  const hasExternalSnapshots = Object.keys(this._snapshotData).length;
626
301
  const hasInlineSnapshots = this._inlineSnapshots.length;
@@ -864,7 +539,7 @@ class SnapshotClient {
864
539
  }
865
540
  received = deepMergeSnapshot(received, properties);
866
541
  }
867
- const { actual, expected, key, pass } = snapshotState.match({
542
+ const { actual, expected, key, pass, update } = snapshotState.match({
868
543
  testId,
869
544
  testName,
870
545
  received,
@@ -878,7 +553,8 @@ class SnapshotClient {
878
553
  pass,
879
554
  message: () => `Snapshot \`${key || "unknown"}\` mismatched`,
880
555
  actual: rawSnapshot ? actual : actual?.trim(),
881
- expected: rawSnapshot ? expected : expected?.trim()
556
+ expected: rawSnapshot ? expected : expected?.trim(),
557
+ meta: createMatchMeta(key, update)
882
558
  };
883
559
  }
884
560
  assert(options) {
@@ -889,7 +565,7 @@ class SnapshotClient {
889
565
  }
890
566
  }
891
567
  matchDomain(options) {
892
- const { received, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error } = options;
568
+ const { received, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error, assertionName } = options;
893
569
  if (!filepath) throw new Error("Snapshot cannot be used outside of test");
894
570
  const captured = adapter.capture(received);
895
571
  const rendered = adapter.render(captured);
@@ -903,24 +579,25 @@ class SnapshotClient {
903
579
  });
904
580
  expectedSnapshot.markAsChecked();
905
581
  const matchResult = expectedSnapshot.data !== void 0 ? adapter.match(captured, adapter.parseExpected(expectedSnapshot.data)) : void 0;
906
- const { actual, expected, key, pass } = snapshotState.processDomainSnapshot({
582
+ const { actual, expected, key, pass, update } = snapshotState.processDomainSnapshot({
907
583
  testId,
908
584
  received: rendered,
909
585
  expectedSnapshot,
910
586
  matchResult,
911
587
  isInline,
912
588
  error,
913
- assertionName: options.assertionName
589
+ assertionName
914
590
  });
915
591
  return {
916
592
  pass,
917
593
  message: () => `Snapshot \`${key}\` mismatched`,
918
594
  actual: actual?.trim(),
919
- expected: expected?.trim()
595
+ expected: expected?.trim(),
596
+ meta: createMatchMeta(key, update)
920
597
  };
921
598
  }
922
599
  async pollMatchDomain(options) {
923
- const { poll, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error, timeout = 1e3, interval = 50 } = options;
600
+ const { poll, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error, timeout = 1e3, interval = 50, assertionName } = options;
924
601
  if (!filepath) throw new Error("Snapshot cannot be used outside of test");
925
602
  const snapshotState = this.getSnapshotState(filepath);
926
603
  const testName = [name, ...message ? [message] : []].join(" > ");
@@ -956,20 +633,21 @@ class SnapshotClient {
956
633
  // Silently hiding the error and creating snapshot full scratch isn't good either.
957
634
  // Users can fix or purge the broken snapshot manually and that decision affects how domain snapshot gets updated.
958
635
  const matchResult = expectedSnapshot.data !== void 0 ? adapter.match(stableResult.captured, adapter.parseExpected(expectedSnapshot.data)) : void 0;
959
- const { actual, expected, key, pass } = snapshotState.processDomainSnapshot({
636
+ const { actual, expected, key, pass, update } = snapshotState.processDomainSnapshot({
960
637
  testId,
961
638
  received: stableResult.rendered,
962
639
  expectedSnapshot,
963
640
  matchResult,
964
641
  isInline,
965
642
  error,
966
- assertionName: options.assertionName
643
+ assertionName
967
644
  });
968
645
  return {
969
646
  pass,
970
647
  message: () => `Snapshot \`${key}\` mismatched`,
971
648
  actual: actual?.trim(),
972
- expected: expected?.trim()
649
+ expected: expected?.trim(),
650
+ meta: createMatchMeta(key, update)
973
651
  };
974
652
  }
975
653
  async assertRaw(options) {
@@ -1045,6 +723,13 @@ function raceWith$1(promise, other) {
1045
723
  value
1046
724
  }))]);
1047
725
  }
726
+ function createMatchMeta(key, update) {
727
+ return update && {
728
+ type: "snapshot",
729
+ key,
730
+ update
731
+ };
732
+ }
1048
733
 
1049
734
  const ChaiStyleAssertions = (chai, utils) => {
1050
735
  function defProperty(name, delegateTo) {
@@ -1410,6 +1095,12 @@ const IteratorSymbol = Symbol.iterator;
1410
1095
  function hasIterator(object) {
1411
1096
  return !!(object != null && object[IteratorSymbol]);
1412
1097
  }
1098
+ function isTypedArray(value) {
1099
+ return ArrayBuffer.isView(value);
1100
+ }
1101
+ function getNonIndexEntries(typedArray) {
1102
+ return Object.keys(typedArray).slice(typedArray.length).map((key) => [key, Reflect.get(typedArray, key)]);
1103
+ }
1413
1104
  function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) {
1414
1105
  if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) return;
1415
1106
  if (a.constructor !== b.constructor) return false;
@@ -1463,6 +1154,14 @@ function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) {
1463
1154
  return allFound;
1464
1155
  }
1465
1156
  }
1157
+ if (isTypedArray(a) && isTypedArray(b)) {
1158
+ if (a.length !== b.length) return false;
1159
+ for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i]) && !equals(a[i], b[i], filteredCustomTesters)) return false;
1160
+ if (!equals(getNonIndexEntries(a), getNonIndexEntries(b), filteredCustomTesters)) return false;
1161
+ aStack.pop();
1162
+ bStack.pop();
1163
+ return true;
1164
+ }
1466
1165
  const bIterator = b[IteratorSymbol]();
1467
1166
  for (const aValue of a) {
1468
1167
  const nextB = bIterator.next();
@@ -1951,7 +1650,7 @@ function wrapAssertion(utils, name, fn) {
1951
1650
  return function(...args) {
1952
1651
  // private
1953
1652
  if (name !== "withTest") utils.flag(this, "_name", name);
1954
- if (!utils.flag(this, "soft"))
1653
+ if (!(utils.flag(this, "soft") && !utils.flag(this, "promise")))
1955
1654
  // avoid WebKit's proper tail call to preserve stacktrace offset for inline snapshot
1956
1655
  // https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit
1957
1656
  try {
@@ -2509,10 +2208,14 @@ const JestChaiExpect = (chai, utils) => {
2509
2208
  return proxy;
2510
2209
  });
2511
2210
  };
2211
+ function formatDiff(expected, received) {
2212
+ const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(deepClone(received, { forceWritable: true }), deepClone(expected, { forceWritable: true }));
2213
+ return diff(replacedExpected, replacedActual, { omitAnnotationLines: true });
2214
+ }
2512
2215
  function formatCalls(spy, msg, showActualCall) {
2513
2216
  if (spy.mock.calls.length) msg += $.gray(`\n\nReceived:\n\n${spy.mock.calls.map((callArg, i) => {
2514
2217
  let methodCall = $.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call:\n\n`);
2515
- if (showActualCall) methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true });
2218
+ if (showActualCall) methodCall += formatDiff(showActualCall, callArg);
2516
2219
  else methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n");
2517
2220
  methodCall += "\n";
2518
2221
  return methodCall;
@@ -2523,7 +2226,7 @@ function formatCalls(spy, msg, showActualCall) {
2523
2226
  function formatReturns(spy, results, msg, showActualReturn) {
2524
2227
  if (results.length) msg += $.gray(`\n\nReceived:\n\n${results.map((callReturn, i) => {
2525
2228
  let methodCall = $.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call return:\n\n`);
2526
- if (showActualReturn) methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true });
2229
+ if (showActualReturn) methodCall += formatDiff(showActualReturn, callReturn.value);
2527
2230
  else methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n");
2528
2231
  methodCall += "\n";
2529
2232
  return methodCall;
@@ -2662,7 +2365,8 @@ function JestExtendPlugin(c, expect, matchers) {
2662
2365
  }
2663
2366
  const JestExtend = (chai, utils) => {
2664
2367
  utils.addMethod(chai.expect, "extend", (expect, expects) => {
2665
- use(JestExtendPlugin(chai, expect, expects));
2368
+ // not `chai.use`, it keeps every plugin forever
2369
+ JestExtendPlugin(chai, expect, expects)(chai, utils);
2666
2370
  });
2667
2371
  };
2668
2372
 
@@ -2708,6 +2412,92 @@ const benchMatchers = {
2708
2412
  }
2709
2413
  };
2710
2414
 
2415
+ const attempts = /* @__PURE__ */ new WeakMap();
2416
+ function startTraceAttempt(test, options) {
2417
+ attempts.set(test, {
2418
+ ...options,
2419
+ startTime: performance.now(),
2420
+ entries: []
2421
+ });
2422
+ }
2423
+ function getTraceAttempt(test) {
2424
+ return attempts.get(test);
2425
+ }
2426
+ function createTraceRangeId() {
2427
+ return Math.random().toString(36).slice(2);
2428
+ }
2429
+ function recordTraceEntry(attempt, entry, source) {
2430
+ attempt.entries.push({
2431
+ entry: {
2432
+ ...entry,
2433
+ startTime: performance.now() - attempt.startTime
2434
+ },
2435
+ source
2436
+ });
2437
+ }
2438
+ function startPromiseTraceRange(name, source) {
2439
+ const test = getCurrentTest();
2440
+ // the current test is a guess when several tests run concurrently
2441
+ const attempt = test && getRunningTests().size === 1 ? attempts.get(test) : void 0;
2442
+ if (!attempt) return (promise) => promise;
2443
+ const id = createTraceRangeId();
2444
+ recordTraceEntry(attempt, {
2445
+ name,
2446
+ kind: "expect",
2447
+ range: {
2448
+ id,
2449
+ phase: "start"
2450
+ }
2451
+ }, source);
2452
+ const end = (status) => recordTraceEntry(attempt, {
2453
+ name,
2454
+ kind: "expect",
2455
+ range: {
2456
+ id,
2457
+ phase: "end"
2458
+ },
2459
+ status
2460
+ }, source);
2461
+ return (promise) => {
2462
+ promise.then(() => end("pass"), () => end("fail"));
2463
+ return promise;
2464
+ };
2465
+ }
2466
+ async function finishTraceAttempt(test) {
2467
+ const attempt = attempts.get(test);
2468
+ attempts.delete(test);
2469
+ // record only failed attempts
2470
+ if (!attempt || test.result?.state !== "fail" || !attempt.entries.length) return;
2471
+ // locations are resolved in the main process, like error stacks
2472
+ const entries = attempt.entries.map(({ entry, source }) => ({
2473
+ ...entry,
2474
+ stack: source.stack
2475
+ }));
2476
+ const data = {
2477
+ retry: attempt.retry,
2478
+ repeats: attempt.repeats,
2479
+ entries
2480
+ };
2481
+ await recordArtifact(test, {
2482
+ type: "internal:browserTrace",
2483
+ data
2484
+ });
2485
+ }
2486
+
2487
+ /**
2488
+ * Copies the stack trace from one error to another.
2489
+ *
2490
+ * If the source has no stack trace, the target is left unchanged.
2491
+ *
2492
+ * @param target - The error to copy the stack trace to.
2493
+ * @param source - The error to copy the stack trace from.
2494
+ * @returns The target error with the updated stack trace.
2495
+ */
2496
+ function copyStackTrace(target, source) {
2497
+ if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
2498
+ return target;
2499
+ }
2500
+
2711
2501
  var fakeTimersSrc = {};
2712
2502
 
2713
2503
  var global;
@@ -7170,15 +6960,27 @@ function validateOptions(options) {
7170
6960
  if (typeof options?.times === "number" && options.times <= 0) throw new RangeError("vi.when: `times` option must be greater than 0");
7171
6961
  }
7172
6962
 
7173
- function copyStackTrace$2(target, source) {
7174
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
7175
- return target;
6963
+ function prefixMessage(error, message) {
6964
+ if (message && error instanceof Error) {
6965
+ const original = error.message;
6966
+ try {
6967
+ error.message = `${message}: ${original}`;
6968
+ } catch {
6969
+ // message can be read-only, e.g. DOMException
6970
+ return error;
6971
+ }
6972
+ if (error.stack !== void 0) error.stack = error.stack.replace(original, error.message);
6973
+ }
6974
+ return error;
6975
+ }
6976
+ function getTraceName(name, message) {
6977
+ return message ? `${message} (${name})` : `${name}()`;
7176
6978
  }
7177
6979
  function waitFor(callback, options = {}) {
7178
6980
  const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
7179
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
6981
+ const { interval = 50, timeout = 1e3, message } = typeof options === "number" ? { timeout: options } : options;
7180
6982
  const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
7181
- return new Promise((resolve, reject) => {
6983
+ return startPromiseTraceRange(getTraceName("vi.waitFor", message), STACK_TRACE_ERROR)(new Promise((resolve, reject) => {
7182
6984
  let lastError;
7183
6985
  let promiseStatus = "idle";
7184
6986
  let timeoutId;
@@ -7191,8 +6993,8 @@ function waitFor(callback, options = {}) {
7191
6993
  const handleTimeout = () => {
7192
6994
  if (intervalId) clearInterval(intervalId);
7193
6995
  let error = lastError;
7194
- if (!error) error = copyStackTrace$2(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
7195
- reject(error);
6996
+ if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
6997
+ reject(prefixMessage(error, message));
7196
6998
  };
7197
6999
  const checkCallback = () => {
7198
7000
  if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
@@ -7220,20 +7022,20 @@ function waitFor(callback, options = {}) {
7220
7022
  if (checkCallback() === true) return;
7221
7023
  timeoutId = setTimeout(handleTimeout, timeout);
7222
7024
  intervalId = setInterval(checkCallback, interval);
7223
- });
7025
+ }));
7224
7026
  }
7225
7027
  function waitUntil(callback, options = {}) {
7226
7028
  const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
7227
- const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
7029
+ const { interval = 50, timeout = 1e3, message } = typeof options === "number" ? { timeout: options } : options;
7228
7030
  const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
7229
- return new Promise((resolve, reject) => {
7031
+ return startPromiseTraceRange(getTraceName("vi.waitUntil", message), STACK_TRACE_ERROR)(new Promise((resolve, reject) => {
7230
7032
  let promiseStatus = "idle";
7231
7033
  let timeoutId;
7232
7034
  let intervalId;
7233
7035
  const onReject = (error) => {
7234
7036
  if (intervalId) clearInterval(intervalId);
7235
- if (!error) error = copyStackTrace$2(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
7236
- reject(error);
7037
+ if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
7038
+ reject(prefixMessage(error, message));
7237
7039
  };
7238
7040
  const onResolve = (result) => {
7239
7041
  if (!result) return;
@@ -7265,7 +7067,7 @@ function waitUntil(callback, options = {}) {
7265
7067
  if (checkCallback() === true) return;
7266
7068
  timeoutId = setTimeout(onReject, timeout);
7267
7069
  intervalId = setInterval(checkCallback, interval);
7268
- });
7070
+ }));
7269
7071
  }
7270
7072
 
7271
7073
  function createVitest() {
@@ -7380,7 +7182,7 @@ function createVitest() {
7380
7182
  try {
7381
7183
  return await result;
7382
7184
  } catch (error) {
7383
- if (error instanceof Error && !error.stack?.includes("__VITEST_HELPER__")) copyStackTrace$1(error, stackTraceError);
7185
+ if (error instanceof Error && !error.stack?.includes("__VITEST_HELPER__")) copyStackTrace(error, stackTraceError);
7384
7186
  throw error;
7385
7187
  }
7386
7188
  })();
@@ -7514,10 +7316,6 @@ function getImporter(name) {
7514
7316
  });
7515
7317
  return parseSingleStack(stackArray[importerStackIndex + 1])?.file || "";
7516
7318
  }
7517
- function copyStackTrace$1(target, source) {
7518
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
7519
- return target;
7520
- }
7521
7319
  function waitNextTick() {
7522
7320
  const { setTimeout } = getSafeTimers();
7523
7321
  return new Promise((resolve) => setTimeout(resolve, 0));
@@ -7547,18 +7345,23 @@ const unsupported = [
7547
7345
  "toThrowError"
7548
7346
  ];
7549
7347
  /**
7550
- * Attaches a `cause` property to the error if missing, copies the stack trace from the source, and throws.
7348
+ * Attaches a `cause` property to the error if missing, prefixes the custom message, copies the stack trace from the source, and throws.
7551
7349
  *
7552
7350
  * @param error - The error to throw
7553
7351
  * @param source - Error to copy the stack trace from
7352
+ * @param message - Custom message passed to `expect.poll`
7554
7353
  *
7555
7354
  * @throws Always throws the provided error with an amended stack trace
7556
7355
  */
7557
- function throwWithCause(error, source) {
7356
+ function throwWithCause(error, source, message) {
7558
7357
  error.cause ??= /* @__PURE__ */ new Error("Matcher did not succeed in time.");
7358
+ // matcher errors already start with the custom message
7359
+ if (message && typeof error.message === "string" && !error.message.startsWith(`${message}: `)) try {
7360
+ error.message = `${message}: ${error.message}`;
7361
+ } catch {}
7559
7362
  throw copyStackTrace(error, source);
7560
7363
  }
7561
- function createExpectPoll(expect) {
7364
+ function createExpectPoll(expect, isLocalExpect) {
7562
7365
  return function poll(fn, options = {}) {
7563
7366
  const defaults = getWorkerState().config.expect?.poll ?? {};
7564
7367
  const { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options;
@@ -7571,6 +7374,8 @@ function createExpectPoll(expect) {
7571
7374
  chai.util.flag(assertion, "_poll.interval", interval);
7572
7375
  const test = chai.util.flag(assertion, "vitest-test");
7573
7376
  if (!test) throw new Error("expect.poll() must be called inside a test");
7377
+ // the global expect guesses the current test, which is ambiguous while several tests run concurrently
7378
+ if (isLocalExpect || getRunningTests().size === 1) setTraceHandlers(assertion, test);
7574
7379
  const proxy = new Proxy(assertion, { get(target, key, receiver) {
7575
7380
  const assertionFunction = Reflect.get(target, key, receiver);
7576
7381
  if (typeof assertionFunction !== "function") return assertionFunction instanceof chai.Assertion ? proxy : assertionFunction;
@@ -7614,7 +7419,7 @@ function createExpectPoll(expect) {
7614
7419
  assertion,
7615
7420
  status: "fail"
7616
7421
  });
7617
- throwWithCause(err, STACK_TRACE_ERROR);
7422
+ throwWithCause(err, STACK_TRACE_ERROR, message);
7618
7423
  }
7619
7424
  const { setTimeout, clearTimeout } = getSafeTimers();
7620
7425
  let timerId;
@@ -7662,7 +7467,7 @@ function createExpectPoll(expect) {
7662
7467
  assertion,
7663
7468
  status: "fail"
7664
7469
  });
7665
- throwWithCause(lastError, STACK_TRACE_ERROR);
7470
+ throwWithCause(lastError, STACK_TRACE_ERROR, message);
7666
7471
  }
7667
7472
  };
7668
7473
  let awaited = false;
@@ -7671,7 +7476,8 @@ function createExpectPoll(expect) {
7671
7476
  if (!awaited) {
7672
7477
  const negated = chai.util.flag(assertion, "negate") ? "not." : "";
7673
7478
  const assertionString = `expect.${chai.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`;
7674
- throw copyStackTrace(/* @__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`), STACK_TRACE_ERROR);
7479
+ const 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`);
7480
+ throw copyStackTrace(error, STACK_TRACE_ERROR);
7675
7481
  }
7676
7482
  });
7677
7483
  let resultPromise;
@@ -7700,9 +7506,41 @@ function createExpectPoll(expect) {
7700
7506
  return proxy;
7701
7507
  };
7702
7508
  }
7703
- function copyStackTrace(target, source) {
7704
- if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
7705
- return target;
7509
+ function setTraceHandlers(assertion, test) {
7510
+ const attempt = getTraceAttempt(test);
7511
+ if (!attempt) return;
7512
+ const rangeId = createTraceRangeId();
7513
+ // TODO: compute the name once in `__VITEST_POLL_CHAIN__` and pass it to the hooks,
7514
+ // so this and `getTraceName` in packages/browser/src/client/tester/expect-element.ts can share it
7515
+ const getName = (assertion) => {
7516
+ const negated = chai.util.flag(assertion, "negate") ? "not." : "";
7517
+ const message = chai.util.flag(assertion, "message");
7518
+ const name = `expect.poll().${negated}${chai.util.flag(assertion, "_name")}`;
7519
+ return message ? `${message} (${name})` : `${name}()`;
7520
+ };
7521
+ const onStart = ({ assertion }) => {
7522
+ recordTraceEntry(attempt, {
7523
+ name: getName(assertion),
7524
+ kind: "expect",
7525
+ range: {
7526
+ id: rangeId,
7527
+ phase: "start"
7528
+ }
7529
+ }, chai.util.flag(assertion, "error"));
7530
+ };
7531
+ const onSettled = ({ assertion, status }) => {
7532
+ recordTraceEntry(attempt, {
7533
+ name: getName(assertion),
7534
+ kind: "expect",
7535
+ range: {
7536
+ id: rangeId,
7537
+ phase: "end"
7538
+ },
7539
+ status
7540
+ }, chai.util.flag(assertion, "error"));
7541
+ };
7542
+ chai.util.flag(assertion, "_poll.onStart", onStart);
7543
+ chai.util.flag(assertion, "_poll.onSettled", onSettled);
7706
7544
  }
7707
7545
  function raceWith(promise, other) {
7708
7546
  const left = promise.then((value) => ({
@@ -7785,7 +7623,9 @@ const SnapshotPlugin = (chai, utils) => {
7785
7623
  filepath,
7786
7624
  hint
7787
7625
  }).then((result) => assertMatchResult(result, chai.util.flag(this, "message")));
7788
- return recordAsyncExpect(getTest(this), assertPromise, createAssertionMessage(utils, this, true), /* @__PURE__ */ new Error("resolves"), utils.flag(this, "soft"));
7626
+ // `.resolves/rejects` handle `expect.soft` through `recordAsyncExpect`
7627
+ const isSoft = utils.flag(this, "soft") && !utils.flag(this, "promise");
7628
+ return recordAsyncExpect(getTest(this), assertPromise, createAssertionMessage(utils, this, true), /* @__PURE__ */ new Error("resolves"), isSoft);
7789
7629
  });
7790
7630
  utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", wrapAssertion(utils, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT_OFFSET_3__(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
7791
7631
  return assertMatchResult(toMatchSnapshotImpl({
@@ -7901,6 +7741,7 @@ async function toMatchFileSnapshotImpl(options) {
7901
7741
  const snapshotState = getSnapshotClient().getSnapshotState(testNames.filepath);
7902
7742
  const rawSnapshotFile = await snapshotState.environment.resolveRawPath(testNames.filepath, options.filepath);
7903
7743
  const rawSnapshotContent = await snapshotState.environment.readSnapshotFile(rawSnapshotFile);
7744
+ const assertionName = getAssertionName(assertion);
7904
7745
  return getSnapshotClient().match({
7905
7746
  received: options.received,
7906
7747
  message: options.hint,
@@ -7908,6 +7749,7 @@ async function toMatchFileSnapshotImpl(options) {
7908
7749
  file: rawSnapshotFile,
7909
7750
  content: rawSnapshotContent ?? void 0
7910
7751
  },
7752
+ assertionName,
7911
7753
  ...testNames
7912
7754
  });
7913
7755
  }
@@ -7917,7 +7759,8 @@ function assertMatchResult(result, customMessage) {
7917
7759
  throw Object.assign(new Error(errorMessage), {
7918
7760
  actual: result.actual,
7919
7761
  expected: result.expected,
7920
- diffOptions: { expand: getWorkerState().config.snapshotOptions.expand }
7762
+ diffOptions: { expand: getWorkerState().config.snapshotOptions.expand },
7763
+ __vitest_error_context__: { meta: result.meta }
7921
7764
  });
7922
7765
  }
7923
7766
  }
@@ -8088,7 +7931,7 @@ function createExpect(test) {
8088
7931
  // @ts-expect-error private soft access
8089
7932
  return expect(...args).withContext({ soft: true });
8090
7933
  };
8091
- expect.poll = createExpectPoll(expect);
7934
+ expect.poll = createExpectPoll(expect, !!test);
8092
7935
  expect.unreachable = (message) => {
8093
7936
  chai.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
8094
7937
  };
@@ -8110,11 +7953,11 @@ function createExpect(test) {
8110
7953
  }
8111
7954
  chai.util.addMethod(expect, "assertions", assertions);
8112
7955
  chai.util.addMethod(expect, "hasAssertions", hasAssertions);
8113
- expect.extend(customMatchers);
8114
- expect.extend(benchMatchers);
8115
7956
  return expect;
8116
7957
  }
8117
7958
  const globalExpect = createExpect();
7959
+ globalExpect.extend(customMatchers);
7960
+ globalExpect.extend(benchMatchers);
8118
7961
  Object.defineProperty(globalThis, GLOBAL_EXPECT, {
8119
7962
  value: globalExpect,
8120
7963
  writable: true,
@@ -8537,18 +8380,26 @@ class TestRunner {
8537
8380
  if (suite.mode !== "skip" && "filepath" in suite) await this.snapshotClient.setup(suite.file.filepath, this.workerState.config.snapshotOptions);
8538
8381
  this.workerState.current = suite;
8539
8382
  }
8540
- onBeforeTryTask(test, _options) {
8383
+ onBeforeTryTask(test, options) {
8384
+ if (this.config.experimental.traceTimeline && test.type === "test") startTraceAttempt(test, options);
8541
8385
  clearModuleMocks(this.config);
8542
8386
  this.snapshotClient.clearTest(test.file.filepath, test.id);
8543
- setState({
8387
+ const assertionState = {
8544
8388
  assertionCalls: 0,
8545
8389
  isExpectingAssertions: false,
8546
8390
  isExpectingAssertionsError: null,
8547
8391
  expectedAssertionsNumber: null,
8548
- expectedAssertionsNumberErrorGen: null,
8392
+ expectedAssertionsNumberErrorGen: null
8393
+ };
8394
+ setState({
8395
+ ...assertionState,
8549
8396
  currentTestName: getTestName(test),
8550
8397
  snapshotState: this.snapshotClient.getSnapshotState(test.file.filepath)
8551
8398
  }, globalThis[GLOBAL_EXPECT]);
8399
+ if (test.type === "test" && test.context._local) setState(assertionState, test.context.expect);
8400
+ }
8401
+ async onAfterRetryTask(test, _options) {
8402
+ if (this.config.experimental.traceTimeline) await finishTraceAttempt(test);
8552
8403
  }
8553
8404
  onAfterTryTask(test) {
8554
8405
  this.benchInstances.get(test)?.[kFinalize]();
@@ -8629,33 +8480,33 @@ function clearModuleMocks(config) {
8629
8480
  const assertType = function assertType() {};
8630
8481
 
8631
8482
  var index = /*#__PURE__*/Object.freeze({
8632
- __proto__: null,
8633
- EvaluatedModules: VitestEvaluatedModules,
8634
- Snapshots: Snapshots,
8635
- TestRunner: TestRunner,
8636
- afterAll: afterAll,
8637
- afterEach: afterEach,
8638
- aroundAll: aroundAll,
8639
- aroundEach: aroundEach,
8640
- assert: assert,
8641
- assertType: assertType,
8642
- beforeAll: beforeAll,
8643
- beforeEach: beforeEach,
8644
- chai: chai,
8645
- createExpect: createExpect,
8646
- describe: describe,
8647
- expect: globalExpect,
8648
- expectTypeOf: expectTypeOf,
8649
- inject: inject,
8650
- it: it,
8651
- onTestFailed: onTestFailed,
8652
- onTestFinished: onTestFinished,
8653
- recordArtifact: recordArtifact,
8654
- should: should,
8655
- suite: suite,
8656
- test: test,
8657
- vi: vi,
8658
- vitest: vitest
8483
+ __proto__: null,
8484
+ EvaluatedModules: VitestEvaluatedModules,
8485
+ Snapshots: Snapshots,
8486
+ TestRunner: TestRunner,
8487
+ afterAll: afterAll,
8488
+ afterEach: afterEach,
8489
+ aroundAll: aroundAll,
8490
+ aroundEach: aroundEach,
8491
+ assert: assert,
8492
+ assertType: assertType,
8493
+ beforeAll: beforeAll,
8494
+ beforeEach: beforeEach,
8495
+ chai: chai,
8496
+ createExpect: createExpect,
8497
+ describe: describe,
8498
+ expect: globalExpect,
8499
+ expectTypeOf: expectTypeOf,
8500
+ inject: inject,
8501
+ it: it,
8502
+ onTestFailed: onTestFailed,
8503
+ onTestFinished: onTestFinished,
8504
+ recordArtifact: recordArtifact,
8505
+ should: should,
8506
+ suite: suite,
8507
+ test: test,
8508
+ vi: vi,
8509
+ vitest: vitest
8659
8510
  });
8660
8511
 
8661
8512
  export { Snapshots as S, TestRunner as T, assert as a, assertType as b, createExpect as c, inject as d, vitest as e, globalExpect as g, index as i, should as s, vi as v };