vitest 0.18.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/LICENSE.md +5 -5
  2. package/dist/browser.d.ts +1850 -0
  3. package/dist/browser.mjs +20 -0
  4. package/dist/{chunk-api-setup.9d3f7670.mjs → chunk-api-setup.0cf2c96a.mjs} +23 -6
  5. package/dist/{chunk-constants.d4406290.mjs → chunk-constants.38b43a44.mjs} +3 -3
  6. package/dist/{chunk-env-node.bbba78e5.mjs → chunk-defaults.408a0cfe.mjs} +456 -455
  7. package/dist/{chunk-install-pkg.2dcb2c04.mjs → chunk-install-pkg.6c6dc0c2.mjs} +11 -10
  8. package/dist/{chunk-integrations-globals.00b6e1ad.mjs → chunk-integrations-globals.803277be.mjs} +6 -5
  9. package/dist/chunk-node-git.9058b82a.mjs +1139 -0
  10. package/dist/chunk-runtime-chain.1e1aabb3.mjs +2025 -0
  11. package/dist/chunk-runtime-error.d82dd2cf.mjs +644 -0
  12. package/dist/{chunk-runtime-chain.b60d57da.mjs → chunk-runtime-hooks.db398170.mjs} +10 -2013
  13. package/dist/{chunk-runtime-mocker.1d853e3a.mjs → chunk-runtime-mocker.dfdfd57b.mjs} +3 -3
  14. package/dist/{chunk-runtime-rpc.9d1f4c48.mjs → chunk-runtime-rpc.45d8ee19.mjs} +1 -1
  15. package/dist/{chunk-utils-global.0a7416cf.mjs → chunk-utils-global.2aa95025.mjs} +11 -6
  16. package/dist/{chunk-utils-source-map.c03f8bc4.mjs → chunk-utils-source-map.8b066ce2.mjs} +2 -2
  17. package/dist/{chunk-vite-node-externalize.6956d2d9.mjs → chunk-vite-node-externalize.a2813ad7.mjs} +103 -1173
  18. package/dist/{chunk-vite-node-utils.8077cd3c.mjs → chunk-vite-node-utils.ad73f2ab.mjs} +13 -2
  19. package/dist/cli.mjs +8 -10
  20. package/dist/config.cjs +3 -1
  21. package/dist/config.d.ts +1 -0
  22. package/dist/config.mjs +3 -1
  23. package/dist/entry.mjs +14 -597
  24. package/dist/index.d.ts +39 -4
  25. package/dist/index.mjs +8 -5
  26. package/dist/node.d.ts +28 -2
  27. package/dist/node.mjs +10 -12
  28. package/dist/suite.mjs +13 -0
  29. package/dist/vendor-index.61438b77.mjs +335 -0
  30. package/dist/{vendor-index.4bf9c627.mjs → vendor-index.62ce5c33.mjs} +11 -343
  31. package/dist/worker.mjs +5 -5
  32. package/package.json +11 -3
@@ -0,0 +1,2025 @@
1
+ import util$1 from 'util';
2
+ import { i as isObject, j as join, d as dirname, b as getCallLastIndex, c as slash, g as getWorkerState, e as getNames, f as assertTypes, p as picocolors, h as getFullName, s as safeSetTimeout, k as safeClearTimeout, n as noop } from './chunk-utils-global.2aa95025.mjs';
3
+ import * as chai$2 from 'chai';
4
+ import { expect, AssertionError, util } from 'chai';
5
+ import { c as commonjsGlobal } from './vendor-_commonjsHelpers.4da45ef5.mjs';
6
+ import { r as rpc } from './chunk-runtime-rpc.45d8ee19.mjs';
7
+ import fs, { promises } from 'fs';
8
+ import { a as plugins_1, f as format_1, g as getOriginalPos, b as posToNumber, n as numberToPos, l as lineSplitRE, p as parseStacktrace, u as unifiedDiff, s as stringify, m as matcherUtils } from './chunk-utils-source-map.8b066ce2.mjs';
9
+ import { isMockFunction } from './spy.mjs';
10
+
11
+ function createChainable(keys, fn) {
12
+ function create(obj) {
13
+ const chain2 = function(...args) {
14
+ return fn.apply(obj, args);
15
+ };
16
+ for (const key of keys) {
17
+ Object.defineProperty(chain2, key, {
18
+ get() {
19
+ return create({ ...obj, [key]: true });
20
+ }
21
+ });
22
+ }
23
+ return chain2;
24
+ }
25
+ const chain = create({});
26
+ chain.fn = fn;
27
+ return chain;
28
+ }
29
+
30
+ function commonjsRequire(path) {
31
+ 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.');
32
+ }
33
+
34
+ var chaiSubset = {exports: {}};
35
+
36
+ (function (module, exports) {
37
+ (function() {
38
+ (function(chaiSubset) {
39
+ if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
40
+ return module.exports = chaiSubset;
41
+ } else {
42
+ return chai.use(chaiSubset);
43
+ }
44
+ })(function(chai, utils) {
45
+ var Assertion = chai.Assertion;
46
+ var assertionPrototype = Assertion.prototype;
47
+
48
+ Assertion.addMethod('containSubset', function (expected) {
49
+ var actual = utils.flag(this, 'object');
50
+ var showDiff = chai.config.showDiff;
51
+
52
+ assertionPrototype.assert.call(this,
53
+ compare(expected, actual),
54
+ 'expected #{act} to contain subset #{exp}',
55
+ 'expected #{act} to not contain subset #{exp}',
56
+ expected,
57
+ actual,
58
+ showDiff
59
+ );
60
+ });
61
+
62
+ chai.assert.containSubset = function(val, exp, msg) {
63
+ new chai.Assertion(val, msg).to.be.containSubset(exp);
64
+ };
65
+
66
+ function compare(expected, actual) {
67
+ if (expected === actual) {
68
+ return true;
69
+ }
70
+ if (typeof(actual) !== typeof(expected)) {
71
+ return false;
72
+ }
73
+ if (typeof(expected) !== 'object' || expected === null) {
74
+ return expected === actual;
75
+ }
76
+ if (!!expected && !actual) {
77
+ return false;
78
+ }
79
+
80
+ if (Array.isArray(expected)) {
81
+ if (typeof(actual.length) !== 'number') {
82
+ return false;
83
+ }
84
+ var aa = Array.prototype.slice.call(actual);
85
+ return expected.every(function (exp) {
86
+ return aa.some(function (act) {
87
+ return compare(exp, act);
88
+ });
89
+ });
90
+ }
91
+
92
+ if (expected instanceof Date) {
93
+ if (actual instanceof Date) {
94
+ return expected.getTime() === actual.getTime();
95
+ } else {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ return Object.keys(expected).every(function (key) {
101
+ var eo = expected[key];
102
+ var ao = actual[key];
103
+ if (typeof(eo) === 'object' && eo !== null && ao !== null) {
104
+ return compare(eo, ao);
105
+ }
106
+ if (typeof(eo) === 'function') {
107
+ return eo(ao);
108
+ }
109
+ return ao === eo;
110
+ });
111
+ }
112
+ });
113
+
114
+ }).call(commonjsGlobal);
115
+ } (chaiSubset));
116
+
117
+ var Subset = chaiSubset.exports;
118
+
119
+ function equals(a, b, customTesters, strictCheck) {
120
+ customTesters = customTesters || [];
121
+ return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
122
+ }
123
+ function isAsymmetric(obj) {
124
+ return !!obj && isA("Function", obj.asymmetricMatch);
125
+ }
126
+ function asymmetricMatch(a, b) {
127
+ const asymmetricA = isAsymmetric(a);
128
+ const asymmetricB = isAsymmetric(b);
129
+ if (asymmetricA && asymmetricB)
130
+ return void 0;
131
+ if (asymmetricA)
132
+ return a.asymmetricMatch(b);
133
+ if (asymmetricB)
134
+ return b.asymmetricMatch(a);
135
+ }
136
+ function eq(a, b, aStack, bStack, customTesters, hasKey2) {
137
+ let result = true;
138
+ const asymmetricResult = asymmetricMatch(a, b);
139
+ if (asymmetricResult !== void 0)
140
+ return asymmetricResult;
141
+ for (let i = 0; i < customTesters.length; i++) {
142
+ const customTesterResult = customTesters[i](a, b);
143
+ if (customTesterResult !== void 0)
144
+ return customTesterResult;
145
+ }
146
+ if (a instanceof Error && b instanceof Error)
147
+ return a.message === b.message;
148
+ if (Object.is(a, b))
149
+ return true;
150
+ if (a === null || b === null)
151
+ return a === b;
152
+ const className = Object.prototype.toString.call(a);
153
+ if (className !== Object.prototype.toString.call(b))
154
+ return false;
155
+ switch (className) {
156
+ case "[object Boolean]":
157
+ case "[object String]":
158
+ case "[object Number]":
159
+ if (typeof a !== typeof b) {
160
+ return false;
161
+ } else if (typeof a !== "object" && typeof b !== "object") {
162
+ return Object.is(a, b);
163
+ } else {
164
+ return Object.is(a.valueOf(), b.valueOf());
165
+ }
166
+ case "[object Date]":
167
+ return +a === +b;
168
+ case "[object RegExp]":
169
+ return a.source === b.source && a.flags === b.flags;
170
+ }
171
+ if (typeof a !== "object" || typeof b !== "object")
172
+ return false;
173
+ if (isDomNode(a) && isDomNode(b))
174
+ return a.isEqualNode(b);
175
+ let length = aStack.length;
176
+ while (length--) {
177
+ if (aStack[length] === a)
178
+ return bStack[length] === b;
179
+ else if (bStack[length] === b)
180
+ return false;
181
+ }
182
+ aStack.push(a);
183
+ bStack.push(b);
184
+ if (className === "[object Array]" && a.length !== b.length)
185
+ return false;
186
+ const aKeys = keys(a, hasKey2);
187
+ let key;
188
+ let size = aKeys.length;
189
+ if (keys(b, hasKey2).length !== size)
190
+ return false;
191
+ while (size--) {
192
+ key = aKeys[size];
193
+ result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2);
194
+ if (!result)
195
+ return false;
196
+ }
197
+ aStack.pop();
198
+ bStack.pop();
199
+ return result;
200
+ }
201
+ function keys(obj, hasKey2) {
202
+ const keys2 = [];
203
+ for (const key in obj) {
204
+ if (hasKey2(obj, key))
205
+ keys2.push(key);
206
+ }
207
+ return keys2.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable));
208
+ }
209
+ function hasDefinedKey(obj, key) {
210
+ return hasKey(obj, key) && obj[key] !== void 0;
211
+ }
212
+ function hasKey(obj, key) {
213
+ return Object.prototype.hasOwnProperty.call(obj, key);
214
+ }
215
+ function isA(typeName, value) {
216
+ return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
217
+ }
218
+ function isDomNode(obj) {
219
+ return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function";
220
+ }
221
+ const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@";
222
+ const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@";
223
+ const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@";
224
+ function isImmutableUnorderedKeyed(maybeKeyed) {
225
+ return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]);
226
+ }
227
+ function isImmutableUnorderedSet(maybeSet) {
228
+ return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]);
229
+ }
230
+ const IteratorSymbol = Symbol.iterator;
231
+ const hasIterator = (object) => !!(object != null && object[IteratorSymbol]);
232
+ const iterableEquality = (a, b, aStack = [], bStack = []) => {
233
+ if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b))
234
+ return void 0;
235
+ if (a.constructor !== b.constructor)
236
+ return false;
237
+ let length = aStack.length;
238
+ while (length--) {
239
+ if (aStack[length] === a)
240
+ return bStack[length] === b;
241
+ }
242
+ aStack.push(a);
243
+ bStack.push(b);
244
+ const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]);
245
+ if (a.size !== void 0) {
246
+ if (a.size !== b.size) {
247
+ return false;
248
+ } else if (isA("Set", a) || isImmutableUnorderedSet(a)) {
249
+ let allFound = true;
250
+ for (const aValue of a) {
251
+ if (!b.has(aValue)) {
252
+ let has = false;
253
+ for (const bValue of b) {
254
+ const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]);
255
+ if (isEqual === true)
256
+ has = true;
257
+ }
258
+ if (has === false) {
259
+ allFound = false;
260
+ break;
261
+ }
262
+ }
263
+ }
264
+ aStack.pop();
265
+ bStack.pop();
266
+ return allFound;
267
+ } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
268
+ let allFound = true;
269
+ for (const aEntry of a) {
270
+ if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) {
271
+ let has = false;
272
+ for (const bEntry of b) {
273
+ const matchedKey = equals(aEntry[0], bEntry[0], [
274
+ iterableEqualityWithStack
275
+ ]);
276
+ let matchedValue = false;
277
+ if (matchedKey === true) {
278
+ matchedValue = equals(aEntry[1], bEntry[1], [
279
+ iterableEqualityWithStack
280
+ ]);
281
+ }
282
+ if (matchedValue === true)
283
+ has = true;
284
+ }
285
+ if (has === false) {
286
+ allFound = false;
287
+ break;
288
+ }
289
+ }
290
+ }
291
+ aStack.pop();
292
+ bStack.pop();
293
+ return allFound;
294
+ }
295
+ }
296
+ const bIterator = b[IteratorSymbol]();
297
+ for (const aValue of a) {
298
+ const nextB = bIterator.next();
299
+ if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack]))
300
+ return false;
301
+ }
302
+ if (!bIterator.next().done)
303
+ return false;
304
+ aStack.pop();
305
+ bStack.pop();
306
+ return true;
307
+ };
308
+ const hasPropertyInObject = (object, key) => {
309
+ const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype;
310
+ if (shouldTerminate)
311
+ return false;
312
+ return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
313
+ };
314
+ const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date);
315
+ const subsetEquality = (object, subset) => {
316
+ const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => {
317
+ if (!isObjectWithKeys(subset2))
318
+ return void 0;
319
+ return Object.keys(subset2).every((key) => {
320
+ if (isObjectWithKeys(subset2[key])) {
321
+ if (seenReferences.has(subset2[key]))
322
+ return equals(object2[key], subset2[key], [iterableEquality]);
323
+ seenReferences.set(subset2[key], true);
324
+ }
325
+ const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [
326
+ iterableEquality,
327
+ subsetEqualityWithContext(seenReferences)
328
+ ]);
329
+ seenReferences.delete(subset2[key]);
330
+ return result;
331
+ });
332
+ };
333
+ return subsetEqualityWithContext()(object, subset);
334
+ };
335
+ const typeEquality = (a, b) => {
336
+ if (a == null || b == null || a.constructor === b.constructor)
337
+ return void 0;
338
+ return false;
339
+ };
340
+ const arrayBufferEquality = (a, b) => {
341
+ if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer))
342
+ return void 0;
343
+ const dataViewA = new DataView(a);
344
+ const dataViewB = new DataView(b);
345
+ if (dataViewA.byteLength !== dataViewB.byteLength)
346
+ return false;
347
+ for (let i = 0; i < dataViewA.byteLength; i++) {
348
+ if (dataViewA.getUint8(i) !== dataViewB.getUint8(i))
349
+ return false;
350
+ }
351
+ return true;
352
+ };
353
+ const sparseArrayEquality = (a, b) => {
354
+ if (!Array.isArray(a) || !Array.isArray(b))
355
+ return void 0;
356
+ const aKeys = Object.keys(a);
357
+ const bKeys = Object.keys(b);
358
+ return equals(a, b, [iterableEquality, typeEquality], true) && equals(aKeys, bKeys);
359
+ };
360
+ const generateToBeMessage = (deepEqualityName, expected = "#{this}", actual = "#{exp}") => {
361
+ const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`;
362
+ if (["toStrictEqual", "toEqual"].includes(deepEqualityName))
363
+ return `${toBeMessage}
364
+
365
+ If it should pass with deep equality, replace "toBe" with "${deepEqualityName}"
366
+
367
+ Expected: ${expected}
368
+ Received: serializes to the same string
369
+ `;
370
+ return toBeMessage;
371
+ };
372
+
373
+ var naturalCompare$1 = {exports: {}};
374
+
375
+ /*
376
+ * @version 1.4.0
377
+ * @date 2015-10-26
378
+ * @stability 3 - Stable
379
+ * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
380
+ * @license MIT License
381
+ */
382
+
383
+
384
+ var naturalCompare = function(a, b) {
385
+ var i, codeA
386
+ , codeB = 1
387
+ , posA = 0
388
+ , posB = 0
389
+ , alphabet = String.alphabet;
390
+
391
+ function getCode(str, pos, code) {
392
+ if (code) {
393
+ for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
394
+ return +str.slice(pos - 1, i)
395
+ }
396
+ code = alphabet && alphabet.indexOf(str.charAt(pos));
397
+ return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
398
+ : code < 46 ? 65 // -
399
+ : code < 48 ? code - 1
400
+ : code < 58 ? code + 18 // 0-9
401
+ : code < 65 ? code - 11
402
+ : code < 91 ? code + 11 // A-Z
403
+ : code < 97 ? code - 37
404
+ : code < 123 ? code + 5 // a-z
405
+ : code - 63
406
+ }
407
+
408
+
409
+ if ((a+="") != (b+="")) for (;codeB;) {
410
+ codeA = getCode(a, posA++);
411
+ codeB = getCode(b, posB++);
412
+
413
+ if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
414
+ codeA = getCode(a, posA, posA);
415
+ codeB = getCode(b, posB, posA = i);
416
+ posB = i;
417
+ }
418
+
419
+ if (codeA != codeB) return (codeA < codeB) ? -1 : 1
420
+ }
421
+ return 0
422
+ };
423
+
424
+ try {
425
+ naturalCompare$1.exports = naturalCompare;
426
+ } catch (e) {
427
+ String.naturalCompare = naturalCompare;
428
+ }
429
+
430
+ const {
431
+ DOMCollection,
432
+ DOMElement,
433
+ Immutable,
434
+ ReactElement,
435
+ ReactTestComponent,
436
+ AsymmetricMatcher: AsymmetricMatcher$1
437
+ } = plugins_1;
438
+ let PLUGINS = [
439
+ ReactTestComponent,
440
+ ReactElement,
441
+ DOMElement,
442
+ DOMCollection,
443
+ Immutable,
444
+ AsymmetricMatcher$1
445
+ ];
446
+ const addSerializer = (plugin) => {
447
+ PLUGINS = [plugin].concat(PLUGINS);
448
+ };
449
+ const getSerializers = () => PLUGINS;
450
+
451
+ const SNAPSHOT_VERSION = "1";
452
+ const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`;
453
+ const testNameToKey = (testName, count) => `${testName} ${count}`;
454
+ const keyToTestName = (key) => {
455
+ if (!/ \d+$/.test(key))
456
+ throw new Error("Snapshot keys must end with a number.");
457
+ return key.replace(/ \d+$/, "");
458
+ };
459
+ const getSnapshotData = (snapshotPath, update) => {
460
+ const data = /* @__PURE__ */ Object.create(null);
461
+ let snapshotContents = "";
462
+ let dirty = false;
463
+ if (fs.existsSync(snapshotPath)) {
464
+ try {
465
+ snapshotContents = fs.readFileSync(snapshotPath, "utf8");
466
+ const populate = new Function("exports", snapshotContents);
467
+ populate(data);
468
+ } catch {
469
+ }
470
+ }
471
+ const isInvalid = snapshotContents;
472
+ if ((update === "all" || update === "new") && isInvalid)
473
+ dirty = true;
474
+ return { data, dirty };
475
+ };
476
+ const addExtraLineBreaks = (string) => string.includes("\n") ? `
477
+ ${string}
478
+ ` : string;
479
+ const removeExtraLineBreaks = (string) => string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string;
480
+ const escapeRegex = true;
481
+ const printFunctionName = false;
482
+ function serialize(val, indent = 2, formatOverrides = {}) {
483
+ return normalizeNewlines(format_1(val, {
484
+ escapeRegex,
485
+ indent,
486
+ plugins: getSerializers(),
487
+ printFunctionName,
488
+ ...formatOverrides
489
+ }));
490
+ }
491
+ function escapeBacktickString(str) {
492
+ return str.replace(/`|\\|\${/g, "\\$&");
493
+ }
494
+ function printBacktickString(str) {
495
+ return `\`${escapeBacktickString(str)}\``;
496
+ }
497
+ function ensureDirectoryExists(filePath) {
498
+ try {
499
+ fs.mkdirSync(join(dirname(filePath)), { recursive: true });
500
+ } catch {
501
+ }
502
+ }
503
+ function normalizeNewlines(string) {
504
+ return string.replace(/\r\n|\r/g, "\n");
505
+ }
506
+ async function saveSnapshotFile(snapshotData, snapshotPath) {
507
+ var _a, _b;
508
+ const snapshots = Object.keys(snapshotData).sort(naturalCompare$1.exports).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
509
+ const content = `${writeSnapshotVersion()}
510
+
511
+ ${snapshots.join("\n\n")}
512
+ `;
513
+ const skipWriting = fs.existsSync(snapshotPath) && await ((_a = fs) == null ? void 0 : _a.promises.readFile(snapshotPath, "utf8")) === content;
514
+ if (skipWriting)
515
+ return;
516
+ ensureDirectoryExists(snapshotPath);
517
+ await ((_b = fs) == null ? void 0 : _b.promises.writeFile(snapshotPath, content, "utf-8"));
518
+ }
519
+ function prepareExpected(expected) {
520
+ function findStartIndent() {
521
+ var _a, _b;
522
+ const matchObject = /^( +)}\s+$/m.exec(expected || "");
523
+ const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length;
524
+ if (objectIndent)
525
+ return objectIndent;
526
+ const matchText = /^\n( +)"/.exec(expected || "");
527
+ return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0;
528
+ }
529
+ const startIndent = findStartIndent();
530
+ let expectedTrimmed = expected == null ? void 0 : expected.trim();
531
+ if (startIndent) {
532
+ expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}");
533
+ }
534
+ return expectedTrimmed;
535
+ }
536
+ function deepMergeArray(target = [], source = []) {
537
+ const mergedOutput = Array.from(target);
538
+ source.forEach((sourceElement, index) => {
539
+ const targetElement = mergedOutput[index];
540
+ if (Array.isArray(target[index])) {
541
+ mergedOutput[index] = deepMergeArray(target[index], sourceElement);
542
+ } else if (isObject(targetElement)) {
543
+ mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
544
+ } else {
545
+ mergedOutput[index] = sourceElement;
546
+ }
547
+ });
548
+ return mergedOutput;
549
+ }
550
+ function deepMergeSnapshot(target, source) {
551
+ if (isObject(target) && isObject(source)) {
552
+ const mergedOutput = { ...target };
553
+ Object.keys(source).forEach((key) => {
554
+ if (isObject(source[key]) && !source[key].$$typeof) {
555
+ if (!(key in target))
556
+ Object.assign(mergedOutput, { [key]: source[key] });
557
+ else
558
+ mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
559
+ } else if (Array.isArray(source[key])) {
560
+ mergedOutput[key] = deepMergeArray(target[key], source[key]);
561
+ } else {
562
+ Object.assign(mergedOutput, { [key]: source[key] });
563
+ }
564
+ });
565
+ return mergedOutput;
566
+ } else if (Array.isArray(target) && Array.isArray(source)) {
567
+ return deepMergeArray(target, source);
568
+ }
569
+ return target;
570
+ }
571
+
572
+ async function saveInlineSnapshots(snapshots) {
573
+ const MagicString = (await import('./chunk-magic-string.efe26975.mjs')).default;
574
+ const files = new Set(snapshots.map((i) => i.file));
575
+ await Promise.all(Array.from(files).map(async (file) => {
576
+ const map = await rpc().getSourceMap(file);
577
+ const snaps = snapshots.filter((i) => i.file === file);
578
+ const code = await promises.readFile(file, "utf8");
579
+ const s = new MagicString(code);
580
+ for (const snap of snaps) {
581
+ const pos = await getOriginalPos(map, snap);
582
+ const index = posToNumber(code, pos);
583
+ replaceInlineSnap(code, s, index, snap.snapshot);
584
+ }
585
+ const transformed = s.toString();
586
+ if (transformed !== code)
587
+ await promises.writeFile(file, transformed, "utf-8");
588
+ }));
589
+ }
590
+ const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*({)/m;
591
+ function replaceObjectSnap(code, s, index, newSnap) {
592
+ code = code.slice(index);
593
+ const startMatch = startObjectRegex.exec(code);
594
+ if (!startMatch)
595
+ return false;
596
+ code = code.slice(startMatch.index);
597
+ const charIndex = getCallLastIndex(code);
598
+ if (charIndex === null)
599
+ return false;
600
+ s.appendLeft(index + startMatch.index + charIndex, `, ${prepareSnapString(newSnap, code, index)}`);
601
+ return true;
602
+ }
603
+ function prepareSnapString(snap, source, index) {
604
+ const lineIndex = numberToPos(source, index).line;
605
+ const line = source.split(lineSplitRE)[lineIndex - 1];
606
+ const indent = line.match(/^\s*/)[0] || "";
607
+ const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `;
608
+ const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
609
+ const isOneline = lines.length <= 1;
610
+ const quote = isOneline ? "'" : "`";
611
+ if (isOneline)
612
+ return `'${lines.join("\n").replace(/'/g, "\\'")}'`;
613
+ else
614
+ return `${quote}
615
+ ${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")}
616
+ ${indent}${quote}`;
617
+ }
618
+ const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*[\w_$]*(['"`\)])/m;
619
+ function replaceInlineSnap(code, s, index, newSnap) {
620
+ const startMatch = startRegex.exec(code.slice(index));
621
+ if (!startMatch)
622
+ return replaceObjectSnap(code, s, index, newSnap);
623
+ const quote = startMatch[1];
624
+ const startIndex = index + startMatch.index + startMatch[0].length;
625
+ const snapString = prepareSnapString(newSnap, code, index);
626
+ if (quote === ")") {
627
+ s.appendRight(startIndex - 1, snapString);
628
+ return true;
629
+ }
630
+ const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`);
631
+ const endMatch = quoteEndRE.exec(code.slice(startIndex));
632
+ if (!endMatch)
633
+ return false;
634
+ const endIndex = startIndex + endMatch.index + endMatch[0].length;
635
+ s.overwrite(startIndex - 1, endIndex, snapString);
636
+ return true;
637
+ }
638
+ const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
639
+ function stripSnapshotIndentation(inlineSnapshot) {
640
+ const match = inlineSnapshot.match(INDENTATION_REGEX);
641
+ if (!match || !match[1]) {
642
+ return inlineSnapshot;
643
+ }
644
+ const indentation = match[1];
645
+ const lines = inlineSnapshot.split(/\n/g);
646
+ if (lines.length <= 2) {
647
+ return inlineSnapshot;
648
+ }
649
+ if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") {
650
+ return inlineSnapshot;
651
+ }
652
+ for (let i = 1; i < lines.length - 1; i++) {
653
+ if (lines[i] !== "") {
654
+ if (lines[i].indexOf(indentation) !== 0) {
655
+ return inlineSnapshot;
656
+ }
657
+ lines[i] = lines[i].substring(indentation.length);
658
+ }
659
+ }
660
+ lines[lines.length - 1] = "";
661
+ inlineSnapshot = lines.join("\n");
662
+ return inlineSnapshot;
663
+ }
664
+
665
+ class SnapshotState {
666
+ constructor(testFilePath, snapshotPath, options) {
667
+ this.testFilePath = testFilePath;
668
+ this.snapshotPath = snapshotPath;
669
+ const { data, dirty } = getSnapshotData(this.snapshotPath, options.updateSnapshot);
670
+ this._initialData = data;
671
+ this._snapshotData = data;
672
+ this._dirty = dirty;
673
+ this._inlineSnapshots = [];
674
+ this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
675
+ this._counters = /* @__PURE__ */ new Map();
676
+ this.expand = options.expand || false;
677
+ this.added = 0;
678
+ this.matched = 0;
679
+ this.unmatched = 0;
680
+ this._updateSnapshot = options.updateSnapshot;
681
+ this.updated = 0;
682
+ this._snapshotFormat = {
683
+ printBasicPrototype: false,
684
+ ...options.snapshotFormat
685
+ };
686
+ }
687
+ markSnapshotsAsCheckedForTest(testName) {
688
+ this._uncheckedKeys.forEach((uncheckedKey) => {
689
+ if (keyToTestName(uncheckedKey) === testName)
690
+ this._uncheckedKeys.delete(uncheckedKey);
691
+ });
692
+ }
693
+ _inferInlineSnapshotStack(stacks) {
694
+ const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/));
695
+ if (promiseIndex !== -1)
696
+ return stacks[promiseIndex + 3];
697
+ const stackIndex = stacks.findIndex((i) => i.method.includes("__VITEST_INLINE_SNAPSHOT__"));
698
+ return stackIndex !== -1 ? stacks[stackIndex + 2] : null;
699
+ }
700
+ _addSnapshot(key, receivedSerialized, options) {
701
+ this._dirty = true;
702
+ if (options.isInline) {
703
+ const error = options.error || new Error("Unknown error");
704
+ const stacks = parseStacktrace(error, true);
705
+ stacks.forEach((i) => i.file = slash(i.file));
706
+ const stack = this._inferInlineSnapshotStack(stacks);
707
+ if (!stack) {
708
+ throw new Error(`Vitest: Couldn't infer stack frame for inline snapshot.
709
+ ${JSON.stringify(stacks)}`);
710
+ }
711
+ stack.column--;
712
+ this._inlineSnapshots.push({
713
+ snapshot: receivedSerialized,
714
+ ...stack
715
+ });
716
+ } else {
717
+ this._snapshotData[key] = receivedSerialized;
718
+ }
719
+ }
720
+ clear() {
721
+ this._snapshotData = this._initialData;
722
+ this._counters = /* @__PURE__ */ new Map();
723
+ this.added = 0;
724
+ this.matched = 0;
725
+ this.unmatched = 0;
726
+ this.updated = 0;
727
+ this._dirty = false;
728
+ }
729
+ async save() {
730
+ const hasExternalSnapshots = Object.keys(this._snapshotData).length;
731
+ const hasInlineSnapshots = this._inlineSnapshots.length;
732
+ const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
733
+ const status = {
734
+ deleted: false,
735
+ saved: false
736
+ };
737
+ if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
738
+ if (hasExternalSnapshots)
739
+ await saveSnapshotFile(this._snapshotData, this.snapshotPath);
740
+ if (hasInlineSnapshots)
741
+ await saveInlineSnapshots(this._inlineSnapshots);
742
+ status.saved = true;
743
+ } else if (!hasExternalSnapshots && fs.existsSync(this.snapshotPath)) {
744
+ if (this._updateSnapshot === "all")
745
+ fs.unlinkSync(this.snapshotPath);
746
+ status.deleted = true;
747
+ }
748
+ return status;
749
+ }
750
+ getUncheckedCount() {
751
+ return this._uncheckedKeys.size || 0;
752
+ }
753
+ getUncheckedKeys() {
754
+ return Array.from(this._uncheckedKeys);
755
+ }
756
+ removeUncheckedKeys() {
757
+ if (this._updateSnapshot === "all" && this._uncheckedKeys.size) {
758
+ this._dirty = true;
759
+ this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]);
760
+ this._uncheckedKeys.clear();
761
+ }
762
+ }
763
+ match({
764
+ testName,
765
+ received,
766
+ key,
767
+ inlineSnapshot,
768
+ isInline,
769
+ error
770
+ }) {
771
+ this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
772
+ const count = Number(this._counters.get(testName));
773
+ if (!key)
774
+ key = testNameToKey(testName, count);
775
+ if (!(isInline && this._snapshotData[key] !== void 0))
776
+ this._uncheckedKeys.delete(key);
777
+ const receivedSerialized = addExtraLineBreaks(serialize(received, void 0, this._snapshotFormat));
778
+ const expected = isInline ? inlineSnapshot : this._snapshotData[key];
779
+ const expectedTrimmed = prepareExpected(expected);
780
+ const pass = expectedTrimmed === prepareExpected(receivedSerialized);
781
+ const hasSnapshot = expected !== void 0;
782
+ const snapshotIsPersisted = isInline || fs.existsSync(this.snapshotPath);
783
+ if (pass && !isInline) {
784
+ this._snapshotData[key] = receivedSerialized;
785
+ }
786
+ if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) {
787
+ if (this._updateSnapshot === "all") {
788
+ if (!pass) {
789
+ if (hasSnapshot)
790
+ this.updated++;
791
+ else
792
+ this.added++;
793
+ this._addSnapshot(key, receivedSerialized, { error, isInline });
794
+ } else {
795
+ this.matched++;
796
+ }
797
+ } else {
798
+ this._addSnapshot(key, receivedSerialized, { error, isInline });
799
+ this.added++;
800
+ }
801
+ return {
802
+ actual: "",
803
+ count,
804
+ expected: "",
805
+ key,
806
+ pass: true
807
+ };
808
+ } else {
809
+ if (!pass) {
810
+ this.unmatched++;
811
+ return {
812
+ actual: removeExtraLineBreaks(receivedSerialized),
813
+ count,
814
+ expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0,
815
+ key,
816
+ pass: false
817
+ };
818
+ } else {
819
+ this.matched++;
820
+ return {
821
+ actual: "",
822
+ count,
823
+ expected: "",
824
+ key,
825
+ pass: true
826
+ };
827
+ }
828
+ }
829
+ }
830
+ async pack() {
831
+ const snapshot = {
832
+ filepath: this.testFilePath,
833
+ added: 0,
834
+ fileDeleted: false,
835
+ matched: 0,
836
+ unchecked: 0,
837
+ uncheckedKeys: [],
838
+ unmatched: 0,
839
+ updated: 0
840
+ };
841
+ const uncheckedCount = this.getUncheckedCount();
842
+ const uncheckedKeys = this.getUncheckedKeys();
843
+ if (uncheckedCount)
844
+ this.removeUncheckedKeys();
845
+ const status = await this.save();
846
+ snapshot.fileDeleted = status.deleted;
847
+ snapshot.added = this.added;
848
+ snapshot.matched = this.matched;
849
+ snapshot.unmatched = this.unmatched;
850
+ snapshot.updated = this.updated;
851
+ snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
852
+ snapshot.uncheckedKeys = Array.from(uncheckedKeys);
853
+ return snapshot;
854
+ }
855
+ }
856
+
857
+ class SnapshotClient {
858
+ constructor() {
859
+ this.snapshotStateMap = /* @__PURE__ */ new Map();
860
+ }
861
+ async setTest(test) {
862
+ var _a;
863
+ this.test = test;
864
+ if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== this.test.file.filepath) {
865
+ this.saveCurrent();
866
+ const filePath = this.test.file.filepath;
867
+ if (!this.getSnapshotState(test)) {
868
+ this.snapshotStateMap.set(filePath, new SnapshotState(filePath, await rpc().resolveSnapshotPath(filePath), getWorkerState().config.snapshotOptions));
869
+ }
870
+ this.snapshotState = this.getSnapshotState(test);
871
+ }
872
+ }
873
+ getSnapshotState(test) {
874
+ return this.snapshotStateMap.get(test.file.filepath);
875
+ }
876
+ clearTest() {
877
+ this.test = void 0;
878
+ }
879
+ skipTestSnapshots(test) {
880
+ var _a;
881
+ (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(test.name);
882
+ }
883
+ assert(options) {
884
+ const {
885
+ test = this.test,
886
+ message,
887
+ isInline = false,
888
+ properties,
889
+ inlineSnapshot,
890
+ error,
891
+ errorMessage
892
+ } = options;
893
+ let { received } = options;
894
+ if (!test)
895
+ throw new Error("Snapshot cannot be used outside of test");
896
+ if (typeof properties === "object") {
897
+ if (typeof received !== "object" || !received)
898
+ throw new Error("Received value must be an object when the matcher has properties");
899
+ try {
900
+ const pass2 = equals(received, properties, [iterableEquality, subsetEquality]);
901
+ if (!pass2)
902
+ expect(received).equals(properties);
903
+ else
904
+ received = deepMergeSnapshot(received, properties);
905
+ } catch (err) {
906
+ err.message = errorMessage || "Snapshot mismatched";
907
+ throw err;
908
+ }
909
+ }
910
+ const testName = [
911
+ ...getNames(test).slice(1),
912
+ ...message ? [message] : []
913
+ ].join(" > ");
914
+ const snapshotState = this.getSnapshotState(test);
915
+ const { actual, expected, key, pass } = snapshotState.match({
916
+ testName,
917
+ received,
918
+ isInline,
919
+ error,
920
+ inlineSnapshot
921
+ });
922
+ if (!pass) {
923
+ try {
924
+ expect(actual.trim()).equals(expected ? expected.trim() : "");
925
+ } catch (error2) {
926
+ error2.message = errorMessage || `Snapshot \`${key || "unknown"}\` mismatched`;
927
+ throw error2;
928
+ }
929
+ }
930
+ }
931
+ async saveCurrent() {
932
+ if (!this.snapshotState)
933
+ return;
934
+ const result = await this.snapshotState.pack();
935
+ await rpc().snapshotSaved(result);
936
+ this.snapshotState = void 0;
937
+ }
938
+ clear() {
939
+ this.snapshotStateMap.clear();
940
+ }
941
+ }
942
+
943
+ let _client;
944
+ function getSnapshotClient() {
945
+ if (!_client)
946
+ _client = new SnapshotClient();
947
+ return _client;
948
+ }
949
+ const getErrorMessage = (err) => {
950
+ if (err instanceof Error)
951
+ return err.message;
952
+ return err;
953
+ };
954
+ const getErrorString = (expected, promise) => {
955
+ if (typeof expected !== "function") {
956
+ if (!promise)
957
+ throw new Error(`expected must be a function, received ${typeof expected}`);
958
+ return getErrorMessage(expected);
959
+ }
960
+ try {
961
+ expected();
962
+ } catch (e) {
963
+ return getErrorMessage(e);
964
+ }
965
+ throw new Error("snapshot function didn't threw");
966
+ };
967
+ const SnapshotPlugin = (chai, utils) => {
968
+ for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
969
+ utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
970
+ const expected = utils.flag(this, "object");
971
+ const test = utils.flag(this, "vitest-test");
972
+ if (typeof properties === "string" && typeof message === "undefined") {
973
+ message = properties;
974
+ properties = void 0;
975
+ }
976
+ const errorMessage = utils.flag(this, "message");
977
+ getSnapshotClient().assert({
978
+ received: expected,
979
+ test,
980
+ message,
981
+ isInline: false,
982
+ properties,
983
+ errorMessage
984
+ });
985
+ });
986
+ }
987
+ utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __VITEST_INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
988
+ const expected = utils.flag(this, "object");
989
+ const error = utils.flag(this, "error");
990
+ const test = utils.flag(this, "vitest-test");
991
+ if (typeof properties === "string") {
992
+ message = inlineSnapshot;
993
+ inlineSnapshot = properties;
994
+ properties = void 0;
995
+ }
996
+ if (inlineSnapshot)
997
+ inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
998
+ const errorMessage = utils.flag(this, "message");
999
+ getSnapshotClient().assert({
1000
+ received: expected,
1001
+ test,
1002
+ message,
1003
+ isInline: true,
1004
+ properties,
1005
+ inlineSnapshot,
1006
+ error,
1007
+ errorMessage
1008
+ });
1009
+ });
1010
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
1011
+ const expected = utils.flag(this, "object");
1012
+ const test = utils.flag(this, "vitest-test");
1013
+ const promise = utils.flag(this, "promise");
1014
+ const errorMessage = utils.flag(this, "message");
1015
+ getSnapshotClient().assert({
1016
+ received: getErrorString(expected, promise),
1017
+ test,
1018
+ message,
1019
+ errorMessage
1020
+ });
1021
+ });
1022
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __VITEST_INLINE_SNAPSHOT__(inlineSnapshot, message) {
1023
+ const expected = utils.flag(this, "object");
1024
+ const error = utils.flag(this, "error");
1025
+ const test = utils.flag(this, "vitest-test");
1026
+ const promise = utils.flag(this, "promise");
1027
+ const errorMessage = utils.flag(this, "message");
1028
+ getSnapshotClient().assert({
1029
+ received: getErrorString(expected, promise),
1030
+ test,
1031
+ message,
1032
+ inlineSnapshot,
1033
+ isInline: true,
1034
+ error,
1035
+ errorMessage
1036
+ });
1037
+ });
1038
+ };
1039
+
1040
+ var chai$1 = /*#__PURE__*/Object.freeze({
1041
+ __proto__: null,
1042
+ getSnapshotClient: getSnapshotClient,
1043
+ SnapshotPlugin: SnapshotPlugin
1044
+ });
1045
+
1046
+ const GLOBAL_EXPECT = Symbol.for("expect-global");
1047
+ const MATCHERS_OBJECT = Symbol.for("matchers-object");
1048
+
1049
+ if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
1050
+ Object.defineProperty(globalThis, MATCHERS_OBJECT, {
1051
+ value: /* @__PURE__ */ new WeakMap()
1052
+ });
1053
+ }
1054
+ const getState = (expect) => globalThis[MATCHERS_OBJECT].get(expect);
1055
+ const setState = (state, expect) => {
1056
+ const map = globalThis[MATCHERS_OBJECT];
1057
+ const current = map.get(expect) || {};
1058
+ Object.assign(current, state);
1059
+ map.set(expect, current);
1060
+ };
1061
+ const JestChaiExpect = (chai, utils) => {
1062
+ function def(name, fn) {
1063
+ const addMethod = (n) => {
1064
+ utils.addMethod(chai.Assertion.prototype, n, fn);
1065
+ };
1066
+ if (Array.isArray(name))
1067
+ name.forEach((n) => addMethod(n));
1068
+ else
1069
+ addMethod(name);
1070
+ }
1071
+ ["throw", "throws", "Throw"].forEach((m) => {
1072
+ utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => {
1073
+ return function(...args) {
1074
+ const promise = utils.flag(this, "promise");
1075
+ const object = utils.flag(this, "object");
1076
+ const isNot = utils.flag(this, "negate");
1077
+ if (promise === "rejects") {
1078
+ utils.flag(this, "object", () => {
1079
+ throw object;
1080
+ });
1081
+ } else if (promise === "resolves" && typeof object !== "function") {
1082
+ if (!isNot) {
1083
+ const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
1084
+ const error = {
1085
+ showDiff: false
1086
+ };
1087
+ throw new AssertionError(message, error, utils.flag(this, "ssfi"));
1088
+ } else {
1089
+ return;
1090
+ }
1091
+ }
1092
+ _super.apply(this, args);
1093
+ };
1094
+ });
1095
+ });
1096
+ def("withTest", function(test) {
1097
+ utils.flag(this, "vitest-test", test);
1098
+ return this;
1099
+ });
1100
+ def("toEqual", function(expected) {
1101
+ const actual = utils.flag(this, "object");
1102
+ const equal = equals(actual, expected, [iterableEquality]);
1103
+ return this.assert(equal, "expected #{this} to deeply equal #{exp}", "expected #{this} to not deeply equal #{exp}", expected, actual);
1104
+ });
1105
+ def("toStrictEqual", function(expected) {
1106
+ const obj = utils.flag(this, "object");
1107
+ const equal = equals(obj, expected, [
1108
+ iterableEquality,
1109
+ typeEquality,
1110
+ sparseArrayEquality,
1111
+ arrayBufferEquality
1112
+ ], true);
1113
+ return this.assert(equal, "expected #{this} to strictly equal #{exp}", "expected #{this} to not strictly equal #{exp}", expected, obj);
1114
+ });
1115
+ def("toBe", function(expected) {
1116
+ const actual = this._obj;
1117
+ const pass = Object.is(actual, expected);
1118
+ let deepEqualityName = "";
1119
+ if (!pass) {
1120
+ const toStrictEqualPass = equals(actual, expected, [
1121
+ iterableEquality,
1122
+ typeEquality,
1123
+ sparseArrayEquality,
1124
+ arrayBufferEquality
1125
+ ], true);
1126
+ if (toStrictEqualPass) {
1127
+ deepEqualityName = "toStrictEqual";
1128
+ } else {
1129
+ const toEqualPass = equals(actual, expected, [iterableEquality]);
1130
+ if (toEqualPass)
1131
+ deepEqualityName = "toEqual";
1132
+ }
1133
+ }
1134
+ return this.assert(pass, generateToBeMessage(deepEqualityName), "expected #{this} not to be #{exp} // Object.is equality", expected, actual);
1135
+ });
1136
+ def("toMatchObject", function(expected) {
1137
+ const actual = this._obj;
1138
+ return this.assert(equals(actual, expected, [iterableEquality, subsetEquality]), "expected #{this} to match object #{exp}", "expected #{this} to not match object #{exp}", expected, actual);
1139
+ });
1140
+ def("toMatch", function(expected) {
1141
+ if (typeof expected === "string")
1142
+ return this.include(expected);
1143
+ else
1144
+ return this.match(expected);
1145
+ });
1146
+ def("toContain", function(item) {
1147
+ return this.contain(item);
1148
+ });
1149
+ def("toContainEqual", function(expected) {
1150
+ const obj = utils.flag(this, "object");
1151
+ const index = Array.from(obj).findIndex((item) => {
1152
+ return equals(item, expected);
1153
+ });
1154
+ this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected);
1155
+ });
1156
+ def("toBeTruthy", function() {
1157
+ const obj = utils.flag(this, "object");
1158
+ this.assert(Boolean(obj), "expected #{this} to be truthy", "expected #{this} to not be truthy", obj);
1159
+ });
1160
+ def("toBeFalsy", function() {
1161
+ const obj = utils.flag(this, "object");
1162
+ this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", obj);
1163
+ });
1164
+ def("toBeGreaterThan", function(expected) {
1165
+ const actual = this._obj;
1166
+ assertTypes(actual, "actual", ["number", "bigint"]);
1167
+ assertTypes(expected, "expected", ["number", "bigint"]);
1168
+ return this.assert(actual > expected, `expected ${actual} to be greater than ${expected}`, `expected ${actual} to be not greater than ${expected}`, actual, expected);
1169
+ });
1170
+ def("toBeGreaterThanOrEqual", function(expected) {
1171
+ const actual = this._obj;
1172
+ assertTypes(actual, "actual", ["number", "bigint"]);
1173
+ assertTypes(expected, "expected", ["number", "bigint"]);
1174
+ return this.assert(actual >= expected, `expected ${actual} to be greater than or equal to ${expected}`, `expected ${actual} to be not greater than or equal to ${expected}`, actual, expected);
1175
+ });
1176
+ def("toBeLessThan", function(expected) {
1177
+ const actual = this._obj;
1178
+ assertTypes(actual, "actual", ["number", "bigint"]);
1179
+ assertTypes(expected, "expected", ["number", "bigint"]);
1180
+ return this.assert(actual < expected, `expected ${actual} to be less than ${expected}`, `expected ${actual} to be not less than ${expected}`, actual, expected);
1181
+ });
1182
+ def("toBeLessThanOrEqual", function(expected) {
1183
+ const actual = this._obj;
1184
+ assertTypes(actual, "actual", ["number", "bigint"]);
1185
+ assertTypes(expected, "expected", ["number", "bigint"]);
1186
+ return this.assert(actual <= expected, `expected ${actual} to be less than or equal to ${expected}`, `expected ${actual} to be not less than or equal to ${expected}`, actual, expected);
1187
+ });
1188
+ def("toBeNaN", function() {
1189
+ return this.be.NaN;
1190
+ });
1191
+ def("toBeUndefined", function() {
1192
+ return this.be.undefined;
1193
+ });
1194
+ def("toBeNull", function() {
1195
+ return this.be.null;
1196
+ });
1197
+ def("toBeDefined", function() {
1198
+ const negate = utils.flag(this, "negate");
1199
+ utils.flag(this, "negate", false);
1200
+ if (negate)
1201
+ return this.be.undefined;
1202
+ return this.not.be.undefined;
1203
+ });
1204
+ def("toBeTypeOf", function(expected) {
1205
+ const actual = typeof this._obj;
1206
+ const equal = expected === actual;
1207
+ return this.assert(equal, "expected #{this} to be type of #{exp}", "expected #{this} not to be type of #{exp}", expected, actual);
1208
+ });
1209
+ def("toBeInstanceOf", function(obj) {
1210
+ return this.instanceOf(obj);
1211
+ });
1212
+ def("toHaveLength", function(length) {
1213
+ return this.have.length(length);
1214
+ });
1215
+ def("toHaveProperty", function(...args) {
1216
+ if (Array.isArray(args[0]))
1217
+ args[0] = args[0].map((key) => key.replace(/([.[\]])/g, "\\$1")).join(".");
1218
+ const actual = this._obj;
1219
+ const [propertyName, expected] = args;
1220
+ const { value, exists } = utils.getPathInfo(actual, propertyName);
1221
+ const pass = exists && (args.length === 1 || equals(expected, value));
1222
+ return this.assert(pass, "expected #{this} to have property #{exp}", "expected #{this} to not have property #{exp}", expected, actual);
1223
+ });
1224
+ def("toBeCloseTo", function(received, precision = 2) {
1225
+ const expected = this._obj;
1226
+ let pass = false;
1227
+ let expectedDiff = 0;
1228
+ let receivedDiff = 0;
1229
+ if (received === Infinity && expected === Infinity) {
1230
+ pass = true;
1231
+ } else if (received === -Infinity && expected === -Infinity) {
1232
+ pass = true;
1233
+ } else {
1234
+ expectedDiff = 10 ** -precision / 2;
1235
+ receivedDiff = Math.abs(expected - received);
1236
+ pass = receivedDiff < expectedDiff;
1237
+ }
1238
+ return this.assert(pass, `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, received, expected);
1239
+ });
1240
+ const assertIsMock = (assertion) => {
1241
+ if (!isMockFunction(assertion._obj))
1242
+ throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
1243
+ };
1244
+ const getSpy = (assertion) => {
1245
+ assertIsMock(assertion);
1246
+ return assertion._obj;
1247
+ };
1248
+ const ordinalOf = (i) => {
1249
+ const j = i % 10;
1250
+ const k = i % 100;
1251
+ if (j === 1 && k !== 11)
1252
+ return `${i}st`;
1253
+ if (j === 2 && k !== 12)
1254
+ return `${i}nd`;
1255
+ if (j === 3 && k !== 13)
1256
+ return `${i}rd`;
1257
+ return `${i}th`;
1258
+ };
1259
+ const formatCalls = (spy, msg, actualCall) => {
1260
+ msg += picocolors.exports.gray(`
1261
+
1262
+ Received:
1263
+ ${spy.mock.calls.map((callArg, i) => {
1264
+ let methodCall = picocolors.exports.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:
1265
+
1266
+ `);
1267
+ if (actualCall)
1268
+ methodCall += unifiedDiff(stringify(callArg), stringify(actualCall), { showLegend: false });
1269
+ else
1270
+ methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n");
1271
+ methodCall += "\n";
1272
+ return methodCall;
1273
+ }).join("\n")}`);
1274
+ msg += picocolors.exports.gray(`
1275
+
1276
+ Number of calls: ${picocolors.exports.bold(spy.mock.calls.length)}
1277
+ `);
1278
+ return msg;
1279
+ };
1280
+ def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
1281
+ const spy = getSpy(this);
1282
+ const spyName = spy.getMockName();
1283
+ const callCount = spy.mock.calls.length;
1284
+ return this.assert(callCount === number, `expected "${spyName}" to be called #{exp} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount);
1285
+ });
1286
+ def("toHaveBeenCalledOnce", function() {
1287
+ const spy = getSpy(this);
1288
+ const spyName = spy.getMockName();
1289
+ const callCount = spy.mock.calls.length;
1290
+ return this.assert(callCount === 1, `expected "${spyName}" to be called once`, `expected "${spyName}" to not be called once`, 1, callCount);
1291
+ });
1292
+ def(["toHaveBeenCalled", "toBeCalled"], function() {
1293
+ const spy = getSpy(this);
1294
+ const spyName = spy.getMockName();
1295
+ const called = spy.mock.calls.length > 0;
1296
+ const isNot = utils.flag(this, "negate");
1297
+ let msg = utils.getMessage(this, [
1298
+ called,
1299
+ `expected "${spyName}" to be called at least once`,
1300
+ `expected "${spyName}" to not be called at all`,
1301
+ true,
1302
+ called
1303
+ ]);
1304
+ if (called && isNot)
1305
+ msg += formatCalls(spy, msg);
1306
+ if (called && isNot || !called && !isNot) {
1307
+ const err = new Error(msg);
1308
+ err.name = "AssertionError";
1309
+ throw err;
1310
+ }
1311
+ });
1312
+ def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
1313
+ const spy = getSpy(this);
1314
+ const spyName = spy.getMockName();
1315
+ const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [iterableEquality]));
1316
+ const isNot = utils.flag(this, "negate");
1317
+ let msg = utils.getMessage(this, [
1318
+ pass,
1319
+ `expected "${spyName}" to be called with arguments: #{exp}`,
1320
+ `expected "${spyName}" to not be called with arguments: #{exp}`,
1321
+ args
1322
+ ]);
1323
+ if (pass && isNot || !pass && !isNot) {
1324
+ msg += formatCalls(spy, msg, args);
1325
+ const err = new Error(msg);
1326
+ err.name = "AssertionError";
1327
+ throw err;
1328
+ }
1329
+ });
1330
+ def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
1331
+ const spy = getSpy(this);
1332
+ const spyName = spy.getMockName();
1333
+ const nthCall = spy.mock.calls[times - 1];
1334
+ this.assert(equals(nthCall, args, [iterableEquality]), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall);
1335
+ });
1336
+ def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
1337
+ const spy = getSpy(this);
1338
+ const spyName = spy.getMockName();
1339
+ const lastCall = spy.mock.calls[spy.calls.length - 1];
1340
+ this.assert(equals(lastCall, args, [iterableEquality]), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall);
1341
+ });
1342
+ def(["toThrow", "toThrowError"], function(expected) {
1343
+ if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp)
1344
+ return this.throws(expected);
1345
+ const obj = this._obj;
1346
+ const promise = utils.flag(this, "promise");
1347
+ const isNot = utils.flag(this, "negate");
1348
+ let thrown = null;
1349
+ if (promise === "rejects") {
1350
+ thrown = obj;
1351
+ } else if (promise === "resolves" && typeof obj !== "function") {
1352
+ if (!isNot) {
1353
+ const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
1354
+ const error = {
1355
+ showDiff: false
1356
+ };
1357
+ throw new AssertionError(message, error, utils.flag(this, "ssfi"));
1358
+ } else {
1359
+ return;
1360
+ }
1361
+ } else {
1362
+ try {
1363
+ obj();
1364
+ } catch (err) {
1365
+ thrown = err;
1366
+ }
1367
+ }
1368
+ if (typeof expected === "function") {
1369
+ const name = expected.name || expected.prototype.constructor.name;
1370
+ return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown);
1371
+ }
1372
+ if (expected instanceof Error) {
1373
+ return this.assert(thrown && expected.message === thrown.message, `expected error to have message: ${expected.message}`, `expected error not to have message: ${expected.message}`, expected.message, thrown && thrown.message);
1374
+ }
1375
+ if (typeof expected.asymmetricMatch === "function") {
1376
+ const matcher = expected;
1377
+ return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher.toString(), thrown);
1378
+ }
1379
+ throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`);
1380
+ });
1381
+ def(["toHaveReturned", "toReturn"], function() {
1382
+ const spy = getSpy(this);
1383
+ const spyName = spy.getMockName();
1384
+ const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === "throw");
1385
+ this.assert(calledAndNotThrew, `expected "${spyName}" to be successfully called at least once`, `expected "${spyName}" to not be successfully called`, calledAndNotThrew, !calledAndNotThrew);
1386
+ });
1387
+ def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
1388
+ const spy = getSpy(this);
1389
+ const spyName = spy.getMockName();
1390
+ const successfulReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0);
1391
+ this.assert(successfulReturns === times, `expected "${spyName}" to be successfully called ${times} times`, `expected "${spyName}" to not be successfully called ${times} times`, `expected number of returns: ${times}`, `received number of returns: ${successfulReturns}`);
1392
+ });
1393
+ def(["toHaveReturnedWith", "toReturnWith"], function(value) {
1394
+ const spy = getSpy(this);
1395
+ const spyName = spy.getMockName();
1396
+ const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result));
1397
+ this.assert(pass, `expected "${spyName}" to be successfully called with #{exp}`, `expected "${spyName}" to not be successfully called with #{exp}`, value);
1398
+ });
1399
+ def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
1400
+ const spy = getSpy(this);
1401
+ const spyName = spy.getMockName();
1402
+ const { value: lastResult } = spy.mock.results[spy.returns.length - 1];
1403
+ const pass = equals(lastResult, value);
1404
+ this.assert(pass, `expected last "${spyName}" call to return #{exp}`, `expected last "${spyName}" call to not return #{exp}`, value, lastResult);
1405
+ });
1406
+ def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) {
1407
+ const spy = getSpy(this);
1408
+ const spyName = spy.getMockName();
1409
+ const isNot = utils.flag(this, "negate");
1410
+ const { type: callType, value: callResult } = spy.mock.results[nthCall - 1];
1411
+ const ordinalCall = `${ordinalOf(nthCall)} call`;
1412
+ if (!isNot && callType === "throw")
1413
+ chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
1414
+ const nthCallReturn = equals(callResult, value);
1415
+ this.assert(nthCallReturn, `expected ${ordinalCall} "${spyName}" call to return #{exp}`, `expected ${ordinalCall} "${spyName}" call to not return #{exp}`, value, callResult);
1416
+ });
1417
+ def("toSatisfy", function(matcher, message) {
1418
+ return this.be.satisfy(matcher, message);
1419
+ });
1420
+ utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() {
1421
+ utils.flag(this, "promise", "resolves");
1422
+ utils.flag(this, "error", new Error("resolves"));
1423
+ const obj = utils.flag(this, "object");
1424
+ if (typeof (obj == null ? void 0 : obj.then) !== "function")
1425
+ throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
1426
+ const proxy = new Proxy(this, {
1427
+ get: (target, key, receiver) => {
1428
+ const result = Reflect.get(target, key, receiver);
1429
+ if (typeof result !== "function")
1430
+ return result instanceof chai.Assertion ? proxy : result;
1431
+ return async (...args) => {
1432
+ return obj.then((value) => {
1433
+ utils.flag(this, "object", value);
1434
+ return result.call(this, ...args);
1435
+ }, (err) => {
1436
+ throw new Error(`promise rejected "${toString(err)}" instead of resolving`);
1437
+ });
1438
+ };
1439
+ }
1440
+ });
1441
+ return proxy;
1442
+ });
1443
+ utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() {
1444
+ utils.flag(this, "promise", "rejects");
1445
+ utils.flag(this, "error", new Error("rejects"));
1446
+ const obj = utils.flag(this, "object");
1447
+ const wrapper = typeof obj === "function" ? obj() : obj;
1448
+ if (typeof (wrapper == null ? void 0 : wrapper.then) !== "function")
1449
+ throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
1450
+ const proxy = new Proxy(this, {
1451
+ get: (target, key, receiver) => {
1452
+ const result = Reflect.get(target, key, receiver);
1453
+ if (typeof result !== "function")
1454
+ return result instanceof chai.Assertion ? proxy : result;
1455
+ return async (...args) => {
1456
+ return wrapper.then((value) => {
1457
+ throw new Error(`promise resolved "${toString(value)}" instead of rejecting`);
1458
+ }, (err) => {
1459
+ utils.flag(this, "object", err);
1460
+ return result.call(this, ...args);
1461
+ });
1462
+ };
1463
+ }
1464
+ });
1465
+ return proxy;
1466
+ });
1467
+ utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
1468
+ };
1469
+ function toString(value) {
1470
+ try {
1471
+ return `${value}`;
1472
+ } catch (_error) {
1473
+ return "unknown";
1474
+ }
1475
+ }
1476
+
1477
+ class AsymmetricMatcher {
1478
+ constructor(sample, inverse = false) {
1479
+ this.sample = sample;
1480
+ this.inverse = inverse;
1481
+ this.$$typeof = Symbol.for("jest.asymmetricMatcher");
1482
+ }
1483
+ getMatcherContext(expect) {
1484
+ return {
1485
+ ...getState(expect || globalThis[GLOBAL_EXPECT]),
1486
+ equals,
1487
+ isNot: this.inverse,
1488
+ utils: matcherUtils
1489
+ };
1490
+ }
1491
+ }
1492
+ class StringContaining extends AsymmetricMatcher {
1493
+ constructor(sample, inverse = false) {
1494
+ if (!isA("String", sample))
1495
+ throw new Error("Expected is not a string");
1496
+ super(sample, inverse);
1497
+ }
1498
+ asymmetricMatch(other) {
1499
+ const result = isA("String", other) && other.includes(this.sample);
1500
+ return this.inverse ? !result : result;
1501
+ }
1502
+ toString() {
1503
+ return `String${this.inverse ? "Not" : ""}Containing`;
1504
+ }
1505
+ getExpectedType() {
1506
+ return "string";
1507
+ }
1508
+ }
1509
+ class Anything extends AsymmetricMatcher {
1510
+ asymmetricMatch(other) {
1511
+ return other != null;
1512
+ }
1513
+ toString() {
1514
+ return "Anything";
1515
+ }
1516
+ toAsymmetricMatcher() {
1517
+ return "Anything";
1518
+ }
1519
+ }
1520
+ class ObjectContaining extends AsymmetricMatcher {
1521
+ constructor(sample, inverse = false) {
1522
+ super(sample, inverse);
1523
+ }
1524
+ getPrototype(obj) {
1525
+ if (Object.getPrototypeOf)
1526
+ return Object.getPrototypeOf(obj);
1527
+ if (obj.constructor.prototype === obj)
1528
+ return null;
1529
+ return obj.constructor.prototype;
1530
+ }
1531
+ hasProperty(obj, property) {
1532
+ if (!obj)
1533
+ return false;
1534
+ if (Object.prototype.hasOwnProperty.call(obj, property))
1535
+ return true;
1536
+ return this.hasProperty(this.getPrototype(obj), property);
1537
+ }
1538
+ asymmetricMatch(other) {
1539
+ if (typeof this.sample !== "object") {
1540
+ throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`);
1541
+ }
1542
+ let result = true;
1543
+ for (const property in this.sample) {
1544
+ if (!this.hasProperty(other, property) || !equals(this.sample[property], other[property])) {
1545
+ result = false;
1546
+ break;
1547
+ }
1548
+ }
1549
+ return this.inverse ? !result : result;
1550
+ }
1551
+ toString() {
1552
+ return `Object${this.inverse ? "Not" : ""}Containing`;
1553
+ }
1554
+ getExpectedType() {
1555
+ return "object";
1556
+ }
1557
+ }
1558
+ class ArrayContaining extends AsymmetricMatcher {
1559
+ constructor(sample, inverse = false) {
1560
+ super(sample, inverse);
1561
+ }
1562
+ asymmetricMatch(other) {
1563
+ if (!Array.isArray(this.sample)) {
1564
+ throw new TypeError(`You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`);
1565
+ }
1566
+ const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every((item) => other.some((another) => equals(item, another)));
1567
+ return this.inverse ? !result : result;
1568
+ }
1569
+ toString() {
1570
+ return `Array${this.inverse ? "Not" : ""}Containing`;
1571
+ }
1572
+ getExpectedType() {
1573
+ return "array";
1574
+ }
1575
+ }
1576
+ class Any extends AsymmetricMatcher {
1577
+ constructor(sample) {
1578
+ if (typeof sample === "undefined") {
1579
+ throw new TypeError("any() expects to be passed a constructor function. Please pass one or use anything() to match any object.");
1580
+ }
1581
+ super(sample);
1582
+ }
1583
+ fnNameFor(func) {
1584
+ if (func.name)
1585
+ return func.name;
1586
+ const functionToString = Function.prototype.toString;
1587
+ const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
1588
+ return matches ? matches[1] : "<anonymous>";
1589
+ }
1590
+ asymmetricMatch(other) {
1591
+ if (this.sample === String)
1592
+ return typeof other == "string" || other instanceof String;
1593
+ if (this.sample === Number)
1594
+ return typeof other == "number" || other instanceof Number;
1595
+ if (this.sample === Function)
1596
+ return typeof other == "function" || other instanceof Function;
1597
+ if (this.sample === Boolean)
1598
+ return typeof other == "boolean" || other instanceof Boolean;
1599
+ if (this.sample === BigInt)
1600
+ return typeof other == "bigint" || other instanceof BigInt;
1601
+ if (this.sample === Symbol)
1602
+ return typeof other == "symbol" || other instanceof Symbol;
1603
+ if (this.sample === Object)
1604
+ return typeof other == "object";
1605
+ return other instanceof this.sample;
1606
+ }
1607
+ toString() {
1608
+ return "Any";
1609
+ }
1610
+ getExpectedType() {
1611
+ if (this.sample === String)
1612
+ return "string";
1613
+ if (this.sample === Number)
1614
+ return "number";
1615
+ if (this.sample === Function)
1616
+ return "function";
1617
+ if (this.sample === Object)
1618
+ return "object";
1619
+ if (this.sample === Boolean)
1620
+ return "boolean";
1621
+ return this.fnNameFor(this.sample);
1622
+ }
1623
+ toAsymmetricMatcher() {
1624
+ return `Any<${this.fnNameFor(this.sample)}>`;
1625
+ }
1626
+ }
1627
+ class StringMatching extends AsymmetricMatcher {
1628
+ constructor(sample, inverse = false) {
1629
+ if (!isA("String", sample) && !isA("RegExp", sample))
1630
+ throw new Error("Expected is not a String or a RegExp");
1631
+ super(new RegExp(sample), inverse);
1632
+ }
1633
+ asymmetricMatch(other) {
1634
+ const result = isA("String", other) && this.sample.test(other);
1635
+ return this.inverse ? !result : result;
1636
+ }
1637
+ toString() {
1638
+ return `String${this.inverse ? "Not" : ""}Matching`;
1639
+ }
1640
+ getExpectedType() {
1641
+ return "string";
1642
+ }
1643
+ }
1644
+ const JestAsymmetricMatchers = (chai, utils) => {
1645
+ utils.addMethod(chai.expect, "anything", () => new Anything());
1646
+ utils.addMethod(chai.expect, "any", (expected) => new Any(expected));
1647
+ utils.addMethod(chai.expect, "stringContaining", (expected) => new StringContaining(expected));
1648
+ utils.addMethod(chai.expect, "objectContaining", (expected) => new ObjectContaining(expected));
1649
+ utils.addMethod(chai.expect, "arrayContaining", (expected) => new ArrayContaining(expected));
1650
+ utils.addMethod(chai.expect, "stringMatching", (expected) => new StringMatching(expected));
1651
+ chai.expect.not = {
1652
+ stringContaining: (expected) => new StringContaining(expected, true),
1653
+ objectContaining: (expected) => new ObjectContaining(expected, true),
1654
+ arrayContaining: (expected) => new ArrayContaining(expected, true),
1655
+ stringMatching: (expected) => new StringMatching(expected, true)
1656
+ };
1657
+ };
1658
+
1659
+ const isAsyncFunction = (fn) => typeof fn === "function" && fn[Symbol.toStringTag] === "AsyncFunction";
1660
+ const getMatcherState = (assertion, expect) => {
1661
+ const obj = assertion._obj;
1662
+ const isNot = util.flag(assertion, "negate");
1663
+ const promise = util.flag(assertion, "promise") || "";
1664
+ const jestUtils = {
1665
+ ...matcherUtils,
1666
+ iterableEquality,
1667
+ subsetEquality
1668
+ };
1669
+ const matcherState = {
1670
+ ...getState(expect),
1671
+ isNot,
1672
+ utils: jestUtils,
1673
+ promise,
1674
+ equals,
1675
+ suppressedErrors: [],
1676
+ snapshotState: getSnapshotClient().snapshotState
1677
+ };
1678
+ return {
1679
+ state: matcherState,
1680
+ isNot,
1681
+ obj
1682
+ };
1683
+ };
1684
+ class JestExtendError extends Error {
1685
+ constructor(message, actual, expected) {
1686
+ super(message);
1687
+ this.actual = actual;
1688
+ this.expected = expected;
1689
+ }
1690
+ }
1691
+ function JestExtendPlugin(expect, matchers) {
1692
+ return (c, utils) => {
1693
+ Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
1694
+ function expectSyncWrapper(...args) {
1695
+ const { state, isNot, obj } = getMatcherState(this, expect);
1696
+ const { pass, message, actual, expected } = expectAssertion.call(state, obj, ...args);
1697
+ if (pass && isNot || !pass && !isNot)
1698
+ throw new JestExtendError(message(), actual, expected);
1699
+ }
1700
+ async function expectAsyncWrapper(...args) {
1701
+ const { state, isNot, obj } = getMatcherState(this, expect);
1702
+ const { pass, message, actual, expected } = await expectAssertion.call(state, obj, ...args);
1703
+ if (pass && isNot || !pass && !isNot)
1704
+ throw new JestExtendError(message(), actual, expected);
1705
+ }
1706
+ const expectAssertionWrapper = isAsyncFunction(expectAssertion) ? expectAsyncWrapper : expectSyncWrapper;
1707
+ utils.addMethod(c.Assertion.prototype, expectAssertionName, expectAssertionWrapper);
1708
+ class CustomMatcher extends AsymmetricMatcher {
1709
+ constructor(inverse = false, ...sample) {
1710
+ super(sample, inverse);
1711
+ }
1712
+ asymmetricMatch(other) {
1713
+ const { pass } = expectAssertion.call(this.getMatcherContext(expect), other, ...this.sample);
1714
+ return this.inverse ? !pass : pass;
1715
+ }
1716
+ toString() {
1717
+ return `${this.inverse ? "not." : ""}${expectAssertionName}`;
1718
+ }
1719
+ getExpectedType() {
1720
+ return "any";
1721
+ }
1722
+ toAsymmetricMatcher() {
1723
+ return `${this.toString()}<${this.sample.map(String).join(", ")}>`;
1724
+ }
1725
+ }
1726
+ Object.defineProperty(expect, expectAssertionName, {
1727
+ configurable: true,
1728
+ enumerable: true,
1729
+ value: (...sample) => new CustomMatcher(false, ...sample),
1730
+ writable: true
1731
+ });
1732
+ Object.defineProperty(expect.not, expectAssertionName, {
1733
+ configurable: true,
1734
+ enumerable: true,
1735
+ value: (...sample) => new CustomMatcher(true, ...sample),
1736
+ writable: true
1737
+ });
1738
+ });
1739
+ };
1740
+ }
1741
+ const JestExtend = (chai, utils) => {
1742
+ utils.addMethod(chai.expect, "extend", (expect, expects) => {
1743
+ chai.use(JestExtendPlugin(expect, expects));
1744
+ });
1745
+ };
1746
+
1747
+ chai$2.use(JestExtend);
1748
+ chai$2.use(JestChaiExpect);
1749
+ chai$2.use(Subset);
1750
+ chai$2.use(SnapshotPlugin);
1751
+ chai$2.use(JestAsymmetricMatchers);
1752
+
1753
+ function createExpect(test) {
1754
+ var _a;
1755
+ const expect = (value, message) => {
1756
+ const { assertionCalls } = getState(expect);
1757
+ setState({ assertionCalls: assertionCalls + 1 }, expect);
1758
+ const assert2 = chai$2.expect(value, message);
1759
+ if (test)
1760
+ return assert2.withTest(test);
1761
+ else
1762
+ return assert2;
1763
+ };
1764
+ Object.assign(expect, chai$2.expect);
1765
+ expect.getState = () => getState(expect);
1766
+ expect.setState = (state) => setState(state, expect);
1767
+ setState({
1768
+ assertionCalls: 0,
1769
+ isExpectingAssertions: false,
1770
+ isExpectingAssertionsError: null,
1771
+ expectedAssertionsNumber: null,
1772
+ expectedAssertionsNumberErrorGen: null,
1773
+ testPath: (_a = test == null ? void 0 : test.suite.file) == null ? void 0 : _a.filepath,
1774
+ currentTestName: test ? getFullName(test) : void 0
1775
+ }, expect);
1776
+ expect.extend = (matchers) => chai$2.expect.extend(expect, matchers);
1777
+ function assertions(expected) {
1778
+ const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
1779
+ if (Error.captureStackTrace)
1780
+ Error.captureStackTrace(errorGen(), assertions);
1781
+ expect.setState({
1782
+ expectedAssertionsNumber: expected,
1783
+ expectedAssertionsNumberErrorGen: errorGen
1784
+ });
1785
+ }
1786
+ function hasAssertions() {
1787
+ const error = new Error("expected any number of assertion, but got none");
1788
+ if (Error.captureStackTrace)
1789
+ Error.captureStackTrace(error, hasAssertions);
1790
+ expect.setState({
1791
+ isExpectingAssertions: true,
1792
+ isExpectingAssertionsError: error
1793
+ });
1794
+ }
1795
+ chai$2.util.addMethod(expect, "assertions", assertions);
1796
+ chai$2.util.addMethod(expect, "hasAssertions", hasAssertions);
1797
+ return expect;
1798
+ }
1799
+ const globalExpect = createExpect();
1800
+ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
1801
+ value: globalExpect,
1802
+ writable: true,
1803
+ configurable: true
1804
+ });
1805
+
1806
+ const collectorContext = {
1807
+ tasks: [],
1808
+ currentSuite: null
1809
+ };
1810
+ function collectTask(task) {
1811
+ var _a;
1812
+ (_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task);
1813
+ }
1814
+ async function runWithSuite(suite, fn) {
1815
+ const prev = collectorContext.currentSuite;
1816
+ collectorContext.currentSuite = suite;
1817
+ await fn();
1818
+ collectorContext.currentSuite = prev;
1819
+ }
1820
+ function getDefaultTestTimeout() {
1821
+ return getWorkerState().config.testTimeout;
1822
+ }
1823
+ function getDefaultHookTimeout() {
1824
+ return getWorkerState().config.hookTimeout;
1825
+ }
1826
+ function withTimeout(fn, timeout = getDefaultTestTimeout(), isHook = false) {
1827
+ if (timeout <= 0 || timeout === Infinity)
1828
+ return fn;
1829
+ return (...args) => {
1830
+ return Promise.race([fn(...args), new Promise((resolve, reject) => {
1831
+ var _a;
1832
+ const timer = safeSetTimeout(() => {
1833
+ safeClearTimeout(timer);
1834
+ reject(new Error(makeTimeoutMsg(isHook, timeout)));
1835
+ }, timeout);
1836
+ (_a = timer.unref) == null ? void 0 : _a.call(timer);
1837
+ })]);
1838
+ };
1839
+ }
1840
+ function createTestContext(test) {
1841
+ const context = function() {
1842
+ throw new Error("done() callback is deprecated, use promise instead");
1843
+ };
1844
+ context.meta = test;
1845
+ let _expect;
1846
+ Object.defineProperty(context, "expect", {
1847
+ get() {
1848
+ if (!_expect)
1849
+ _expect = createExpect(test);
1850
+ return _expect;
1851
+ }
1852
+ });
1853
+ Object.defineProperty(context, "_local", {
1854
+ get() {
1855
+ return _expect != null;
1856
+ }
1857
+ });
1858
+ return context;
1859
+ }
1860
+ function makeTimeoutMsg(isHook, timeout) {
1861
+ return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
1862
+ If this is a long-running test, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
1863
+ }
1864
+
1865
+ const fnMap = /* @__PURE__ */ new WeakMap();
1866
+ const hooksMap = /* @__PURE__ */ new WeakMap();
1867
+ function setFn(key, fn) {
1868
+ fnMap.set(key, fn);
1869
+ }
1870
+ function getFn(key) {
1871
+ return fnMap.get(key);
1872
+ }
1873
+ function setHooks(key, hooks) {
1874
+ hooksMap.set(key, hooks);
1875
+ }
1876
+ function getHooks(key) {
1877
+ return hooksMap.get(key);
1878
+ }
1879
+
1880
+ const suite = createSuite();
1881
+ const test = createTest(function(name, fn, timeout) {
1882
+ getCurrentSuite().test.fn.call(this, name, fn, timeout);
1883
+ });
1884
+ function formatTitle(template, items, idx) {
1885
+ if (template.includes("%#")) {
1886
+ template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%");
1887
+ }
1888
+ const count = template.split("%").length - 1;
1889
+ let formatted = util$1.format(template, ...items.slice(0, count));
1890
+ if (isObject(items[0])) {
1891
+ formatted = formatted.replace(/\$([$\w_]+)/g, (_, key) => {
1892
+ return items[0][key];
1893
+ });
1894
+ }
1895
+ return formatted;
1896
+ }
1897
+ const describe = suite;
1898
+ const it = test;
1899
+ const workerState = getWorkerState();
1900
+ const defaultSuite = workerState.config.sequence.shuffle ? suite.shuffle("") : suite("");
1901
+ function clearCollectorContext() {
1902
+ collectorContext.tasks.length = 0;
1903
+ defaultSuite.clear();
1904
+ collectorContext.currentSuite = defaultSuite;
1905
+ }
1906
+ function getCurrentSuite() {
1907
+ return collectorContext.currentSuite || defaultSuite;
1908
+ }
1909
+ function createSuiteHooks() {
1910
+ return {
1911
+ beforeAll: [],
1912
+ afterAll: [],
1913
+ beforeEach: [],
1914
+ afterEach: []
1915
+ };
1916
+ }
1917
+ function createSuiteCollector(name, factory = () => {
1918
+ }, mode, concurrent, shuffle) {
1919
+ const tasks = [];
1920
+ const factoryQueue = [];
1921
+ let suite2;
1922
+ initSuite();
1923
+ const test2 = createTest(function(name2, fn = noop, timeout) {
1924
+ const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
1925
+ const test3 = {
1926
+ id: "",
1927
+ type: "test",
1928
+ name: name2,
1929
+ mode: mode2,
1930
+ suite: void 0,
1931
+ fails: this.fails
1932
+ };
1933
+ if (this.concurrent || concurrent)
1934
+ test3.concurrent = true;
1935
+ if (shuffle)
1936
+ test3.shuffle = true;
1937
+ const context = createTestContext(test3);
1938
+ Object.defineProperty(test3, "context", {
1939
+ value: context,
1940
+ enumerable: false
1941
+ });
1942
+ setFn(test3, withTimeout(() => fn(context), timeout));
1943
+ tasks.push(test3);
1944
+ });
1945
+ const collector = {
1946
+ type: "collector",
1947
+ name,
1948
+ mode,
1949
+ test: test2,
1950
+ tasks,
1951
+ collect,
1952
+ clear,
1953
+ on: addHook
1954
+ };
1955
+ function addHook(name2, ...fn) {
1956
+ getHooks(suite2)[name2].push(...fn);
1957
+ }
1958
+ function initSuite() {
1959
+ suite2 = {
1960
+ id: "",
1961
+ type: "suite",
1962
+ name,
1963
+ mode,
1964
+ shuffle,
1965
+ tasks: []
1966
+ };
1967
+ setHooks(suite2, createSuiteHooks());
1968
+ }
1969
+ function clear() {
1970
+ tasks.length = 0;
1971
+ factoryQueue.length = 0;
1972
+ initSuite();
1973
+ }
1974
+ async function collect(file) {
1975
+ factoryQueue.length = 0;
1976
+ if (factory)
1977
+ await runWithSuite(collector, () => factory(test2));
1978
+ const allChildren = [];
1979
+ for (const i of [...factoryQueue, ...tasks])
1980
+ allChildren.push(i.type === "collector" ? await i.collect(file) : i);
1981
+ suite2.file = file;
1982
+ suite2.tasks = allChildren;
1983
+ allChildren.forEach((task) => {
1984
+ task.suite = suite2;
1985
+ if (file)
1986
+ task.file = file;
1987
+ });
1988
+ return suite2;
1989
+ }
1990
+ collectTask(collector);
1991
+ return collector;
1992
+ }
1993
+ function createSuite() {
1994
+ const suite2 = createChainable(["concurrent", "shuffle", "skip", "only", "todo"], function(name, factory) {
1995
+ const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
1996
+ return createSuiteCollector(name, factory, mode, this.concurrent, this.shuffle);
1997
+ });
1998
+ suite2.each = (cases) => {
1999
+ return (name, fn) => {
2000
+ cases.forEach((i, idx) => {
2001
+ const items = Array.isArray(i) ? i : [i];
2002
+ suite2(formatTitle(name, items, idx), () => fn(...items));
2003
+ });
2004
+ };
2005
+ };
2006
+ suite2.skipIf = (condition) => condition ? suite2.skip : suite2;
2007
+ suite2.runIf = (condition) => condition ? suite2 : suite2.skip;
2008
+ return suite2;
2009
+ }
2010
+ function createTest(fn) {
2011
+ const test2 = createChainable(["concurrent", "skip", "only", "todo", "fails"], fn);
2012
+ test2.each = (cases) => {
2013
+ return (name, fn2) => {
2014
+ cases.forEach((i, idx) => {
2015
+ const items = Array.isArray(i) ? i : [i];
2016
+ test2(formatTitle(name, items, idx), () => fn2(...items));
2017
+ });
2018
+ };
2019
+ };
2020
+ test2.skipIf = (condition) => condition ? test2.skip : test2;
2021
+ test2.runIf = (condition) => condition ? test2 : test2.skip;
2022
+ return test2;
2023
+ }
2024
+
2025
+ export { GLOBAL_EXPECT as G, getDefaultHookTimeout as a, globalExpect as b, createExpect as c, describe as d, clearCollectorContext as e, defaultSuite as f, getCurrentSuite as g, setHooks as h, it as i, getHooks as j, collectorContext as k, setState as l, getFn as m, getState as n, createSuiteHooks as o, chai$1 as p, suite as s, test as t, withTimeout as w };