@depup/vitest__snapshot 4.1.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,908 @@
1
+ import { parseErrorStacktrace } from '@vitest/utils/source-map';
2
+ import { getCallLastIndex, isObject } from '@vitest/utils/helpers';
3
+ import { positionToOffset, offsetToLineNumber, lineSplitRE } from '@vitest/utils/offset';
4
+ import { plugins, format } from '@vitest/pretty-format';
5
+
6
+ async function saveInlineSnapshots(environment, snapshots) {
7
+ const MagicString = (await import('magic-string')).default;
8
+ const files = new Set(snapshots.map((i) => i.file));
9
+ await Promise.all(Array.from(files).map(async (file) => {
10
+ const snaps = snapshots.filter((i) => i.file === file);
11
+ const code = await environment.readSnapshotFile(file);
12
+ if (code == null) {
13
+ throw new Error(`cannot read ${file} when saving inline snapshot`);
14
+ }
15
+ const s = new MagicString(code);
16
+ for (const snap of snaps) {
17
+ const index = positionToOffset(code, snap.line, snap.column);
18
+ replaceInlineSnap(code, s, index, snap.snapshot);
19
+ }
20
+ const transformed = s.toString();
21
+ if (transformed !== code) {
22
+ await environment.saveSnapshotFile(file, transformed);
23
+ }
24
+ }));
25
+ }
26
+ const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/;
27
+ function replaceObjectSnap(code, s, index, newSnap) {
28
+ let _code = code.slice(index);
29
+ const startMatch = startObjectRegex.exec(_code);
30
+ if (!startMatch) {
31
+ return false;
32
+ }
33
+ _code = _code.slice(startMatch.index);
34
+ let callEnd = getCallLastIndex(_code);
35
+ if (callEnd === null) {
36
+ return false;
37
+ }
38
+ callEnd += index + startMatch.index;
39
+ const shapeStart = index + startMatch.index + startMatch[0].length;
40
+ const shapeEnd = getObjectShapeEndIndex(code, shapeStart);
41
+ const snap = `, ${prepareSnapString(newSnap, code, index)}`;
42
+ if (shapeEnd === callEnd) {
43
+ // toMatchInlineSnapshot({ foo: expect.any(String) })
44
+ s.appendLeft(callEnd, snap);
45
+ } else {
46
+ // toMatchInlineSnapshot({ foo: expect.any(String) }, ``)
47
+ s.overwrite(shapeEnd, callEnd, snap);
48
+ }
49
+ return true;
50
+ }
51
+ function getObjectShapeEndIndex(code, index) {
52
+ let startBraces = 1;
53
+ let endBraces = 0;
54
+ while (startBraces !== endBraces && index < code.length) {
55
+ const s = code[index++];
56
+ if (s === "{") {
57
+ startBraces++;
58
+ } else if (s === "}") {
59
+ endBraces++;
60
+ }
61
+ }
62
+ return index;
63
+ }
64
+ function prepareSnapString(snap, source, index) {
65
+ const lineNumber = offsetToLineNumber(source, index);
66
+ const line = source.split(lineSplitRE)[lineNumber - 1];
67
+ const indent = line.match(/^\s*/)[0] || "";
68
+ const indentNext = indent.includes(" ") ? `${indent}\t` : `${indent} `;
69
+ const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
70
+ const isOneline = lines.length <= 1;
71
+ const quote = "`";
72
+ if (isOneline) {
73
+ return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`;
74
+ }
75
+ return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`;
76
+ }
77
+ const toMatchInlineName = "toMatchInlineSnapshot";
78
+ const toThrowErrorMatchingInlineName = "toThrowErrorMatchingInlineSnapshot";
79
+ // on webkit, the line number is at the end of the method, not at the start
80
+ function getCodeStartingAtIndex(code, index) {
81
+ const indexInline = index - toMatchInlineName.length;
82
+ if (code.slice(indexInline, index) === toMatchInlineName) {
83
+ return {
84
+ code: code.slice(indexInline),
85
+ index: indexInline
86
+ };
87
+ }
88
+ const indexThrowInline = index - toThrowErrorMatchingInlineName.length;
89
+ if (code.slice(index - indexThrowInline, index) === toThrowErrorMatchingInlineName) {
90
+ return {
91
+ code: code.slice(index - indexThrowInline),
92
+ index: index - indexThrowInline
93
+ };
94
+ }
95
+ return {
96
+ code: code.slice(index),
97
+ index
98
+ };
99
+ }
100
+ const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/;
101
+ function replaceInlineSnap(code, s, currentIndex, newSnap) {
102
+ const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex);
103
+ const startMatch = startRegex.exec(codeStartingAtIndex);
104
+ const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex);
105
+ if (!startMatch || startMatch.index !== firstKeywordMatch?.index) {
106
+ return replaceObjectSnap(code, s, index, newSnap);
107
+ }
108
+ const quote = startMatch[1];
109
+ const startIndex = index + startMatch.index + startMatch[0].length;
110
+ const snapString = prepareSnapString(newSnap, code, index);
111
+ if (quote === ")") {
112
+ s.appendRight(startIndex - 1, snapString);
113
+ return true;
114
+ }
115
+ const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`);
116
+ const endMatch = quoteEndRE.exec(code.slice(startIndex));
117
+ if (!endMatch) {
118
+ return false;
119
+ }
120
+ const endIndex = startIndex + endMatch.index + endMatch[0].length;
121
+ s.overwrite(startIndex - 1, endIndex, snapString);
122
+ return true;
123
+ }
124
+ const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
125
+ function stripSnapshotIndentation(inlineSnapshot) {
126
+ // Find indentation if exists.
127
+ const match = inlineSnapshot.match(INDENTATION_REGEX);
128
+ if (!match || !match[1]) {
129
+ // No indentation.
130
+ return inlineSnapshot;
131
+ }
132
+ const indentation = match[1];
133
+ const lines = inlineSnapshot.split(/\n/g);
134
+ if (lines.length <= 2) {
135
+ // Must be at least 3 lines.
136
+ return inlineSnapshot;
137
+ }
138
+ if (lines[0].trim() !== "" || lines.at(-1)?.trim() !== "") {
139
+ // If not blank first and last lines, abort.
140
+ return inlineSnapshot;
141
+ }
142
+ for (let i = 1; i < lines.length - 1; i++) {
143
+ if (lines[i] !== "") {
144
+ if (lines[i].indexOf(indentation) !== 0) {
145
+ // All lines except first and last should either be blank or have the same
146
+ // indent as the first line (or more). If this isn't the case we don't
147
+ // want to touch the snapshot at all.
148
+ return inlineSnapshot;
149
+ }
150
+ lines[i] = lines[i].substring(indentation.length);
151
+ }
152
+ }
153
+ // Last line is a special case because it won't have the same indent as others
154
+ // but may still have been given some indent to line up.
155
+ lines[lines.length - 1] = "";
156
+ // Return inline snapshot, now at indent 0.
157
+ inlineSnapshot = lines.join("\n");
158
+ return inlineSnapshot;
159
+ }
160
+
161
+ async function saveRawSnapshots(environment, snapshots) {
162
+ await Promise.all(snapshots.map(async (snap) => {
163
+ if (!snap.readonly) {
164
+ await environment.saveSnapshotFile(snap.file, snap.snapshot);
165
+ }
166
+ }));
167
+ }
168
+
169
+ function getDefaultExportFromCjs(x) {
170
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
171
+ }
172
+
173
+ var naturalCompare$1 = {exports: {}};
174
+
175
+ var hasRequiredNaturalCompare;
176
+
177
+ function requireNaturalCompare () {
178
+ if (hasRequiredNaturalCompare) return naturalCompare$1.exports;
179
+ hasRequiredNaturalCompare = 1;
180
+ /*
181
+ * @version 1.4.0
182
+ * @date 2015-10-26
183
+ * @stability 3 - Stable
184
+ * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
185
+ * @license MIT License
186
+ */
187
+
188
+
189
+ var naturalCompare = function(a, b) {
190
+ var i, codeA
191
+ , codeB = 1
192
+ , posA = 0
193
+ , posB = 0
194
+ , alphabet = String.alphabet;
195
+
196
+ function getCode(str, pos, code) {
197
+ if (code) {
198
+ for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
199
+ return +str.slice(pos - 1, i)
200
+ }
201
+ code = alphabet && alphabet.indexOf(str.charAt(pos));
202
+ return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
203
+ : code < 46 ? 65 // -
204
+ : code < 48 ? code - 1
205
+ : code < 58 ? code + 18 // 0-9
206
+ : code < 65 ? code - 11
207
+ : code < 91 ? code + 11 // A-Z
208
+ : code < 97 ? code - 37
209
+ : code < 123 ? code + 5 // a-z
210
+ : code - 63
211
+ }
212
+
213
+
214
+ if ((a+="") != (b+="")) for (;codeB;) {
215
+ codeA = getCode(a, posA++);
216
+ codeB = getCode(b, posB++);
217
+
218
+ if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
219
+ codeA = getCode(a, posA, posA);
220
+ codeB = getCode(b, posB, posA = i);
221
+ posB = i;
222
+ }
223
+
224
+ if (codeA != codeB) return (codeA < codeB) ? -1 : 1
225
+ }
226
+ return 0
227
+ };
228
+
229
+ try {
230
+ naturalCompare$1.exports = naturalCompare;
231
+ } catch (e) {
232
+ String.naturalCompare = naturalCompare;
233
+ }
234
+ return naturalCompare$1.exports;
235
+ }
236
+
237
+ var naturalCompareExports = requireNaturalCompare();
238
+ var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports);
239
+
240
+ const serialize$1 = (val, config, indentation, depth, refs, printer) => {
241
+ // Serialize a non-default name, even if config.printFunctionName is false.
242
+ const name = val.getMockName();
243
+ const nameString = name === "vi.fn()" ? "" : ` ${name}`;
244
+ let callsString = "";
245
+ if (val.mock.calls.length !== 0) {
246
+ const indentationNext = indentation + config.indent;
247
+ callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`;
248
+ }
249
+ return `[MockFunction${nameString}]${callsString}`;
250
+ };
251
+ const test = (val) => val && !!val._isMockFunction;
252
+ const plugin = {
253
+ serialize: serialize$1,
254
+ test
255
+ };
256
+
257
+ const { DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent, AsymmetricMatcher } = plugins;
258
+ let PLUGINS = [
259
+ ReactTestComponent,
260
+ ReactElement,
261
+ DOMElement,
262
+ DOMCollection,
263
+ Immutable,
264
+ AsymmetricMatcher,
265
+ plugin
266
+ ];
267
+ function addSerializer(plugin) {
268
+ PLUGINS = [plugin].concat(PLUGINS);
269
+ }
270
+ function getSerializers() {
271
+ return PLUGINS;
272
+ }
273
+
274
+ // TODO: rewrite and clean up
275
+ function testNameToKey(testName, count) {
276
+ return `${testName} ${count}`;
277
+ }
278
+ function keyToTestName(key) {
279
+ if (!/ \d+$/.test(key)) {
280
+ throw new Error("Snapshot keys must end with a number.");
281
+ }
282
+ return key.replace(/ \d+$/, "");
283
+ }
284
+ function getSnapshotData(content, options) {
285
+ const update = options.updateSnapshot;
286
+ const data = Object.create(null);
287
+ let snapshotContents = "";
288
+ let dirty = false;
289
+ if (content != null) {
290
+ try {
291
+ snapshotContents = content;
292
+ // eslint-disable-next-line no-new-func
293
+ const populate = new Function("exports", snapshotContents);
294
+ populate(data);
295
+ } catch {}
296
+ }
297
+ // const validationResult = validateSnapshotVersion(snapshotContents)
298
+ const isInvalid = snapshotContents;
299
+ // if (update === 'none' && isInvalid)
300
+ // throw validationResult
301
+ if ((update === "all" || update === "new") && isInvalid) {
302
+ dirty = true;
303
+ }
304
+ return {
305
+ data,
306
+ dirty
307
+ };
308
+ }
309
+ // Add extra line breaks at beginning and end of multiline snapshot
310
+ // to make the content easier to read.
311
+ function addExtraLineBreaks(string) {
312
+ return string.includes("\n") ? `\n${string}\n` : string;
313
+ }
314
+ // Remove extra line breaks at beginning and end of multiline snapshot.
315
+ // Instead of trim, which can remove additional newlines or spaces
316
+ // at beginning or end of the content from a custom serializer.
317
+ function removeExtraLineBreaks(string) {
318
+ return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string;
319
+ }
320
+ // export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => {
321
+ // const lines = stack.split('\n')
322
+ // for (let i = 0; i < lines.length; i += 1) {
323
+ // // It's a function name specified in `packages/expect/src/index.ts`
324
+ // // for external custom matchers.
325
+ // if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__'))
326
+ // return lines.slice(i + 1).join('\n')
327
+ // }
328
+ // return stack
329
+ // }
330
+ const escapeRegex = true;
331
+ const printFunctionName = false;
332
+ function serialize(val, indent = 2, formatOverrides = {}) {
333
+ return normalizeNewlines(format(val, {
334
+ escapeRegex,
335
+ indent,
336
+ plugins: getSerializers(),
337
+ printFunctionName,
338
+ ...formatOverrides
339
+ }));
340
+ }
341
+ function escapeBacktickString(str) {
342
+ return str.replace(/`|\\|\$\{/g, "\\$&");
343
+ }
344
+ function printBacktickString(str) {
345
+ return `\`${escapeBacktickString(str)}\``;
346
+ }
347
+ function normalizeNewlines(string) {
348
+ return string.replace(/\r\n|\r/g, "\n");
349
+ }
350
+ async function saveSnapshotFile(environment, snapshotData, snapshotPath) {
351
+ const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
352
+ const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`;
353
+ const oldContent = await environment.readSnapshotFile(snapshotPath);
354
+ const skipWriting = oldContent != null && oldContent === content;
355
+ if (skipWriting) {
356
+ return;
357
+ }
358
+ await environment.saveSnapshotFile(snapshotPath, content);
359
+ }
360
+ function deepMergeArray(target = [], source = []) {
361
+ const mergedOutput = Array.from(target);
362
+ source.forEach((sourceElement, index) => {
363
+ const targetElement = mergedOutput[index];
364
+ if (Array.isArray(target[index])) {
365
+ mergedOutput[index] = deepMergeArray(target[index], sourceElement);
366
+ } else if (isObject(targetElement)) {
367
+ mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
368
+ } else {
369
+ // Source does not exist in target or target is primitive and cannot be deep merged
370
+ mergedOutput[index] = sourceElement;
371
+ }
372
+ });
373
+ return mergedOutput;
374
+ }
375
+ /**
376
+ * Deep merge, but considers asymmetric matchers. Unlike base util's deep merge,
377
+ * will merge any object-like instance.
378
+ * Compatible with Jest's snapshot matcher. Should not be used outside of snapshot.
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * toMatchSnapshot({
383
+ * name: expect.stringContaining('text')
384
+ * })
385
+ * ```
386
+ */
387
+ function deepMergeSnapshot(target, source) {
388
+ if (isObject(target) && isObject(source)) {
389
+ const mergedOutput = { ...target };
390
+ Object.keys(source).forEach((key) => {
391
+ if (isObject(source[key]) && !source[key].$$typeof) {
392
+ if (!(key in target)) {
393
+ Object.assign(mergedOutput, { [key]: source[key] });
394
+ } else {
395
+ mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
396
+ }
397
+ } else if (Array.isArray(source[key])) {
398
+ mergedOutput[key] = deepMergeArray(target[key], source[key]);
399
+ } else {
400
+ Object.assign(mergedOutput, { [key]: source[key] });
401
+ }
402
+ });
403
+ return mergedOutput;
404
+ } else if (Array.isArray(target) && Array.isArray(source)) {
405
+ return deepMergeArray(target, source);
406
+ }
407
+ return target;
408
+ }
409
+ class DefaultMap extends Map {
410
+ constructor(defaultFn, entries) {
411
+ super(entries);
412
+ this.defaultFn = defaultFn;
413
+ }
414
+ get(key) {
415
+ if (!this.has(key)) {
416
+ this.set(key, this.defaultFn(key));
417
+ }
418
+ return super.get(key);
419
+ }
420
+ }
421
+ class CounterMap extends DefaultMap {
422
+ constructor() {
423
+ super(() => 0);
424
+ }
425
+ // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322
426
+ // `valueOf` and `Snapshot.added` setter allows
427
+ // snapshotState.added = snapshotState.added + 1
428
+ // to function as
429
+ // snapshotState.added.total_ = snapshotState.added.total() + 1
430
+ _total;
431
+ valueOf() {
432
+ return this._total = this.total();
433
+ }
434
+ increment(key) {
435
+ if (typeof this._total !== "undefined") {
436
+ this._total++;
437
+ }
438
+ this.set(key, this.get(key) + 1);
439
+ }
440
+ total() {
441
+ if (typeof this._total !== "undefined") {
442
+ return this._total;
443
+ }
444
+ let total = 0;
445
+ for (const x of this.values()) {
446
+ total += x;
447
+ }
448
+ return total;
449
+ }
450
+ }
451
+
452
+ function isSameStackPosition(x, y) {
453
+ return x.file === y.file && x.column === y.column && x.line === y.line;
454
+ }
455
+ class SnapshotState {
456
+ _counters = new CounterMap();
457
+ _dirty;
458
+ _updateSnapshot;
459
+ _snapshotData;
460
+ _initialData;
461
+ _inlineSnapshots;
462
+ _inlineSnapshotStacks;
463
+ _testIdToKeys = new DefaultMap(() => []);
464
+ _rawSnapshots;
465
+ _uncheckedKeys;
466
+ _snapshotFormat;
467
+ _environment;
468
+ _fileExists;
469
+ expand;
470
+ // getter/setter for jest-image-snapshot compat
471
+ // https://github.com/vitest-dev/vitest/issues/7322
472
+ _added = new CounterMap();
473
+ _matched = new CounterMap();
474
+ _unmatched = new CounterMap();
475
+ _updated = new CounterMap();
476
+ get added() {
477
+ return this._added;
478
+ }
479
+ set added(value) {
480
+ this._added._total = value;
481
+ }
482
+ get matched() {
483
+ return this._matched;
484
+ }
485
+ set matched(value) {
486
+ this._matched._total = value;
487
+ }
488
+ get unmatched() {
489
+ return this._unmatched;
490
+ }
491
+ set unmatched(value) {
492
+ this._unmatched._total = value;
493
+ }
494
+ get updated() {
495
+ return this._updated;
496
+ }
497
+ set updated(value) {
498
+ this._updated._total = value;
499
+ }
500
+ constructor(testFilePath, snapshotPath, snapshotContent, options) {
501
+ this.testFilePath = testFilePath;
502
+ this.snapshotPath = snapshotPath;
503
+ const { data, dirty } = getSnapshotData(snapshotContent, options);
504
+ this._fileExists = snapshotContent != null;
505
+ this._initialData = { ...data };
506
+ this._snapshotData = { ...data };
507
+ this._dirty = dirty;
508
+ this._inlineSnapshots = [];
509
+ this._inlineSnapshotStacks = [];
510
+ this._rawSnapshots = [];
511
+ this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
512
+ this.expand = options.expand || false;
513
+ this._updateSnapshot = options.updateSnapshot;
514
+ this._snapshotFormat = {
515
+ printBasicPrototype: false,
516
+ escapeString: false,
517
+ ...options.snapshotFormat
518
+ };
519
+ this._environment = options.snapshotEnvironment;
520
+ }
521
+ static async create(testFilePath, options) {
522
+ const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath);
523
+ const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath);
524
+ return new SnapshotState(testFilePath, snapshotPath, content, options);
525
+ }
526
+ get environment() {
527
+ return this._environment;
528
+ }
529
+ markSnapshotsAsCheckedForTest(testName) {
530
+ this._uncheckedKeys.forEach((uncheckedKey) => {
531
+ // skip snapshots with following keys
532
+ // testName n
533
+ // testName > xxx n (this is for toMatchSnapshot("xxx") API)
534
+ if (/ \d+$| > /.test(uncheckedKey.slice(testName.length))) {
535
+ this._uncheckedKeys.delete(uncheckedKey);
536
+ }
537
+ });
538
+ }
539
+ clearTest(testId) {
540
+ // clear inline
541
+ this._inlineSnapshots = this._inlineSnapshots.filter((s) => s.testId !== testId);
542
+ this._inlineSnapshotStacks = this._inlineSnapshotStacks.filter((s) => s.testId !== testId);
543
+ // clear file
544
+ for (const key of this._testIdToKeys.get(testId)) {
545
+ const name = keyToTestName(key);
546
+ const count = this._counters.get(name);
547
+ if (count > 0) {
548
+ if (key in this._snapshotData || key in this._initialData) {
549
+ this._snapshotData[key] = this._initialData[key];
550
+ }
551
+ this._counters.set(name, count - 1);
552
+ }
553
+ }
554
+ this._testIdToKeys.delete(testId);
555
+ // clear stats
556
+ this.added.delete(testId);
557
+ this.updated.delete(testId);
558
+ this.matched.delete(testId);
559
+ this.unmatched.delete(testId);
560
+ }
561
+ _inferInlineSnapshotStack(stacks) {
562
+ // if called inside resolves/rejects, stacktrace is different
563
+ const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/));
564
+ if (promiseIndex !== -1) {
565
+ return stacks[promiseIndex + 3];
566
+ }
567
+ // inline snapshot function can be named __INLINE_SNAPSHOT_OFFSET_<n>__
568
+ // to specify a custom stack offset
569
+ for (let i = 0; i < stacks.length; i++) {
570
+ const match = stacks[i].method.match(/__INLINE_SNAPSHOT_OFFSET_(\d+)__/);
571
+ if (match) {
572
+ return stacks[i + Number(match[1])] ?? null;
573
+ }
574
+ }
575
+ // inline snapshot function is called __INLINE_SNAPSHOT__
576
+ // in integrations/snapshot/chai.ts
577
+ const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__"));
578
+ return stackIndex !== -1 ? stacks[stackIndex + 2] : null;
579
+ }
580
+ _addSnapshot(key, receivedSerialized, options) {
581
+ this._dirty = true;
582
+ if (options.stack) {
583
+ this._inlineSnapshots.push({
584
+ snapshot: receivedSerialized,
585
+ testId: options.testId,
586
+ ...options.stack
587
+ });
588
+ } else if (options.rawSnapshot) {
589
+ this._rawSnapshots.push({
590
+ ...options.rawSnapshot,
591
+ snapshot: receivedSerialized
592
+ });
593
+ } else {
594
+ this._snapshotData[key] = receivedSerialized;
595
+ }
596
+ }
597
+ async save() {
598
+ const hasExternalSnapshots = Object.keys(this._snapshotData).length;
599
+ const hasInlineSnapshots = this._inlineSnapshots.length;
600
+ const hasRawSnapshots = this._rawSnapshots.length;
601
+ const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots;
602
+ const status = {
603
+ deleted: false,
604
+ saved: false
605
+ };
606
+ if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
607
+ if (hasExternalSnapshots) {
608
+ await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath);
609
+ this._fileExists = true;
610
+ }
611
+ if (hasInlineSnapshots) {
612
+ await saveInlineSnapshots(this._environment, this._inlineSnapshots);
613
+ }
614
+ if (hasRawSnapshots) {
615
+ await saveRawSnapshots(this._environment, this._rawSnapshots);
616
+ }
617
+ status.saved = true;
618
+ } else if (!hasExternalSnapshots && this._fileExists) {
619
+ if (this._updateSnapshot === "all") {
620
+ await this._environment.removeSnapshotFile(this.snapshotPath);
621
+ this._fileExists = false;
622
+ }
623
+ status.deleted = true;
624
+ }
625
+ return status;
626
+ }
627
+ getUncheckedCount() {
628
+ return this._uncheckedKeys.size || 0;
629
+ }
630
+ getUncheckedKeys() {
631
+ return Array.from(this._uncheckedKeys);
632
+ }
633
+ removeUncheckedKeys() {
634
+ if (this._updateSnapshot === "all" && this._uncheckedKeys.size) {
635
+ this._dirty = true;
636
+ this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]);
637
+ this._uncheckedKeys.clear();
638
+ }
639
+ }
640
+ match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }) {
641
+ // this also increments counter for inline snapshots. maybe we shouldn't?
642
+ this._counters.increment(testName);
643
+ const count = this._counters.get(testName);
644
+ if (!key) {
645
+ key = testNameToKey(testName, count);
646
+ }
647
+ this._testIdToKeys.get(testId).push(key);
648
+ // Do not mark the snapshot as "checked" if the snapshot is inline and
649
+ // there's an external snapshot. This way the external snapshot can be
650
+ // removed with `--updateSnapshot`.
651
+ if (!(isInline && this._snapshotData[key] !== undefined)) {
652
+ this._uncheckedKeys.delete(key);
653
+ }
654
+ let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, undefined, this._snapshotFormat);
655
+ if (!rawSnapshot) {
656
+ receivedSerialized = addExtraLineBreaks(receivedSerialized);
657
+ }
658
+ if (rawSnapshot) {
659
+ // normalize EOL when snapshot contains CRLF but received is LF
660
+ if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) {
661
+ rawSnapshot.content = normalizeNewlines(rawSnapshot.content);
662
+ }
663
+ }
664
+ const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key];
665
+ const expectedTrimmed = rawSnapshot ? expected : expected?.trim();
666
+ const pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim());
667
+ const hasSnapshot = expected !== undefined;
668
+ const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null;
669
+ if (pass && !isInline && !rawSnapshot) {
670
+ // Executing a snapshot file as JavaScript and writing the strings back
671
+ // when other snapshots have changed loses the proper escaping for some
672
+ // characters. Since we check every snapshot in every test, use the newly
673
+ // generated formatted string.
674
+ // Note that this is only relevant when a snapshot is added and the dirty
675
+ // flag is set.
676
+ this._snapshotData[key] = receivedSerialized;
677
+ }
678
+ // find call site of toMatchInlineSnapshot
679
+ let stack;
680
+ if (isInline) {
681
+ const stacks = parseErrorStacktrace(error || new Error("snapshot"), { ignoreStackEntries: [] });
682
+ const _stack = this._inferInlineSnapshotStack(stacks);
683
+ if (!_stack) {
684
+ throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.\n${JSON.stringify(stacks)}`);
685
+ }
686
+ stack = this.environment.processStackTrace?.(_stack) || _stack;
687
+ // removing 1 column, because source map points to the wrong
688
+ // location for js files, but `column-1` points to the same in both js/ts
689
+ // https://github.com/vitejs/vite/issues/8657
690
+ stack.column--;
691
+ // reject multiple inline snapshots at the same location if snapshot is different
692
+ const snapshotsWithSameStack = this._inlineSnapshotStacks.filter((s) => isSameStackPosition(s, stack));
693
+ if (snapshotsWithSameStack.length > 0) {
694
+ // ensure only one snapshot will be written at the same location
695
+ this._inlineSnapshots = this._inlineSnapshots.filter((s) => !isSameStackPosition(s, stack));
696
+ const differentSnapshot = snapshotsWithSameStack.find((s) => s.snapshot !== receivedSerialized);
697
+ if (differentSnapshot) {
698
+ throw Object.assign(new Error("toMatchInlineSnapshot with different snapshots cannot be called at the same location"), {
699
+ actual: receivedSerialized,
700
+ expected: differentSnapshot.snapshot
701
+ });
702
+ }
703
+ }
704
+ this._inlineSnapshotStacks.push({
705
+ ...stack,
706
+ testId,
707
+ snapshot: receivedSerialized
708
+ });
709
+ }
710
+ // These are the conditions on when to write snapshots:
711
+ // * There's no snapshot file in a non-CI environment.
712
+ // * There is a snapshot file and we decided to update the snapshot.
713
+ // * There is a snapshot file, but it doesn't have this snapshot.
714
+ // These are the conditions on when not to write snapshots:
715
+ // * The update flag is set to 'none'.
716
+ // * There's no snapshot file or a file without this snapshot on a CI environment.
717
+ if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) {
718
+ if (this._updateSnapshot === "all") {
719
+ if (!pass) {
720
+ if (hasSnapshot) {
721
+ this.updated.increment(testId);
722
+ } else {
723
+ this.added.increment(testId);
724
+ }
725
+ this._addSnapshot(key, receivedSerialized, {
726
+ stack,
727
+ testId,
728
+ rawSnapshot
729
+ });
730
+ } else {
731
+ this.matched.increment(testId);
732
+ }
733
+ } else {
734
+ this._addSnapshot(key, receivedSerialized, {
735
+ stack,
736
+ testId,
737
+ rawSnapshot
738
+ });
739
+ this.added.increment(testId);
740
+ }
741
+ return {
742
+ actual: "",
743
+ count,
744
+ expected: "",
745
+ key,
746
+ pass: true
747
+ };
748
+ } else {
749
+ if (!pass) {
750
+ this.unmatched.increment(testId);
751
+ return {
752
+ actual: rawSnapshot ? receivedSerialized : removeExtraLineBreaks(receivedSerialized),
753
+ count,
754
+ expected: expectedTrimmed !== undefined ? rawSnapshot ? expectedTrimmed : removeExtraLineBreaks(expectedTrimmed) : undefined,
755
+ key,
756
+ pass: false
757
+ };
758
+ } else {
759
+ this.matched.increment(testId);
760
+ return {
761
+ actual: "",
762
+ count,
763
+ expected: "",
764
+ key,
765
+ pass: true
766
+ };
767
+ }
768
+ }
769
+ }
770
+ async pack() {
771
+ const snapshot = {
772
+ filepath: this.testFilePath,
773
+ added: 0,
774
+ fileDeleted: false,
775
+ matched: 0,
776
+ unchecked: 0,
777
+ uncheckedKeys: [],
778
+ unmatched: 0,
779
+ updated: 0
780
+ };
781
+ const uncheckedCount = this.getUncheckedCount();
782
+ const uncheckedKeys = this.getUncheckedKeys();
783
+ if (uncheckedCount) {
784
+ this.removeUncheckedKeys();
785
+ }
786
+ const status = await this.save();
787
+ snapshot.fileDeleted = status.deleted;
788
+ snapshot.added = this.added.total();
789
+ snapshot.matched = this.matched.total();
790
+ snapshot.unmatched = this.unmatched.total();
791
+ snapshot.updated = this.updated.total();
792
+ snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
793
+ snapshot.uncheckedKeys = Array.from(uncheckedKeys);
794
+ return snapshot;
795
+ }
796
+ }
797
+
798
+ function createMismatchError(message, expand, actual, expected) {
799
+ const error = new Error(message);
800
+ Object.defineProperty(error, "actual", {
801
+ value: actual,
802
+ enumerable: true,
803
+ configurable: true,
804
+ writable: true
805
+ });
806
+ Object.defineProperty(error, "expected", {
807
+ value: expected,
808
+ enumerable: true,
809
+ configurable: true,
810
+ writable: true
811
+ });
812
+ Object.defineProperty(error, "diffOptions", { value: { expand } });
813
+ return error;
814
+ }
815
+ class SnapshotClient {
816
+ snapshotStateMap = new Map();
817
+ constructor(options = {}) {
818
+ this.options = options;
819
+ }
820
+ async setup(filepath, options) {
821
+ if (this.snapshotStateMap.has(filepath)) {
822
+ return;
823
+ }
824
+ this.snapshotStateMap.set(filepath, await SnapshotState.create(filepath, options));
825
+ }
826
+ async finish(filepath) {
827
+ const state = this.getSnapshotState(filepath);
828
+ const result = await state.pack();
829
+ this.snapshotStateMap.delete(filepath);
830
+ return result;
831
+ }
832
+ skipTest(filepath, testName) {
833
+ const state = this.getSnapshotState(filepath);
834
+ state.markSnapshotsAsCheckedForTest(testName);
835
+ }
836
+ clearTest(filepath, testId) {
837
+ const state = this.getSnapshotState(filepath);
838
+ state.clearTest(testId);
839
+ }
840
+ getSnapshotState(filepath) {
841
+ const state = this.snapshotStateMap.get(filepath);
842
+ if (!state) {
843
+ throw new Error(`The snapshot state for '${filepath}' is not found. Did you call 'SnapshotClient.setup()'?`);
844
+ }
845
+ return state;
846
+ }
847
+ assert(options) {
848
+ const { filepath, name, testId = name, message, isInline = false, properties, inlineSnapshot, error, errorMessage, rawSnapshot } = options;
849
+ let { received } = options;
850
+ if (!filepath) {
851
+ throw new Error("Snapshot cannot be used outside of test");
852
+ }
853
+ const snapshotState = this.getSnapshotState(filepath);
854
+ if (typeof properties === "object") {
855
+ if (typeof received !== "object" || !received) {
856
+ throw new Error("Received value must be an object when the matcher has properties");
857
+ }
858
+ try {
859
+ const pass = this.options.isEqual?.(received, properties) ?? false;
860
+ // const pass = equals(received, properties, [iterableEquality, subsetEquality])
861
+ if (!pass) {
862
+ throw createMismatchError("Snapshot properties mismatched", snapshotState.expand, received, properties);
863
+ } else {
864
+ received = deepMergeSnapshot(received, properties);
865
+ }
866
+ } catch (err) {
867
+ err.message = errorMessage || "Snapshot mismatched";
868
+ throw err;
869
+ }
870
+ }
871
+ const testName = [name, ...message ? [message] : []].join(" > ");
872
+ const { actual, expected, key, pass } = snapshotState.match({
873
+ testId,
874
+ testName,
875
+ received,
876
+ isInline,
877
+ error,
878
+ inlineSnapshot,
879
+ rawSnapshot
880
+ });
881
+ if (!pass) {
882
+ throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, snapshotState.expand, rawSnapshot ? actual : actual?.trim(), rawSnapshot ? expected : expected?.trim());
883
+ }
884
+ }
885
+ async assertRaw(options) {
886
+ if (!options.rawSnapshot) {
887
+ throw new Error("Raw snapshot is required");
888
+ }
889
+ const { filepath, rawSnapshot } = options;
890
+ if (rawSnapshot.content == null) {
891
+ if (!filepath) {
892
+ throw new Error("Snapshot cannot be used outside of test");
893
+ }
894
+ const snapshotState = this.getSnapshotState(filepath);
895
+ // save the filepath, so it don't lose even if the await make it out-of-context
896
+ options.filepath ||= filepath;
897
+ // resolve and read the raw snapshot file
898
+ rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file);
899
+ rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? undefined;
900
+ }
901
+ return this.assert(options);
902
+ }
903
+ clear() {
904
+ this.snapshotStateMap.clear();
905
+ }
906
+ }
907
+
908
+ export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation };