vitest 0.32.1 → 0.32.3

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 (42) hide show
  1. package/LICENSE.md +33 -4
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +22 -5
  4. package/dist/child.js +3 -3
  5. package/dist/{chunk-api-setup.05e3917b.js → chunk-api-setup.8f785c4a.js} +18 -11
  6. package/dist/{chunk-install-pkg.65daeadb.js → chunk-install-pkg.0716919d.js} +69 -55
  7. package/dist/{chunk-integrations-globals.a56dee90.js → chunk-integrations-globals.0093e2ed.js} +5 -5
  8. package/dist/{chunk-node-git.4c43bd73.js → chunk-node-git.c410fed8.js} +3 -2
  9. package/dist/cli-wrapper.js +2 -2
  10. package/dist/cli.js +8 -8
  11. package/dist/config.d.ts +1 -1
  12. package/dist/coverage.d.ts +1 -1
  13. package/dist/entry.js +9 -9
  14. package/dist/environments.d.ts +1 -1
  15. package/dist/environments.js +1 -1
  16. package/dist/index.d.ts +60 -40
  17. package/dist/index.js +6 -6
  18. package/dist/loader.js +140 -4
  19. package/dist/node.d.ts +3 -3
  20. package/dist/node.js +9 -9
  21. package/dist/runners.d.ts +1 -1
  22. package/dist/runners.js +24 -19
  23. package/dist/suite.d.ts +1 -0
  24. package/dist/{types-2b1c412e.d.ts → types-198fd1d9.d.ts} +302 -77
  25. package/dist/vendor-_commonjsHelpers.7d1333e8.js +7 -0
  26. package/dist/{vendor-cli-api.17011d0a.js → vendor-cli-api.ff679aa2.js} +281 -229
  27. package/dist/{vendor-coverage.de2180ed.js → vendor-coverage.2e41927a.js} +1 -1
  28. package/dist/{vendor-execute.001ae440.js → vendor-execute.3576af13.js} +14 -16
  29. package/dist/{vendor-index.c1e09929.js → vendor-index.1f85e5f1.js} +52 -39
  30. package/dist/{vendor-index.fad2598b.js → vendor-index.23ac4e13.js} +1 -1
  31. package/dist/{vendor-index.0f133dbe.js → vendor-index.2af39fbb.js} +5 -3
  32. package/dist/{vendor-index.fc98d30f.js → vendor-index.98139333.js} +4 -22
  33. package/dist/{vendor-index.87ab04c3.js → vendor-index.cc463d9e.js} +2 -1
  34. package/dist/{vendor-rpc.4d3d7a54.js → vendor-rpc.ad5b08c7.js} +10 -10
  35. package/dist/{vendor-run-once.69ce7172.js → vendor-run-once.1fa85ba7.js} +2 -2
  36. package/dist/vendor-vi.dd6706cb.js +3421 -0
  37. package/dist/worker.js +3 -3
  38. package/package.json +21 -22
  39. package/dist/vendor-_commonjsHelpers.76cdd49e.js +0 -3
  40. package/dist/vendor-setup.common.f1cf2231.js +0 -20
  41. package/dist/vendor-vi.74cf3ef7.js +0 -3354
  42. /package/dist/{vendor-index.75f2b63d.js → vendor-environments.75f2b63d.js} +0 -0
@@ -0,0 +1,3421 @@
1
+ import { getCurrentSuite, getCurrentTest } from '@vitest/runner';
2
+ import { createChainable, getNames } from '@vitest/runner/utils';
3
+ import { getSafeTimers, noop, assertTypes, createSimpleStackTrace, parseSingleStack } from '@vitest/utils';
4
+ import { i as isRunningInBenchmark, r as resetModules } from './vendor-index.23ac4e13.js';
5
+ import * as chai$1 from 'chai';
6
+ import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './vendor-_commonjsHelpers.7d1333e8.js';
7
+ import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT as GLOBAL_EXPECT$1, getState, setState } from '@vitest/expect';
8
+ import { SnapshotClient, stripSnapshotIndentation, addSerializer } from '@vitest/snapshot';
9
+ import '@vitest/utils/error';
10
+ import { g as getWorkerState, a as getCurrentEnvironment } from './vendor-global.6795f91f.js';
11
+ import { g as getFullName } from './vendor-tasks.f9d75aed.js';
12
+ import require$$2 from 'util';
13
+ import { spyOn, fn, isMockFunction, spies } from '@vitest/spy';
14
+
15
+ function waitNextTick() {
16
+ const { setTimeout } = getSafeTimers();
17
+ return new Promise((resolve) => setTimeout(resolve, 0));
18
+ }
19
+ async function waitForImportsToResolve() {
20
+ await waitNextTick();
21
+ const state = getWorkerState();
22
+ const promises = [];
23
+ let resolvingCount = 0;
24
+ for (const mod of state.moduleCache.values()) {
25
+ if (mod.promise && !mod.evaluated)
26
+ promises.push(mod.promise);
27
+ if (mod.resolving)
28
+ resolvingCount++;
29
+ }
30
+ if (!promises.length && !resolvingCount)
31
+ return;
32
+ await Promise.allSettled(promises);
33
+ await waitForImportsToResolve();
34
+ }
35
+
36
+ const benchFns = /* @__PURE__ */ new WeakMap();
37
+ const benchOptsMap = /* @__PURE__ */ new WeakMap();
38
+ function getBenchOptions(key) {
39
+ return benchOptsMap.get(key);
40
+ }
41
+ function getBenchFn(key) {
42
+ return benchFns.get(key);
43
+ }
44
+ const bench = createBenchmark(
45
+ function(name, fn = noop, options = {}) {
46
+ if (!isRunningInBenchmark())
47
+ throw new Error("`bench()` is only available in benchmark mode.");
48
+ const task = getCurrentSuite().custom.call(this, formatName(name));
49
+ task.meta = {
50
+ benchmark: true
51
+ };
52
+ benchFns.set(task, fn);
53
+ benchOptsMap.set(task, options);
54
+ }
55
+ );
56
+ function createBenchmark(fn) {
57
+ const benchmark = createChainable(
58
+ ["skip", "only", "todo"],
59
+ fn
60
+ );
61
+ benchmark.skipIf = (condition) => condition ? benchmark.skip : benchmark;
62
+ benchmark.runIf = (condition) => condition ? benchmark : benchmark.skip;
63
+ return benchmark;
64
+ }
65
+ function formatName(name) {
66
+ return typeof name === "string" ? name : name instanceof Function ? name.name || "<anonymous>" : String(name);
67
+ }
68
+
69
+ function commonjsRequire(path) {
70
+ 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.');
71
+ }
72
+
73
+ var chaiSubset = {exports: {}};
74
+
75
+ (function (module, exports) {
76
+ (function() {
77
+ (function(chaiSubset) {
78
+ if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
79
+ return module.exports = chaiSubset;
80
+ } else {
81
+ return chai.use(chaiSubset);
82
+ }
83
+ })(function(chai, utils) {
84
+ var Assertion = chai.Assertion;
85
+ var assertionPrototype = Assertion.prototype;
86
+
87
+ Assertion.addMethod('containSubset', function (expected) {
88
+ var actual = utils.flag(this, 'object');
89
+ var showDiff = chai.config.showDiff;
90
+
91
+ assertionPrototype.assert.call(this,
92
+ compare(expected, actual),
93
+ 'expected #{act} to contain subset #{exp}',
94
+ 'expected #{act} to not contain subset #{exp}',
95
+ expected,
96
+ actual,
97
+ showDiff
98
+ );
99
+ });
100
+
101
+ chai.assert.containSubset = function(val, exp, msg) {
102
+ new chai.Assertion(val, msg).to.be.containSubset(exp);
103
+ };
104
+
105
+ function compare(expected, actual) {
106
+ if (expected === actual) {
107
+ return true;
108
+ }
109
+ if (typeof(actual) !== typeof(expected)) {
110
+ return false;
111
+ }
112
+ if (typeof(expected) !== 'object' || expected === null) {
113
+ return expected === actual;
114
+ }
115
+ if (!!expected && !actual) {
116
+ return false;
117
+ }
118
+
119
+ if (Array.isArray(expected)) {
120
+ if (typeof(actual.length) !== 'number') {
121
+ return false;
122
+ }
123
+ var aa = Array.prototype.slice.call(actual);
124
+ return expected.every(function (exp) {
125
+ return aa.some(function (act) {
126
+ return compare(exp, act);
127
+ });
128
+ });
129
+ }
130
+
131
+ if (expected instanceof Date) {
132
+ if (actual instanceof Date) {
133
+ return expected.getTime() === actual.getTime();
134
+ } else {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ return Object.keys(expected).every(function (key) {
140
+ var eo = expected[key];
141
+ var ao = actual[key];
142
+ if (typeof(eo) === 'object' && eo !== null && ao !== null) {
143
+ return compare(eo, ao);
144
+ }
145
+ if (typeof(eo) === 'function') {
146
+ return eo(ao);
147
+ }
148
+ return ao === eo;
149
+ });
150
+ }
151
+ });
152
+
153
+ }).call(commonjsGlobal);
154
+ } (chaiSubset));
155
+
156
+ var chaiSubsetExports = chaiSubset.exports;
157
+ var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
158
+
159
+ const MATCHERS_OBJECT = Symbol.for("matchers-object");
160
+ const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
161
+ const GLOBAL_EXPECT = Symbol.for("expect-global");
162
+
163
+ if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
164
+ const globalState = /* @__PURE__ */ new WeakMap();
165
+ const matchers = /* @__PURE__ */ Object.create(null);
166
+ Object.defineProperty(globalThis, MATCHERS_OBJECT, {
167
+ get: () => globalState
168
+ });
169
+ Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
170
+ configurable: true,
171
+ get: () => ({
172
+ state: globalState.get(globalThis[GLOBAL_EXPECT]),
173
+ matchers
174
+ })
175
+ });
176
+ }
177
+
178
+ function recordAsyncExpect(test, promise) {
179
+ if (test && promise instanceof Promise) {
180
+ promise = promise.finally(() => {
181
+ const index = test.promises.indexOf(promise);
182
+ if (index !== -1)
183
+ test.promises.splice(index, 1);
184
+ });
185
+ if (!test.promises)
186
+ test.promises = [];
187
+ test.promises.push(promise);
188
+ }
189
+ return promise;
190
+ }
191
+
192
+ class VitestSnapshotClient extends SnapshotClient {
193
+ equalityCheck(received, expected) {
194
+ return equals(received, expected, [iterableEquality, subsetEquality]);
195
+ }
196
+ }
197
+
198
+ let _client;
199
+ function getSnapshotClient() {
200
+ if (!_client)
201
+ _client = new VitestSnapshotClient();
202
+ return _client;
203
+ }
204
+ function getErrorMessage(err) {
205
+ if (err instanceof Error)
206
+ return err.message;
207
+ return err;
208
+ }
209
+ function getErrorString(expected, promise) {
210
+ if (typeof expected !== "function") {
211
+ if (!promise)
212
+ throw new Error(`expected must be a function, received ${typeof expected}`);
213
+ return getErrorMessage(expected);
214
+ }
215
+ try {
216
+ expected();
217
+ } catch (e) {
218
+ return getErrorMessage(e);
219
+ }
220
+ throw new Error("snapshot function didn't throw");
221
+ }
222
+ const SnapshotPlugin = (chai, utils) => {
223
+ const getTestNames = (test) => {
224
+ var _a;
225
+ if (!test)
226
+ return {};
227
+ return {
228
+ filepath: (_a = test.file) == null ? void 0 : _a.filepath,
229
+ name: getNames(test).slice(1).join(" > ")
230
+ };
231
+ };
232
+ for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
233
+ utils.addMethod(
234
+ chai.Assertion.prototype,
235
+ key,
236
+ function(properties, message) {
237
+ const expected = utils.flag(this, "object");
238
+ const test = utils.flag(this, "vitest-test");
239
+ if (typeof properties === "string" && typeof message === "undefined") {
240
+ message = properties;
241
+ properties = void 0;
242
+ }
243
+ const errorMessage = utils.flag(this, "message");
244
+ getSnapshotClient().assert({
245
+ received: expected,
246
+ message,
247
+ isInline: false,
248
+ properties,
249
+ errorMessage,
250
+ ...getTestNames(test)
251
+ });
252
+ }
253
+ );
254
+ }
255
+ utils.addMethod(
256
+ chai.Assertion.prototype,
257
+ "toMatchFileSnapshot",
258
+ function(file, message) {
259
+ const expected = utils.flag(this, "object");
260
+ const test = utils.flag(this, "vitest-test");
261
+ const errorMessage = utils.flag(this, "message");
262
+ const promise = getSnapshotClient().assertRaw({
263
+ received: expected,
264
+ message,
265
+ isInline: false,
266
+ rawSnapshot: {
267
+ file
268
+ },
269
+ errorMessage,
270
+ ...getTestNames(test)
271
+ });
272
+ return recordAsyncExpect(test, promise);
273
+ }
274
+ );
275
+ utils.addMethod(
276
+ chai.Assertion.prototype,
277
+ "toMatchInlineSnapshot",
278
+ function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
279
+ var _a;
280
+ const test = utils.flag(this, "vitest-test");
281
+ const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
282
+ if (isInsideEach)
283
+ throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
284
+ const expected = utils.flag(this, "object");
285
+ const error = utils.flag(this, "error");
286
+ if (typeof properties === "string") {
287
+ message = inlineSnapshot;
288
+ inlineSnapshot = properties;
289
+ properties = void 0;
290
+ }
291
+ if (inlineSnapshot)
292
+ inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
293
+ const errorMessage = utils.flag(this, "message");
294
+ getSnapshotClient().assert({
295
+ received: expected,
296
+ message,
297
+ isInline: true,
298
+ properties,
299
+ inlineSnapshot,
300
+ error,
301
+ errorMessage,
302
+ ...getTestNames(test)
303
+ });
304
+ }
305
+ );
306
+ utils.addMethod(
307
+ chai.Assertion.prototype,
308
+ "toThrowErrorMatchingSnapshot",
309
+ function(message) {
310
+ const expected = utils.flag(this, "object");
311
+ const test = utils.flag(this, "vitest-test");
312
+ const promise = utils.flag(this, "promise");
313
+ const errorMessage = utils.flag(this, "message");
314
+ getSnapshotClient().assert({
315
+ received: getErrorString(expected, promise),
316
+ message,
317
+ errorMessage,
318
+ ...getTestNames(test)
319
+ });
320
+ }
321
+ );
322
+ utils.addMethod(
323
+ chai.Assertion.prototype,
324
+ "toThrowErrorMatchingInlineSnapshot",
325
+ function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
326
+ var _a;
327
+ const test = utils.flag(this, "vitest-test");
328
+ const isInsideEach = test && (test.each || ((_a = test.suite) == null ? void 0 : _a.each));
329
+ if (isInsideEach)
330
+ throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
331
+ const expected = utils.flag(this, "object");
332
+ const error = utils.flag(this, "error");
333
+ const promise = utils.flag(this, "promise");
334
+ const errorMessage = utils.flag(this, "message");
335
+ getSnapshotClient().assert({
336
+ received: getErrorString(expected, promise),
337
+ message,
338
+ inlineSnapshot,
339
+ isInline: true,
340
+ error,
341
+ errorMessage,
342
+ ...getTestNames(test)
343
+ });
344
+ }
345
+ );
346
+ utils.addMethod(
347
+ chai.expect,
348
+ "addSnapshotSerializer",
349
+ addSerializer
350
+ );
351
+ };
352
+
353
+ chai$1.use(JestExtend);
354
+ chai$1.use(JestChaiExpect);
355
+ chai$1.use(Subset);
356
+ chai$1.use(SnapshotPlugin);
357
+ chai$1.use(JestAsymmetricMatchers);
358
+
359
+ function createExpect(test) {
360
+ var _a;
361
+ const expect = (value, message) => {
362
+ const { assertionCalls } = getState(expect);
363
+ setState({ assertionCalls: assertionCalls + 1, soft: false }, expect);
364
+ const assert2 = chai$1.expect(value, message);
365
+ const _test = test || getCurrentTest();
366
+ if (_test)
367
+ return assert2.withTest(_test);
368
+ else
369
+ return assert2;
370
+ };
371
+ Object.assign(expect, chai$1.expect);
372
+ expect.getState = () => getState(expect);
373
+ expect.setState = (state) => setState(state, expect);
374
+ const globalState = getState(globalThis[GLOBAL_EXPECT$1]) || {};
375
+ setState({
376
+ // this should also add "snapshotState" that is added conditionally
377
+ ...globalState,
378
+ assertionCalls: 0,
379
+ isExpectingAssertions: false,
380
+ isExpectingAssertionsError: null,
381
+ expectedAssertionsNumber: null,
382
+ expectedAssertionsNumberErrorGen: null,
383
+ environment: getCurrentEnvironment(),
384
+ testPath: test ? (_a = test.suite.file) == null ? void 0 : _a.filepath : globalState.testPath,
385
+ currentTestName: test ? getFullName(test) : globalState.currentTestName
386
+ }, expect);
387
+ expect.extend = (matchers) => chai$1.expect.extend(expect, matchers);
388
+ expect.soft = (...args) => {
389
+ const assert2 = expect(...args);
390
+ expect.setState({
391
+ soft: true
392
+ });
393
+ return assert2;
394
+ };
395
+ expect.unreachable = (message) => {
396
+ chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
397
+ };
398
+ function assertions(expected) {
399
+ const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
400
+ if (Error.captureStackTrace)
401
+ Error.captureStackTrace(errorGen(), assertions);
402
+ expect.setState({
403
+ expectedAssertionsNumber: expected,
404
+ expectedAssertionsNumberErrorGen: errorGen
405
+ });
406
+ }
407
+ function hasAssertions() {
408
+ const error = new Error("expected any number of assertion, but got none");
409
+ if (Error.captureStackTrace)
410
+ Error.captureStackTrace(error, hasAssertions);
411
+ expect.setState({
412
+ isExpectingAssertions: true,
413
+ isExpectingAssertionsError: error
414
+ });
415
+ }
416
+ chai$1.util.addMethod(expect, "assertions", assertions);
417
+ chai$1.util.addMethod(expect, "hasAssertions", hasAssertions);
418
+ return expect;
419
+ }
420
+ const globalExpect = createExpect();
421
+ Object.defineProperty(globalThis, GLOBAL_EXPECT$1, {
422
+ value: globalExpect,
423
+ writable: true,
424
+ configurable: true
425
+ });
426
+ function setupChaiConfig(config) {
427
+ Object.assign(chai$1.config, config);
428
+ }
429
+
430
+ var fakeTimersSrc = {exports: {}};
431
+
432
+ /**
433
+ * A reference to the global object
434
+ *
435
+ * @type {object} globalObject
436
+ */
437
+ var globalObject;
438
+
439
+ /* istanbul ignore else */
440
+ if (typeof commonjsGlobal !== "undefined") {
441
+ // Node
442
+ globalObject = commonjsGlobal;
443
+ } else if (typeof window !== "undefined") {
444
+ // Browser
445
+ globalObject = window;
446
+ } else {
447
+ // WebWorker
448
+ globalObject = self;
449
+ }
450
+
451
+ var global = globalObject;
452
+
453
+ /**
454
+ * Is true when the environment causes an error to be thrown for accessing the
455
+ * __proto__ property.
456
+ *
457
+ * This is necessary in order to support `node --disable-proto=throw`.
458
+ *
459
+ * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
460
+ *
461
+ * @type {boolean}
462
+ */
463
+ let throwsOnProto$1;
464
+ try {
465
+ const object = {};
466
+ // eslint-disable-next-line no-proto, no-unused-expressions
467
+ object.__proto__;
468
+ throwsOnProto$1 = false;
469
+ } catch (_) {
470
+ // This branch is covered when tests are run with `--disable-proto=throw`,
471
+ // however we can test both branches at the same time, so this is ignored
472
+ /* istanbul ignore next */
473
+ throwsOnProto$1 = true;
474
+ }
475
+
476
+ var throwsOnProto_1 = throwsOnProto$1;
477
+
478
+ var call = Function.call;
479
+ var throwsOnProto = throwsOnProto_1;
480
+
481
+ var disallowedProperties = [
482
+ // ignore size because it throws from Map
483
+ "size",
484
+ "caller",
485
+ "callee",
486
+ "arguments",
487
+ ];
488
+
489
+ // This branch is covered when tests are run with `--disable-proto=throw`,
490
+ // however we can test both branches at the same time, so this is ignored
491
+ /* istanbul ignore next */
492
+ if (throwsOnProto) {
493
+ disallowedProperties.push("__proto__");
494
+ }
495
+
496
+ var copyPrototypeMethods = function copyPrototypeMethods(prototype) {
497
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
498
+ return Object.getOwnPropertyNames(prototype).reduce(function (
499
+ result,
500
+ name
501
+ ) {
502
+ if (disallowedProperties.includes(name)) {
503
+ return result;
504
+ }
505
+
506
+ if (typeof prototype[name] !== "function") {
507
+ return result;
508
+ }
509
+
510
+ result[name] = call.bind(prototype[name]);
511
+
512
+ return result;
513
+ },
514
+ Object.create(null));
515
+ };
516
+
517
+ var copyPrototype$5 = copyPrototypeMethods;
518
+
519
+ var array = copyPrototype$5(Array.prototype);
520
+
521
+ var every$1 = array.every;
522
+
523
+ /**
524
+ * @private
525
+ */
526
+ function hasCallsLeft(callMap, spy) {
527
+ if (callMap[spy.id] === undefined) {
528
+ callMap[spy.id] = 0;
529
+ }
530
+
531
+ return callMap[spy.id] < spy.callCount;
532
+ }
533
+
534
+ /**
535
+ * @private
536
+ */
537
+ function checkAdjacentCalls(callMap, spy, index, spies) {
538
+ var calledBeforeNext = true;
539
+
540
+ if (index !== spies.length - 1) {
541
+ calledBeforeNext = spy.calledBefore(spies[index + 1]);
542
+ }
543
+
544
+ if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
545
+ callMap[spy.id] += 1;
546
+ return true;
547
+ }
548
+
549
+ return false;
550
+ }
551
+
552
+ /**
553
+ * A Sinon proxy object (fake, spy, stub)
554
+ *
555
+ * @typedef {object} SinonProxy
556
+ * @property {Function} calledBefore - A method that determines if this proxy was called before another one
557
+ * @property {string} id - Some id
558
+ * @property {number} callCount - Number of times this proxy has been called
559
+ */
560
+
561
+ /**
562
+ * Returns true when the spies have been called in the order they were supplied in
563
+ *
564
+ * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
565
+ * @returns {boolean} true when spies are called in order, false otherwise
566
+ */
567
+ function calledInOrder(spies) {
568
+ var callMap = {};
569
+ // eslint-disable-next-line no-underscore-dangle
570
+ var _spies = arguments.length > 1 ? arguments : spies;
571
+
572
+ return every$1(_spies, checkAdjacentCalls.bind(null, callMap));
573
+ }
574
+
575
+ var calledInOrder_1 = calledInOrder;
576
+
577
+ /**
578
+ * Returns a display name for a function
579
+ *
580
+ * @param {Function} func
581
+ * @returns {string}
582
+ */
583
+ var functionName$1 = function functionName(func) {
584
+ if (!func) {
585
+ return "";
586
+ }
587
+
588
+ try {
589
+ return (
590
+ func.displayName ||
591
+ func.name ||
592
+ // Use function decomposition as a last resort to get function
593
+ // name. Does not rely on function decomposition to work - if it
594
+ // doesn't debugging will be slightly less informative
595
+ // (i.e. toString will say 'spy' rather than 'myFunc').
596
+ (String(func).match(/function ([^\s(]+)/) || [])[1]
597
+ );
598
+ } catch (e) {
599
+ // Stringify may fail and we might get an exception, as a last-last
600
+ // resort fall back to empty string.
601
+ return "";
602
+ }
603
+ };
604
+
605
+ var functionName = functionName$1;
606
+
607
+ /**
608
+ * Returns a display name for a value from a constructor
609
+ *
610
+ * @param {object} value A value to examine
611
+ * @returns {(string|null)} A string or null
612
+ */
613
+ function className(value) {
614
+ return (
615
+ (value.constructor && value.constructor.name) ||
616
+ // The next branch is for IE11 support only:
617
+ // Because the name property is not set on the prototype
618
+ // of the Function object, we finally try to grab the
619
+ // name from its definition. This will never be reached
620
+ // in node, so we are not able to test this properly.
621
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
622
+ (typeof value.constructor === "function" &&
623
+ /* istanbul ignore next */
624
+ functionName(value.constructor)) ||
625
+ null
626
+ );
627
+ }
628
+
629
+ var className_1 = className;
630
+
631
+ var deprecated = {};
632
+
633
+ /* eslint-disable no-console */
634
+
635
+ (function (exports) {
636
+
637
+ /**
638
+ * Returns a function that will invoke the supplied function and print a
639
+ * deprecation warning to the console each time it is called.
640
+ *
641
+ * @param {Function} func
642
+ * @param {string} msg
643
+ * @returns {Function}
644
+ */
645
+ exports.wrap = function (func, msg) {
646
+ var wrapped = function () {
647
+ exports.printWarning(msg);
648
+ return func.apply(this, arguments);
649
+ };
650
+ if (func.prototype) {
651
+ wrapped.prototype = func.prototype;
652
+ }
653
+ return wrapped;
654
+ };
655
+
656
+ /**
657
+ * Returns a string which can be supplied to `wrap()` to notify the user that a
658
+ * particular part of the sinon API has been deprecated.
659
+ *
660
+ * @param {string} packageName
661
+ * @param {string} funcName
662
+ * @returns {string}
663
+ */
664
+ exports.defaultMsg = function (packageName, funcName) {
665
+ return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
666
+ };
667
+
668
+ /**
669
+ * Prints a warning on the console, when it exists
670
+ *
671
+ * @param {string} msg
672
+ * @returns {undefined}
673
+ */
674
+ exports.printWarning = function (msg) {
675
+ /* istanbul ignore next */
676
+ if (typeof process === "object" && process.emitWarning) {
677
+ // Emit Warnings in Node
678
+ process.emitWarning(msg);
679
+ } else if (console.info) {
680
+ console.info(msg);
681
+ } else {
682
+ console.log(msg);
683
+ }
684
+ };
685
+ } (deprecated));
686
+
687
+ /**
688
+ * Returns true when fn returns true for all members of obj.
689
+ * This is an every implementation that works for all iterables
690
+ *
691
+ * @param {object} obj
692
+ * @param {Function} fn
693
+ * @returns {boolean}
694
+ */
695
+ var every = function every(obj, fn) {
696
+ var pass = true;
697
+
698
+ try {
699
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
700
+ obj.forEach(function () {
701
+ if (!fn.apply(this, arguments)) {
702
+ // Throwing an error is the only way to break `forEach`
703
+ throw new Error();
704
+ }
705
+ });
706
+ } catch (e) {
707
+ pass = false;
708
+ }
709
+
710
+ return pass;
711
+ };
712
+
713
+ var sort = array.sort;
714
+ var slice = array.slice;
715
+
716
+ /**
717
+ * @private
718
+ */
719
+ function comparator(a, b) {
720
+ // uuid, won't ever be equal
721
+ var aCall = a.getCall(0);
722
+ var bCall = b.getCall(0);
723
+ var aId = (aCall && aCall.callId) || -1;
724
+ var bId = (bCall && bCall.callId) || -1;
725
+
726
+ return aId < bId ? -1 : 1;
727
+ }
728
+
729
+ /**
730
+ * A Sinon proxy object (fake, spy, stub)
731
+ *
732
+ * @typedef {object} SinonProxy
733
+ * @property {Function} getCall - A method that can return the first call
734
+ */
735
+
736
+ /**
737
+ * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
738
+ *
739
+ * @param {SinonProxy[] | SinonProxy} spies
740
+ * @returns {SinonProxy[]}
741
+ */
742
+ function orderByFirstCall(spies) {
743
+ return sort(slice(spies), comparator);
744
+ }
745
+
746
+ var orderByFirstCall_1 = orderByFirstCall;
747
+
748
+ var copyPrototype$4 = copyPrototypeMethods;
749
+
750
+ var _function = copyPrototype$4(Function.prototype);
751
+
752
+ var copyPrototype$3 = copyPrototypeMethods;
753
+
754
+ var map = copyPrototype$3(Map.prototype);
755
+
756
+ var copyPrototype$2 = copyPrototypeMethods;
757
+
758
+ var object = copyPrototype$2(Object.prototype);
759
+
760
+ var copyPrototype$1 = copyPrototypeMethods;
761
+
762
+ var set = copyPrototype$1(Set.prototype);
763
+
764
+ var copyPrototype = copyPrototypeMethods;
765
+
766
+ var string = copyPrototype(String.prototype);
767
+
768
+ var prototypes = {
769
+ array: array,
770
+ function: _function,
771
+ map: map,
772
+ object: object,
773
+ set: set,
774
+ string: string,
775
+ };
776
+
777
+ var typeDetect = {exports: {}};
778
+
779
+ (function (module, exports) {
780
+ (function (global, factory) {
781
+ module.exports = factory() ;
782
+ }(commonjsGlobal, (function () {
783
+ /* !
784
+ * type-detect
785
+ * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
786
+ * MIT Licensed
787
+ */
788
+ var promiseExists = typeof Promise === 'function';
789
+
790
+ /* eslint-disable no-undef */
791
+ var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist
792
+
793
+ var symbolExists = typeof Symbol !== 'undefined';
794
+ var mapExists = typeof Map !== 'undefined';
795
+ var setExists = typeof Set !== 'undefined';
796
+ var weakMapExists = typeof WeakMap !== 'undefined';
797
+ var weakSetExists = typeof WeakSet !== 'undefined';
798
+ var dataViewExists = typeof DataView !== 'undefined';
799
+ var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
800
+ var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
801
+ var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
802
+ var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
803
+ var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
804
+ var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
805
+ var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
806
+ var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
807
+ var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
808
+ var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
809
+ var toStringLeftSliceLength = 8;
810
+ var toStringRightSliceLength = -1;
811
+ /**
812
+ * ### typeOf (obj)
813
+ *
814
+ * Uses `Object.prototype.toString` to determine the type of an object,
815
+ * normalising behaviour across engine versions & well optimised.
816
+ *
817
+ * @param {Mixed} object
818
+ * @return {String} object type
819
+ * @api public
820
+ */
821
+ function typeDetect(obj) {
822
+ /* ! Speed optimisation
823
+ * Pre:
824
+ * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
825
+ * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
826
+ * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
827
+ * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
828
+ * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
829
+ * Post:
830
+ * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
831
+ * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
832
+ * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
833
+ * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
834
+ * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
835
+ */
836
+ var typeofObj = typeof obj;
837
+ if (typeofObj !== 'object') {
838
+ return typeofObj;
839
+ }
840
+
841
+ /* ! Speed optimisation
842
+ * Pre:
843
+ * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
844
+ * Post:
845
+ * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
846
+ */
847
+ if (obj === null) {
848
+ return 'null';
849
+ }
850
+
851
+ /* ! Spec Conformance
852
+ * Test: `Object.prototype.toString.call(window)``
853
+ * - Node === "[object global]"
854
+ * - Chrome === "[object global]"
855
+ * - Firefox === "[object Window]"
856
+ * - PhantomJS === "[object Window]"
857
+ * - Safari === "[object Window]"
858
+ * - IE 11 === "[object Window]"
859
+ * - IE Edge === "[object Window]"
860
+ * Test: `Object.prototype.toString.call(this)``
861
+ * - Chrome Worker === "[object global]"
862
+ * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
863
+ * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
864
+ * - IE 11 Worker === "[object WorkerGlobalScope]"
865
+ * - IE Edge Worker === "[object WorkerGlobalScope]"
866
+ */
867
+ if (obj === globalObject) {
868
+ return 'global';
869
+ }
870
+
871
+ /* ! Speed optimisation
872
+ * Pre:
873
+ * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
874
+ * Post:
875
+ * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
876
+ */
877
+ if (
878
+ Array.isArray(obj) &&
879
+ (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
880
+ ) {
881
+ return 'Array';
882
+ }
883
+
884
+ // Not caching existence of `window` and related properties due to potential
885
+ // for `window` to be unset before tests in quasi-browser environments.
886
+ if (typeof window === 'object' && window !== null) {
887
+ /* ! Spec Conformance
888
+ * (https://html.spec.whatwg.org/multipage/browsers.html#location)
889
+ * WhatWG HTML$7.7.3 - The `Location` interface
890
+ * Test: `Object.prototype.toString.call(window.location)``
891
+ * - IE <=11 === "[object Object]"
892
+ * - IE Edge <=13 === "[object Object]"
893
+ */
894
+ if (typeof window.location === 'object' && obj === window.location) {
895
+ return 'Location';
896
+ }
897
+
898
+ /* ! Spec Conformance
899
+ * (https://html.spec.whatwg.org/#document)
900
+ * WhatWG HTML$3.1.1 - The `Document` object
901
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
902
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
903
+ * which suggests that browsers should use HTMLTableCellElement for
904
+ * both TD and TH elements. WhatWG separates these.
905
+ * WhatWG HTML states:
906
+ * > For historical reasons, Window objects must also have a
907
+ * > writable, configurable, non-enumerable property named
908
+ * > HTMLDocument whose value is the Document interface object.
909
+ * Test: `Object.prototype.toString.call(document)``
910
+ * - Chrome === "[object HTMLDocument]"
911
+ * - Firefox === "[object HTMLDocument]"
912
+ * - Safari === "[object HTMLDocument]"
913
+ * - IE <=10 === "[object Document]"
914
+ * - IE 11 === "[object HTMLDocument]"
915
+ * - IE Edge <=13 === "[object HTMLDocument]"
916
+ */
917
+ if (typeof window.document === 'object' && obj === window.document) {
918
+ return 'Document';
919
+ }
920
+
921
+ if (typeof window.navigator === 'object') {
922
+ /* ! Spec Conformance
923
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
924
+ * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
925
+ * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
926
+ * - IE <=10 === "[object MSMimeTypesCollection]"
927
+ */
928
+ if (typeof window.navigator.mimeTypes === 'object' &&
929
+ obj === window.navigator.mimeTypes) {
930
+ return 'MimeTypeArray';
931
+ }
932
+
933
+ /* ! Spec Conformance
934
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
935
+ * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
936
+ * Test: `Object.prototype.toString.call(navigator.plugins)``
937
+ * - IE <=10 === "[object MSPluginsCollection]"
938
+ */
939
+ if (typeof window.navigator.plugins === 'object' &&
940
+ obj === window.navigator.plugins) {
941
+ return 'PluginArray';
942
+ }
943
+ }
944
+
945
+ if ((typeof window.HTMLElement === 'function' ||
946
+ typeof window.HTMLElement === 'object') &&
947
+ obj instanceof window.HTMLElement) {
948
+ /* ! Spec Conformance
949
+ * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
950
+ * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
951
+ * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
952
+ * - IE <=10 === "[object HTMLBlockElement]"
953
+ */
954
+ if (obj.tagName === 'BLOCKQUOTE') {
955
+ return 'HTMLQuoteElement';
956
+ }
957
+
958
+ /* ! Spec Conformance
959
+ * (https://html.spec.whatwg.org/#htmltabledatacellelement)
960
+ * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
961
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
962
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
963
+ * which suggests that browsers should use HTMLTableCellElement for
964
+ * both TD and TH elements. WhatWG separates these.
965
+ * Test: Object.prototype.toString.call(document.createElement('td'))
966
+ * - Chrome === "[object HTMLTableCellElement]"
967
+ * - Firefox === "[object HTMLTableCellElement]"
968
+ * - Safari === "[object HTMLTableCellElement]"
969
+ */
970
+ if (obj.tagName === 'TD') {
971
+ return 'HTMLTableDataCellElement';
972
+ }
973
+
974
+ /* ! Spec Conformance
975
+ * (https://html.spec.whatwg.org/#htmltableheadercellelement)
976
+ * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
977
+ * Note: Most browsers currently adher to the W3C DOM Level 2 spec
978
+ * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
979
+ * which suggests that browsers should use HTMLTableCellElement for
980
+ * both TD and TH elements. WhatWG separates these.
981
+ * Test: Object.prototype.toString.call(document.createElement('th'))
982
+ * - Chrome === "[object HTMLTableCellElement]"
983
+ * - Firefox === "[object HTMLTableCellElement]"
984
+ * - Safari === "[object HTMLTableCellElement]"
985
+ */
986
+ if (obj.tagName === 'TH') {
987
+ return 'HTMLTableHeaderCellElement';
988
+ }
989
+ }
990
+ }
991
+
992
+ /* ! Speed optimisation
993
+ * Pre:
994
+ * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
995
+ * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
996
+ * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
997
+ * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
998
+ * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
999
+ * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
1000
+ * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
1001
+ * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
1002
+ * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
1003
+ * Post:
1004
+ * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
1005
+ * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
1006
+ * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
1007
+ * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
1008
+ * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
1009
+ * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
1010
+ * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
1011
+ * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
1012
+ * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
1013
+ */
1014
+ var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
1015
+ if (typeof stringTag === 'string') {
1016
+ return stringTag;
1017
+ }
1018
+
1019
+ var objPrototype = Object.getPrototypeOf(obj);
1020
+ /* ! Speed optimisation
1021
+ * Pre:
1022
+ * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
1023
+ * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
1024
+ * Post:
1025
+ * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
1026
+ * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
1027
+ */
1028
+ if (objPrototype === RegExp.prototype) {
1029
+ return 'RegExp';
1030
+ }
1031
+
1032
+ /* ! Speed optimisation
1033
+ * Pre:
1034
+ * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
1035
+ * Post:
1036
+ * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
1037
+ */
1038
+ if (objPrototype === Date.prototype) {
1039
+ return 'Date';
1040
+ }
1041
+
1042
+ /* ! Spec Conformance
1043
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
1044
+ * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
1045
+ * Test: `Object.prototype.toString.call(Promise.resolve())``
1046
+ * - Chrome <=47 === "[object Object]"
1047
+ * - Edge <=20 === "[object Object]"
1048
+ * - Firefox 29-Latest === "[object Promise]"
1049
+ * - Safari 7.1-Latest === "[object Promise]"
1050
+ */
1051
+ if (promiseExists && objPrototype === Promise.prototype) {
1052
+ return 'Promise';
1053
+ }
1054
+
1055
+ /* ! Speed optimisation
1056
+ * Pre:
1057
+ * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
1058
+ * Post:
1059
+ * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
1060
+ */
1061
+ if (setExists && objPrototype === Set.prototype) {
1062
+ return 'Set';
1063
+ }
1064
+
1065
+ /* ! Speed optimisation
1066
+ * Pre:
1067
+ * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
1068
+ * Post:
1069
+ * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
1070
+ */
1071
+ if (mapExists && objPrototype === Map.prototype) {
1072
+ return 'Map';
1073
+ }
1074
+
1075
+ /* ! Speed optimisation
1076
+ * Pre:
1077
+ * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
1078
+ * Post:
1079
+ * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
1080
+ */
1081
+ if (weakSetExists && objPrototype === WeakSet.prototype) {
1082
+ return 'WeakSet';
1083
+ }
1084
+
1085
+ /* ! Speed optimisation
1086
+ * Pre:
1087
+ * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
1088
+ * Post:
1089
+ * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
1090
+ */
1091
+ if (weakMapExists && objPrototype === WeakMap.prototype) {
1092
+ return 'WeakMap';
1093
+ }
1094
+
1095
+ /* ! Spec Conformance
1096
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
1097
+ * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
1098
+ * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
1099
+ * - Edge <=13 === "[object Object]"
1100
+ */
1101
+ if (dataViewExists && objPrototype === DataView.prototype) {
1102
+ return 'DataView';
1103
+ }
1104
+
1105
+ /* ! Spec Conformance
1106
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
1107
+ * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
1108
+ * Test: `Object.prototype.toString.call(new Map().entries())``
1109
+ * - Edge <=13 === "[object Object]"
1110
+ */
1111
+ if (mapExists && objPrototype === mapIteratorPrototype) {
1112
+ return 'Map Iterator';
1113
+ }
1114
+
1115
+ /* ! Spec Conformance
1116
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
1117
+ * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
1118
+ * Test: `Object.prototype.toString.call(new Set().entries())``
1119
+ * - Edge <=13 === "[object Object]"
1120
+ */
1121
+ if (setExists && objPrototype === setIteratorPrototype) {
1122
+ return 'Set Iterator';
1123
+ }
1124
+
1125
+ /* ! Spec Conformance
1126
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
1127
+ * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
1128
+ * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
1129
+ * - Edge <=13 === "[object Object]"
1130
+ */
1131
+ if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
1132
+ return 'Array Iterator';
1133
+ }
1134
+
1135
+ /* ! Spec Conformance
1136
+ * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
1137
+ * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
1138
+ * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
1139
+ * - Edge <=13 === "[object Object]"
1140
+ */
1141
+ if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
1142
+ return 'String Iterator';
1143
+ }
1144
+
1145
+ /* ! Speed optimisation
1146
+ * Pre:
1147
+ * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
1148
+ * Post:
1149
+ * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
1150
+ */
1151
+ if (objPrototype === null) {
1152
+ return 'Object';
1153
+ }
1154
+
1155
+ return Object
1156
+ .prototype
1157
+ .toString
1158
+ .call(obj)
1159
+ .slice(toStringLeftSliceLength, toStringRightSliceLength);
1160
+ }
1161
+
1162
+ return typeDetect;
1163
+
1164
+ })));
1165
+ } (typeDetect));
1166
+
1167
+ var typeDetectExports = typeDetect.exports;
1168
+
1169
+ var type = typeDetectExports;
1170
+
1171
+ /**
1172
+ * Returns the lower-case result of running type from type-detect on the value
1173
+ *
1174
+ * @param {*} value
1175
+ * @returns {string}
1176
+ */
1177
+ var typeOf = function typeOf(value) {
1178
+ return type(value).toLowerCase();
1179
+ };
1180
+
1181
+ /**
1182
+ * Returns a string representation of the value
1183
+ *
1184
+ * @param {*} value
1185
+ * @returns {string}
1186
+ */
1187
+ function valueToString(value) {
1188
+ if (value && value.toString) {
1189
+ // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
1190
+ return value.toString();
1191
+ }
1192
+ return String(value);
1193
+ }
1194
+
1195
+ var valueToString_1 = valueToString;
1196
+
1197
+ var lib = {
1198
+ global: global,
1199
+ calledInOrder: calledInOrder_1,
1200
+ className: className_1,
1201
+ deprecated: deprecated,
1202
+ every: every,
1203
+ functionName: functionName$1,
1204
+ orderByFirstCall: orderByFirstCall_1,
1205
+ prototypes: prototypes,
1206
+ typeOf: typeOf,
1207
+ valueToString: valueToString_1,
1208
+ };
1209
+
1210
+ (function (module, exports) {
1211
+
1212
+ const globalObject = lib.global;
1213
+ let timersModule;
1214
+ if (typeof commonjsRequire === "function" && 'object' === "object") {
1215
+ try {
1216
+ timersModule = require("timers");
1217
+ } catch (e) {
1218
+ // ignored
1219
+ }
1220
+ }
1221
+
1222
+ /**
1223
+ * @typedef {object} IdleDeadline
1224
+ * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
1225
+ * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
1226
+ */
1227
+
1228
+ /**
1229
+ * Queues a function to be called during a browser's idle periods
1230
+ *
1231
+ * @callback RequestIdleCallback
1232
+ * @param {function(IdleDeadline)} callback
1233
+ * @param {{timeout: number}} options - an options object
1234
+ * @returns {number} the id
1235
+ */
1236
+
1237
+ /**
1238
+ * @callback NextTick
1239
+ * @param {VoidVarArgsFunc} callback - the callback to run
1240
+ * @param {...*} arguments - optional arguments to call the callback with
1241
+ * @returns {void}
1242
+ */
1243
+
1244
+ /**
1245
+ * @callback SetImmediate
1246
+ * @param {VoidVarArgsFunc} callback - the callback to run
1247
+ * @param {...*} arguments - optional arguments to call the callback with
1248
+ * @returns {NodeImmediate}
1249
+ */
1250
+
1251
+ /**
1252
+ * @callback VoidVarArgsFunc
1253
+ * @param {...*} callback - the callback to run
1254
+ * @returns {void}
1255
+ */
1256
+
1257
+ /**
1258
+ * @typedef RequestAnimationFrame
1259
+ * @property {function(number):void} requestAnimationFrame
1260
+ * @returns {number} - the id
1261
+ */
1262
+
1263
+ /**
1264
+ * @typedef Performance
1265
+ * @property {function(): number} now
1266
+ */
1267
+
1268
+ /* eslint-disable jsdoc/require-property-description */
1269
+ /**
1270
+ * @typedef {object} Clock
1271
+ * @property {number} now - the current time
1272
+ * @property {Date} Date - the Date constructor
1273
+ * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
1274
+ * @property {RequestIdleCallback} requestIdleCallback
1275
+ * @property {function(number):void} cancelIdleCallback
1276
+ * @property {setTimeout} setTimeout
1277
+ * @property {clearTimeout} clearTimeout
1278
+ * @property {NextTick} nextTick
1279
+ * @property {queueMicrotask} queueMicrotask
1280
+ * @property {setInterval} setInterval
1281
+ * @property {clearInterval} clearInterval
1282
+ * @property {SetImmediate} setImmediate
1283
+ * @property {function(NodeImmediate):void} clearImmediate
1284
+ * @property {function():number} countTimers
1285
+ * @property {RequestAnimationFrame} requestAnimationFrame
1286
+ * @property {function(number):void} cancelAnimationFrame
1287
+ * @property {function():void} runMicrotasks
1288
+ * @property {function(string | number): number} tick
1289
+ * @property {function(string | number): Promise<number>} tickAsync
1290
+ * @property {function(): number} next
1291
+ * @property {function(): Promise<number>} nextAsync
1292
+ * @property {function(): number} runAll
1293
+ * @property {function(): number} runToFrame
1294
+ * @property {function(): Promise<number>} runAllAsync
1295
+ * @property {function(): number} runToLast
1296
+ * @property {function(): Promise<number>} runToLastAsync
1297
+ * @property {function(): void} reset
1298
+ * @property {function(number | Date): void} setSystemTime
1299
+ * @property {function(number): void} jump
1300
+ * @property {Performance} performance
1301
+ * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
1302
+ * @property {function(): void} uninstall Uninstall the clock.
1303
+ * @property {Function[]} methods - the methods that are faked
1304
+ * @property {boolean} [shouldClearNativeTimers] inherited from config
1305
+ * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
1306
+ */
1307
+ /* eslint-enable jsdoc/require-property-description */
1308
+
1309
+ /**
1310
+ * Configuration object for the `install` method.
1311
+ *
1312
+ * @typedef {object} Config
1313
+ * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
1314
+ * @property {string[]} [toFake] names of the methods that should be faked.
1315
+ * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
1316
+ * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
1317
+ * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
1318
+ * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
1319
+ */
1320
+
1321
+ /* eslint-disable jsdoc/require-property-description */
1322
+ /**
1323
+ * The internal structure to describe a scheduled fake timer
1324
+ *
1325
+ * @typedef {object} Timer
1326
+ * @property {Function} func
1327
+ * @property {*[]} args
1328
+ * @property {number} delay
1329
+ * @property {number} callAt
1330
+ * @property {number} createdAt
1331
+ * @property {boolean} immediate
1332
+ * @property {number} id
1333
+ * @property {Error} [error]
1334
+ */
1335
+
1336
+ /**
1337
+ * A Node timer
1338
+ *
1339
+ * @typedef {object} NodeImmediate
1340
+ * @property {function(): boolean} hasRef
1341
+ * @property {function(): NodeImmediate} ref
1342
+ * @property {function(): NodeImmediate} unref
1343
+ */
1344
+ /* eslint-enable jsdoc/require-property-description */
1345
+
1346
+ /* eslint-disable complexity */
1347
+
1348
+ /**
1349
+ * Mocks available features in the specified global namespace.
1350
+ *
1351
+ * @param {*} _global Namespace to mock (e.g. `window`)
1352
+ * @returns {FakeTimers}
1353
+ */
1354
+ function withGlobal(_global) {
1355
+ const userAgent = _global.navigator && _global.navigator.userAgent;
1356
+ const isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
1357
+ const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
1358
+ const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
1359
+ const NOOP = function () {
1360
+ return undefined;
1361
+ };
1362
+ const NOOP_ARRAY = function () {
1363
+ return [];
1364
+ };
1365
+ const timeoutResult = _global.setTimeout(NOOP, 0);
1366
+ const addTimerReturnsObject = typeof timeoutResult === "object";
1367
+ const hrtimePresent =
1368
+ _global.process && typeof _global.process.hrtime === "function";
1369
+ const hrtimeBigintPresent =
1370
+ hrtimePresent && typeof _global.process.hrtime.bigint === "function";
1371
+ const nextTickPresent =
1372
+ _global.process && typeof _global.process.nextTick === "function";
1373
+ const utilPromisify = _global.process && require$$2.promisify;
1374
+ const performancePresent =
1375
+ _global.performance && typeof _global.performance.now === "function";
1376
+ const hasPerformancePrototype =
1377
+ _global.Performance &&
1378
+ (typeof _global.Performance).match(/^(function|object)$/);
1379
+ const hasPerformanceConstructorPrototype =
1380
+ _global.performance &&
1381
+ _global.performance.constructor &&
1382
+ _global.performance.constructor.prototype;
1383
+ const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask");
1384
+ const requestAnimationFramePresent =
1385
+ _global.requestAnimationFrame &&
1386
+ typeof _global.requestAnimationFrame === "function";
1387
+ const cancelAnimationFramePresent =
1388
+ _global.cancelAnimationFrame &&
1389
+ typeof _global.cancelAnimationFrame === "function";
1390
+ const requestIdleCallbackPresent =
1391
+ _global.requestIdleCallback &&
1392
+ typeof _global.requestIdleCallback === "function";
1393
+ const cancelIdleCallbackPresent =
1394
+ _global.cancelIdleCallback &&
1395
+ typeof _global.cancelIdleCallback === "function";
1396
+ const setImmediatePresent =
1397
+ _global.setImmediate && typeof _global.setImmediate === "function";
1398
+
1399
+ // Make properties writable in IE, as per
1400
+ // https://www.adequatelygood.com/Replacing-setTimeout-Globally.html
1401
+ /* eslint-disable no-self-assign */
1402
+ if (isRunningInIE) {
1403
+ _global.setTimeout = _global.setTimeout;
1404
+ _global.clearTimeout = _global.clearTimeout;
1405
+ _global.setInterval = _global.setInterval;
1406
+ _global.clearInterval = _global.clearInterval;
1407
+ _global.Date = _global.Date;
1408
+ }
1409
+
1410
+ // setImmediate is not a standard function
1411
+ // avoid adding the prop to the window object if not present
1412
+ if (setImmediatePresent) {
1413
+ _global.setImmediate = _global.setImmediate;
1414
+ _global.clearImmediate = _global.clearImmediate;
1415
+ }
1416
+ /* eslint-enable no-self-assign */
1417
+
1418
+ _global.clearTimeout(timeoutResult);
1419
+
1420
+ const NativeDate = _global.Date;
1421
+ let uniqueTimerId = idCounterStart;
1422
+
1423
+ /**
1424
+ * @param {number} num
1425
+ * @returns {boolean}
1426
+ */
1427
+ function isNumberFinite(num) {
1428
+ if (Number.isFinite) {
1429
+ return Number.isFinite(num);
1430
+ }
1431
+
1432
+ return isFinite(num);
1433
+ }
1434
+
1435
+ let isNearInfiniteLimit = false;
1436
+
1437
+ /**
1438
+ * @param {Clock} clock
1439
+ * @param {number} i
1440
+ */
1441
+ function checkIsNearInfiniteLimit(clock, i) {
1442
+ if (clock.loopLimit && i === clock.loopLimit - 1) {
1443
+ isNearInfiniteLimit = true;
1444
+ }
1445
+ }
1446
+
1447
+ /**
1448
+ *
1449
+ */
1450
+ function resetIsNearInfiniteLimit() {
1451
+ isNearInfiniteLimit = false;
1452
+ }
1453
+
1454
+ /**
1455
+ * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1456
+ * number of milliseconds. This is used to support human-readable strings passed
1457
+ * to clock.tick()
1458
+ *
1459
+ * @param {string} str
1460
+ * @returns {number}
1461
+ */
1462
+ function parseTime(str) {
1463
+ if (!str) {
1464
+ return 0;
1465
+ }
1466
+
1467
+ const strings = str.split(":");
1468
+ const l = strings.length;
1469
+ let i = l;
1470
+ let ms = 0;
1471
+ let parsed;
1472
+
1473
+ if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
1474
+ throw new Error(
1475
+ "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
1476
+ );
1477
+ }
1478
+
1479
+ while (i--) {
1480
+ parsed = parseInt(strings[i], 10);
1481
+
1482
+ if (parsed >= 60) {
1483
+ throw new Error(`Invalid time ${str}`);
1484
+ }
1485
+
1486
+ ms += parsed * Math.pow(60, l - i - 1);
1487
+ }
1488
+
1489
+ return ms * 1000;
1490
+ }
1491
+
1492
+ /**
1493
+ * Get the decimal part of the millisecond value as nanoseconds
1494
+ *
1495
+ * @param {number} msFloat the number of milliseconds
1496
+ * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1497
+ *
1498
+ * Example: nanoRemainer(123.456789) -> 456789
1499
+ */
1500
+ function nanoRemainder(msFloat) {
1501
+ const modulo = 1e6;
1502
+ const remainder = (msFloat * 1e6) % modulo;
1503
+ const positiveRemainder =
1504
+ remainder < 0 ? remainder + modulo : remainder;
1505
+
1506
+ return Math.floor(positiveRemainder);
1507
+ }
1508
+
1509
+ /**
1510
+ * Used to grok the `now` parameter to createClock.
1511
+ *
1512
+ * @param {Date|number} epoch the system time
1513
+ * @returns {number}
1514
+ */
1515
+ function getEpoch(epoch) {
1516
+ if (!epoch) {
1517
+ return 0;
1518
+ }
1519
+ if (typeof epoch.getTime === "function") {
1520
+ return epoch.getTime();
1521
+ }
1522
+ if (typeof epoch === "number") {
1523
+ return epoch;
1524
+ }
1525
+ throw new TypeError("now should be milliseconds since UNIX epoch");
1526
+ }
1527
+
1528
+ /**
1529
+ * @param {number} from
1530
+ * @param {number} to
1531
+ * @param {Timer} timer
1532
+ * @returns {boolean}
1533
+ */
1534
+ function inRange(from, to, timer) {
1535
+ return timer && timer.callAt >= from && timer.callAt <= to;
1536
+ }
1537
+
1538
+ /**
1539
+ * @param {Clock} clock
1540
+ * @param {Timer} job
1541
+ */
1542
+ function getInfiniteLoopError(clock, job) {
1543
+ const infiniteLoopError = new Error(
1544
+ `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`
1545
+ );
1546
+
1547
+ if (!job.error) {
1548
+ return infiniteLoopError;
1549
+ }
1550
+
1551
+ // pattern never matched in Node
1552
+ const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1553
+ let clockMethodPattern = new RegExp(
1554
+ String(Object.keys(clock).join("|"))
1555
+ );
1556
+
1557
+ if (addTimerReturnsObject) {
1558
+ // node.js environment
1559
+ clockMethodPattern = new RegExp(
1560
+ `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`
1561
+ );
1562
+ }
1563
+
1564
+ let matchedLineIndex = -1;
1565
+ job.error.stack.split("\n").some(function (line, i) {
1566
+ // If we've matched a computed target line (e.g. setTimeout) then we
1567
+ // don't need to look any further. Return true to stop iterating.
1568
+ const matchedComputedTarget = line.match(computedTargetPattern);
1569
+ /* istanbul ignore if */
1570
+ if (matchedComputedTarget) {
1571
+ matchedLineIndex = i;
1572
+ return true;
1573
+ }
1574
+
1575
+ // If we've matched a clock method line, then there may still be
1576
+ // others further down the trace. Return false to keep iterating.
1577
+ const matchedClockMethod = line.match(clockMethodPattern);
1578
+ if (matchedClockMethod) {
1579
+ matchedLineIndex = i;
1580
+ return false;
1581
+ }
1582
+
1583
+ // If we haven't matched anything on this line, but we matched
1584
+ // previously and set the matched line index, then we can stop.
1585
+ // If we haven't matched previously, then we should keep iterating.
1586
+ return matchedLineIndex >= 0;
1587
+ });
1588
+
1589
+ const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
1590
+ job.func.name || "anonymous"
1591
+ }\n${job.error.stack
1592
+ .split("\n")
1593
+ .slice(matchedLineIndex + 1)
1594
+ .join("\n")}`;
1595
+
1596
+ try {
1597
+ Object.defineProperty(infiniteLoopError, "stack", {
1598
+ value: stack,
1599
+ });
1600
+ } catch (e) {
1601
+ // noop
1602
+ }
1603
+
1604
+ return infiniteLoopError;
1605
+ }
1606
+
1607
+ /**
1608
+ * @param {Date} target
1609
+ * @param {Date} source
1610
+ * @returns {Date} the target after modifications
1611
+ */
1612
+ function mirrorDateProperties(target, source) {
1613
+ let prop;
1614
+ for (prop in source) {
1615
+ if (source.hasOwnProperty(prop)) {
1616
+ target[prop] = source[prop];
1617
+ }
1618
+ }
1619
+
1620
+ // set special now implementation
1621
+ if (source.now) {
1622
+ target.now = function now() {
1623
+ return target.clock.now;
1624
+ };
1625
+ } else {
1626
+ delete target.now;
1627
+ }
1628
+
1629
+ // set special toSource implementation
1630
+ if (source.toSource) {
1631
+ target.toSource = function toSource() {
1632
+ return source.toSource();
1633
+ };
1634
+ } else {
1635
+ delete target.toSource;
1636
+ }
1637
+
1638
+ // set special toString implementation
1639
+ target.toString = function toString() {
1640
+ return source.toString();
1641
+ };
1642
+
1643
+ target.prototype = source.prototype;
1644
+ target.parse = source.parse;
1645
+ target.UTC = source.UTC;
1646
+ target.prototype.toUTCString = source.prototype.toUTCString;
1647
+ target.isFake = true;
1648
+
1649
+ return target;
1650
+ }
1651
+
1652
+ //eslint-disable-next-line jsdoc/require-jsdoc
1653
+ function createDate() {
1654
+ /**
1655
+ * @param {number} year
1656
+ * @param {number} month
1657
+ * @param {number} date
1658
+ * @param {number} hour
1659
+ * @param {number} minute
1660
+ * @param {number} second
1661
+ * @param {number} ms
1662
+ * @returns {Date}
1663
+ */
1664
+ function ClockDate(year, month, date, hour, minute, second, ms) {
1665
+ // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
1666
+ // This remains so in the 10th edition of 2019 as well.
1667
+ if (!(this instanceof ClockDate)) {
1668
+ return new NativeDate(ClockDate.clock.now).toString();
1669
+ }
1670
+
1671
+ // if Date is called as a constructor with 'new' keyword
1672
+ // Defensive and verbose to avoid potential harm in passing
1673
+ // explicit undefined when user does not pass argument
1674
+ switch (arguments.length) {
1675
+ case 0:
1676
+ return new NativeDate(ClockDate.clock.now);
1677
+ case 1:
1678
+ return new NativeDate(year);
1679
+ case 2:
1680
+ return new NativeDate(year, month);
1681
+ case 3:
1682
+ return new NativeDate(year, month, date);
1683
+ case 4:
1684
+ return new NativeDate(year, month, date, hour);
1685
+ case 5:
1686
+ return new NativeDate(year, month, date, hour, minute);
1687
+ case 6:
1688
+ return new NativeDate(
1689
+ year,
1690
+ month,
1691
+ date,
1692
+ hour,
1693
+ minute,
1694
+ second
1695
+ );
1696
+ default:
1697
+ return new NativeDate(
1698
+ year,
1699
+ month,
1700
+ date,
1701
+ hour,
1702
+ minute,
1703
+ second,
1704
+ ms
1705
+ );
1706
+ }
1707
+ }
1708
+
1709
+ return mirrorDateProperties(ClockDate, NativeDate);
1710
+ }
1711
+
1712
+ //eslint-disable-next-line jsdoc/require-jsdoc
1713
+ function enqueueJob(clock, job) {
1714
+ // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
1715
+ if (!clock.jobs) {
1716
+ clock.jobs = [];
1717
+ }
1718
+ clock.jobs.push(job);
1719
+ }
1720
+
1721
+ //eslint-disable-next-line jsdoc/require-jsdoc
1722
+ function runJobs(clock) {
1723
+ // runs all microtick-deferred tasks - ecma262/#sec-runjobs
1724
+ if (!clock.jobs) {
1725
+ return;
1726
+ }
1727
+ for (let i = 0; i < clock.jobs.length; i++) {
1728
+ const job = clock.jobs[i];
1729
+ job.func.apply(null, job.args);
1730
+
1731
+ checkIsNearInfiniteLimit(clock, i);
1732
+ if (clock.loopLimit && i > clock.loopLimit) {
1733
+ throw getInfiniteLoopError(clock, job);
1734
+ }
1735
+ }
1736
+ resetIsNearInfiniteLimit();
1737
+ clock.jobs = [];
1738
+ }
1739
+
1740
+ /**
1741
+ * @param {Clock} clock
1742
+ * @param {Timer} timer
1743
+ * @returns {number} id of the created timer
1744
+ */
1745
+ function addTimer(clock, timer) {
1746
+ if (timer.func === undefined) {
1747
+ throw new Error("Callback must be provided to timer calls");
1748
+ }
1749
+
1750
+ if (addTimerReturnsObject) {
1751
+ // Node.js environment
1752
+ if (typeof timer.func !== "function") {
1753
+ throw new TypeError(
1754
+ `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${
1755
+ timer.func
1756
+ } of type ${typeof timer.func}`
1757
+ );
1758
+ }
1759
+ }
1760
+
1761
+ if (isNearInfiniteLimit) {
1762
+ timer.error = new Error();
1763
+ }
1764
+
1765
+ timer.type = timer.immediate ? "Immediate" : "Timeout";
1766
+
1767
+ if (timer.hasOwnProperty("delay")) {
1768
+ if (typeof timer.delay !== "number") {
1769
+ timer.delay = parseInt(timer.delay, 10);
1770
+ }
1771
+
1772
+ if (!isNumberFinite(timer.delay)) {
1773
+ timer.delay = 0;
1774
+ }
1775
+ timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1776
+ timer.delay = Math.max(0, timer.delay);
1777
+ }
1778
+
1779
+ if (timer.hasOwnProperty("interval")) {
1780
+ timer.type = "Interval";
1781
+ timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1782
+ }
1783
+
1784
+ if (timer.hasOwnProperty("animation")) {
1785
+ timer.type = "AnimationFrame";
1786
+ timer.animation = true;
1787
+ }
1788
+
1789
+ if (timer.hasOwnProperty("idleCallback")) {
1790
+ timer.type = "IdleCallback";
1791
+ timer.idleCallback = true;
1792
+ }
1793
+
1794
+ if (!clock.timers) {
1795
+ clock.timers = {};
1796
+ }
1797
+
1798
+ timer.id = uniqueTimerId++;
1799
+ timer.createdAt = clock.now;
1800
+ timer.callAt =
1801
+ clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1802
+
1803
+ clock.timers[timer.id] = timer;
1804
+
1805
+ if (addTimerReturnsObject) {
1806
+ const res = {
1807
+ refed: true,
1808
+ ref: function () {
1809
+ this.refed = true;
1810
+ return res;
1811
+ },
1812
+ unref: function () {
1813
+ this.refed = false;
1814
+ return res;
1815
+ },
1816
+ hasRef: function () {
1817
+ return this.refed;
1818
+ },
1819
+ refresh: function () {
1820
+ timer.callAt =
1821
+ clock.now +
1822
+ (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1823
+
1824
+ // it _might_ have been removed, but if not the assignment is perfectly fine
1825
+ clock.timers[timer.id] = timer;
1826
+
1827
+ return res;
1828
+ },
1829
+ [Symbol.toPrimitive]: function () {
1830
+ return timer.id;
1831
+ },
1832
+ };
1833
+ return res;
1834
+ }
1835
+
1836
+ return timer.id;
1837
+ }
1838
+
1839
+ /* eslint consistent-return: "off" */
1840
+ /**
1841
+ * Timer comparitor
1842
+ *
1843
+ * @param {Timer} a
1844
+ * @param {Timer} b
1845
+ * @returns {number}
1846
+ */
1847
+ function compareTimers(a, b) {
1848
+ // Sort first by absolute timing
1849
+ if (a.callAt < b.callAt) {
1850
+ return -1;
1851
+ }
1852
+ if (a.callAt > b.callAt) {
1853
+ return 1;
1854
+ }
1855
+
1856
+ // Sort next by immediate, immediate timers take precedence
1857
+ if (a.immediate && !b.immediate) {
1858
+ return -1;
1859
+ }
1860
+ if (!a.immediate && b.immediate) {
1861
+ return 1;
1862
+ }
1863
+
1864
+ // Sort next by creation time, earlier-created timers take precedence
1865
+ if (a.createdAt < b.createdAt) {
1866
+ return -1;
1867
+ }
1868
+ if (a.createdAt > b.createdAt) {
1869
+ return 1;
1870
+ }
1871
+
1872
+ // Sort next by id, lower-id timers take precedence
1873
+ if (a.id < b.id) {
1874
+ return -1;
1875
+ }
1876
+ if (a.id > b.id) {
1877
+ return 1;
1878
+ }
1879
+
1880
+ // As timer ids are unique, no fallback `0` is necessary
1881
+ }
1882
+
1883
+ /**
1884
+ * @param {Clock} clock
1885
+ * @param {number} from
1886
+ * @param {number} to
1887
+ * @returns {Timer}
1888
+ */
1889
+ function firstTimerInRange(clock, from, to) {
1890
+ const timers = clock.timers;
1891
+ let timer = null;
1892
+ let id, isInRange;
1893
+
1894
+ for (id in timers) {
1895
+ if (timers.hasOwnProperty(id)) {
1896
+ isInRange = inRange(from, to, timers[id]);
1897
+
1898
+ if (
1899
+ isInRange &&
1900
+ (!timer || compareTimers(timer, timers[id]) === 1)
1901
+ ) {
1902
+ timer = timers[id];
1903
+ }
1904
+ }
1905
+ }
1906
+
1907
+ return timer;
1908
+ }
1909
+
1910
+ /**
1911
+ * @param {Clock} clock
1912
+ * @returns {Timer}
1913
+ */
1914
+ function firstTimer(clock) {
1915
+ const timers = clock.timers;
1916
+ let timer = null;
1917
+ let id;
1918
+
1919
+ for (id in timers) {
1920
+ if (timers.hasOwnProperty(id)) {
1921
+ if (!timer || compareTimers(timer, timers[id]) === 1) {
1922
+ timer = timers[id];
1923
+ }
1924
+ }
1925
+ }
1926
+
1927
+ return timer;
1928
+ }
1929
+
1930
+ /**
1931
+ * @param {Clock} clock
1932
+ * @returns {Timer}
1933
+ */
1934
+ function lastTimer(clock) {
1935
+ const timers = clock.timers;
1936
+ let timer = null;
1937
+ let id;
1938
+
1939
+ for (id in timers) {
1940
+ if (timers.hasOwnProperty(id)) {
1941
+ if (!timer || compareTimers(timer, timers[id]) === -1) {
1942
+ timer = timers[id];
1943
+ }
1944
+ }
1945
+ }
1946
+
1947
+ return timer;
1948
+ }
1949
+
1950
+ /**
1951
+ * @param {Clock} clock
1952
+ * @param {Timer} timer
1953
+ */
1954
+ function callTimer(clock, timer) {
1955
+ if (typeof timer.interval === "number") {
1956
+ clock.timers[timer.id].callAt += timer.interval;
1957
+ } else {
1958
+ delete clock.timers[timer.id];
1959
+ }
1960
+
1961
+ if (typeof timer.func === "function") {
1962
+ timer.func.apply(null, timer.args);
1963
+ } else {
1964
+ /* eslint no-eval: "off" */
1965
+ const eval2 = eval;
1966
+ (function () {
1967
+ eval2(timer.func);
1968
+ })();
1969
+ }
1970
+ }
1971
+
1972
+ /**
1973
+ * Gets clear handler name for a given timer type
1974
+ *
1975
+ * @param {string} ttype
1976
+ */
1977
+ function getClearHandler(ttype) {
1978
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1979
+ return `cancel${ttype}`;
1980
+ }
1981
+ return `clear${ttype}`;
1982
+ }
1983
+
1984
+ /**
1985
+ * Gets schedule handler name for a given timer type
1986
+ *
1987
+ * @param {string} ttype
1988
+ */
1989
+ function getScheduleHandler(ttype) {
1990
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
1991
+ return `request${ttype}`;
1992
+ }
1993
+ return `set${ttype}`;
1994
+ }
1995
+
1996
+ /**
1997
+ * Creates an anonymous function to warn only once
1998
+ */
1999
+ function createWarnOnce() {
2000
+ let calls = 0;
2001
+ return function (msg) {
2002
+ // eslint-disable-next-line
2003
+ !calls++ && console.warn(msg);
2004
+ };
2005
+ }
2006
+ const warnOnce = createWarnOnce();
2007
+
2008
+ /**
2009
+ * @param {Clock} clock
2010
+ * @param {number} timerId
2011
+ * @param {string} ttype
2012
+ */
2013
+ function clearTimer(clock, timerId, ttype) {
2014
+ if (!timerId) {
2015
+ // null appears to be allowed in most browsers, and appears to be
2016
+ // relied upon by some libraries, like Bootstrap carousel
2017
+ return;
2018
+ }
2019
+
2020
+ if (!clock.timers) {
2021
+ clock.timers = {};
2022
+ }
2023
+
2024
+ // in Node, the ID is stored as the primitive value for `Timeout` objects
2025
+ // for `Immediate` objects, no ID exists, so it gets coerced to NaN
2026
+ const id = Number(timerId);
2027
+
2028
+ if (Number.isNaN(id) || id < idCounterStart) {
2029
+ const handlerName = getClearHandler(ttype);
2030
+
2031
+ if (clock.shouldClearNativeTimers === true) {
2032
+ const nativeHandler = clock[`_${handlerName}`];
2033
+ return typeof nativeHandler === "function"
2034
+ ? nativeHandler(timerId)
2035
+ : undefined;
2036
+ }
2037
+ warnOnce(
2038
+ `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` +
2039
+ "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`."
2040
+ );
2041
+ }
2042
+
2043
+ if (clock.timers.hasOwnProperty(id)) {
2044
+ // check that the ID matches a timer of the correct type
2045
+ const timer = clock.timers[id];
2046
+ if (
2047
+ timer.type === ttype ||
2048
+ (timer.type === "Timeout" && ttype === "Interval") ||
2049
+ (timer.type === "Interval" && ttype === "Timeout")
2050
+ ) {
2051
+ delete clock.timers[id];
2052
+ } else {
2053
+ const clear = getClearHandler(ttype);
2054
+ const schedule = getScheduleHandler(timer.type);
2055
+ throw new Error(
2056
+ `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`
2057
+ );
2058
+ }
2059
+ }
2060
+ }
2061
+
2062
+ /**
2063
+ * @param {Clock} clock
2064
+ * @param {Config} config
2065
+ * @returns {Timer[]}
2066
+ */
2067
+ function uninstall(clock, config) {
2068
+ let method, i, l;
2069
+ const installedHrTime = "_hrtime";
2070
+ const installedNextTick = "_nextTick";
2071
+
2072
+ for (i = 0, l = clock.methods.length; i < l; i++) {
2073
+ method = clock.methods[i];
2074
+ if (method === "hrtime" && _global.process) {
2075
+ _global.process.hrtime = clock[installedHrTime];
2076
+ } else if (method === "nextTick" && _global.process) {
2077
+ _global.process.nextTick = clock[installedNextTick];
2078
+ } else if (method === "performance") {
2079
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2080
+ clock,
2081
+ `_${method}`
2082
+ );
2083
+ if (
2084
+ originalPerfDescriptor &&
2085
+ originalPerfDescriptor.get &&
2086
+ !originalPerfDescriptor.set
2087
+ ) {
2088
+ Object.defineProperty(
2089
+ _global,
2090
+ method,
2091
+ originalPerfDescriptor
2092
+ );
2093
+ } else if (originalPerfDescriptor.configurable) {
2094
+ _global[method] = clock[`_${method}`];
2095
+ }
2096
+ } else {
2097
+ if (_global[method] && _global[method].hadOwnProperty) {
2098
+ _global[method] = clock[`_${method}`];
2099
+ } else {
2100
+ try {
2101
+ delete _global[method];
2102
+ } catch (ignore) {
2103
+ /* eslint no-empty: "off" */
2104
+ }
2105
+ }
2106
+ }
2107
+ if (clock.timersModuleMethods !== undefined) {
2108
+ for (let j = 0; j < clock.timersModuleMethods.length; j++) {
2109
+ const entry = clock.timersModuleMethods[j];
2110
+ timersModule[entry.methodName] = entry.original;
2111
+ }
2112
+ }
2113
+ }
2114
+
2115
+ if (config.shouldAdvanceTime === true) {
2116
+ _global.clearInterval(clock.attachedInterval);
2117
+ }
2118
+
2119
+ // Prevent multiple executions which will completely remove these props
2120
+ clock.methods = [];
2121
+
2122
+ // return pending timers, to enable checking what timers remained on uninstall
2123
+ if (!clock.timers) {
2124
+ return [];
2125
+ }
2126
+ return Object.keys(clock.timers).map(function mapper(key) {
2127
+ return clock.timers[key];
2128
+ });
2129
+ }
2130
+
2131
+ /**
2132
+ * @param {object} target the target containing the method to replace
2133
+ * @param {string} method the keyname of the method on the target
2134
+ * @param {Clock} clock
2135
+ */
2136
+ function hijackMethod(target, method, clock) {
2137
+ clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
2138
+ target,
2139
+ method
2140
+ );
2141
+ clock[`_${method}`] = target[method];
2142
+
2143
+ if (method === "Date") {
2144
+ const date = mirrorDateProperties(clock[method], target[method]);
2145
+ target[method] = date;
2146
+ } else if (method === "performance") {
2147
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
2148
+ target,
2149
+ method
2150
+ );
2151
+ // JSDOM has a read only performance field so we have to save/copy it differently
2152
+ if (
2153
+ originalPerfDescriptor &&
2154
+ originalPerfDescriptor.get &&
2155
+ !originalPerfDescriptor.set
2156
+ ) {
2157
+ Object.defineProperty(
2158
+ clock,
2159
+ `_${method}`,
2160
+ originalPerfDescriptor
2161
+ );
2162
+
2163
+ const perfDescriptor = Object.getOwnPropertyDescriptor(
2164
+ clock,
2165
+ method
2166
+ );
2167
+ Object.defineProperty(target, method, perfDescriptor);
2168
+ } else {
2169
+ target[method] = clock[method];
2170
+ }
2171
+ } else {
2172
+ target[method] = function () {
2173
+ return clock[method].apply(clock, arguments);
2174
+ };
2175
+
2176
+ Object.defineProperties(
2177
+ target[method],
2178
+ Object.getOwnPropertyDescriptors(clock[method])
2179
+ );
2180
+ }
2181
+
2182
+ target[method].clock = clock;
2183
+ }
2184
+
2185
+ /**
2186
+ * @param {Clock} clock
2187
+ * @param {number} advanceTimeDelta
2188
+ */
2189
+ function doIntervalTick(clock, advanceTimeDelta) {
2190
+ clock.tick(advanceTimeDelta);
2191
+ }
2192
+
2193
+ /**
2194
+ * @typedef {object} Timers
2195
+ * @property {setTimeout} setTimeout
2196
+ * @property {clearTimeout} clearTimeout
2197
+ * @property {setInterval} setInterval
2198
+ * @property {clearInterval} clearInterval
2199
+ * @property {Date} Date
2200
+ * @property {SetImmediate=} setImmediate
2201
+ * @property {function(NodeImmediate): void=} clearImmediate
2202
+ * @property {function(number[]):number[]=} hrtime
2203
+ * @property {NextTick=} nextTick
2204
+ * @property {Performance=} performance
2205
+ * @property {RequestAnimationFrame=} requestAnimationFrame
2206
+ * @property {boolean=} queueMicrotask
2207
+ * @property {function(number): void=} cancelAnimationFrame
2208
+ * @property {RequestIdleCallback=} requestIdleCallback
2209
+ * @property {function(number): void=} cancelIdleCallback
2210
+ */
2211
+
2212
+ /** @type {Timers} */
2213
+ const timers = {
2214
+ setTimeout: _global.setTimeout,
2215
+ clearTimeout: _global.clearTimeout,
2216
+ setInterval: _global.setInterval,
2217
+ clearInterval: _global.clearInterval,
2218
+ Date: _global.Date,
2219
+ };
2220
+
2221
+ if (setImmediatePresent) {
2222
+ timers.setImmediate = _global.setImmediate;
2223
+ timers.clearImmediate = _global.clearImmediate;
2224
+ }
2225
+
2226
+ if (hrtimePresent) {
2227
+ timers.hrtime = _global.process.hrtime;
2228
+ }
2229
+
2230
+ if (nextTickPresent) {
2231
+ timers.nextTick = _global.process.nextTick;
2232
+ }
2233
+
2234
+ if (performancePresent) {
2235
+ timers.performance = _global.performance;
2236
+ }
2237
+
2238
+ if (requestAnimationFramePresent) {
2239
+ timers.requestAnimationFrame = _global.requestAnimationFrame;
2240
+ }
2241
+
2242
+ if (queueMicrotaskPresent) {
2243
+ timers.queueMicrotask = true;
2244
+ }
2245
+
2246
+ if (cancelAnimationFramePresent) {
2247
+ timers.cancelAnimationFrame = _global.cancelAnimationFrame;
2248
+ }
2249
+
2250
+ if (requestIdleCallbackPresent) {
2251
+ timers.requestIdleCallback = _global.requestIdleCallback;
2252
+ }
2253
+
2254
+ if (cancelIdleCallbackPresent) {
2255
+ timers.cancelIdleCallback = _global.cancelIdleCallback;
2256
+ }
2257
+
2258
+ const originalSetTimeout = _global.setImmediate || _global.setTimeout;
2259
+
2260
+ /**
2261
+ * @param {Date|number} [start] the system time - non-integer values are floored
2262
+ * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
2263
+ * @returns {Clock}
2264
+ */
2265
+ function createClock(start, loopLimit) {
2266
+ // eslint-disable-next-line no-param-reassign
2267
+ start = Math.floor(getEpoch(start));
2268
+ // eslint-disable-next-line no-param-reassign
2269
+ loopLimit = loopLimit || 1000;
2270
+ let nanos = 0;
2271
+ const adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
2272
+
2273
+ if (NativeDate === undefined) {
2274
+ throw new Error(
2275
+ "The global scope doesn't have a `Date` object" +
2276
+ " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
2277
+ );
2278
+ }
2279
+
2280
+ const clock = {
2281
+ now: start,
2282
+ Date: createDate(),
2283
+ loopLimit: loopLimit,
2284
+ };
2285
+
2286
+ clock.Date.clock = clock;
2287
+
2288
+ //eslint-disable-next-line jsdoc/require-jsdoc
2289
+ function getTimeToNextFrame() {
2290
+ return 16 - ((clock.now - start) % 16);
2291
+ }
2292
+
2293
+ //eslint-disable-next-line jsdoc/require-jsdoc
2294
+ function hrtime(prev) {
2295
+ const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
2296
+ const secsSinceStart = Math.floor(millisSinceStart / 1000);
2297
+ const remainderInNanos =
2298
+ (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
2299
+ nanos -
2300
+ adjustedSystemTime[1];
2301
+
2302
+ if (Array.isArray(prev)) {
2303
+ if (prev[1] > 1e9) {
2304
+ throw new TypeError(
2305
+ "Number of nanoseconds can't exceed a billion"
2306
+ );
2307
+ }
2308
+
2309
+ const oldSecs = prev[0];
2310
+ let nanoDiff = remainderInNanos - prev[1];
2311
+ let secDiff = secsSinceStart - oldSecs;
2312
+
2313
+ if (nanoDiff < 0) {
2314
+ nanoDiff += 1e9;
2315
+ secDiff -= 1;
2316
+ }
2317
+
2318
+ return [secDiff, nanoDiff];
2319
+ }
2320
+ return [secsSinceStart, remainderInNanos];
2321
+ }
2322
+
2323
+ function fakePerformanceNow() {
2324
+ const hrt = hrtime();
2325
+ const millis = hrt[0] * 1000 + hrt[1] / 1e6;
2326
+ return millis;
2327
+ }
2328
+
2329
+ if (hrtimeBigintPresent) {
2330
+ hrtime.bigint = function () {
2331
+ const parts = hrtime();
2332
+ return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
2333
+ };
2334
+ }
2335
+
2336
+ clock.requestIdleCallback = function requestIdleCallback(
2337
+ func,
2338
+ timeout
2339
+ ) {
2340
+ let timeToNextIdlePeriod = 0;
2341
+
2342
+ if (clock.countTimers() > 0) {
2343
+ timeToNextIdlePeriod = 50; // const for now
2344
+ }
2345
+
2346
+ const result = addTimer(clock, {
2347
+ func: func,
2348
+ args: Array.prototype.slice.call(arguments, 2),
2349
+ delay:
2350
+ typeof timeout === "undefined"
2351
+ ? timeToNextIdlePeriod
2352
+ : Math.min(timeout, timeToNextIdlePeriod),
2353
+ idleCallback: true,
2354
+ });
2355
+
2356
+ return Number(result);
2357
+ };
2358
+
2359
+ clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
2360
+ return clearTimer(clock, timerId, "IdleCallback");
2361
+ };
2362
+
2363
+ clock.setTimeout = function setTimeout(func, timeout) {
2364
+ return addTimer(clock, {
2365
+ func: func,
2366
+ args: Array.prototype.slice.call(arguments, 2),
2367
+ delay: timeout,
2368
+ });
2369
+ };
2370
+ if (typeof _global.Promise !== "undefined" && utilPromisify) {
2371
+ clock.setTimeout[utilPromisify.custom] =
2372
+ function promisifiedSetTimeout(timeout, arg) {
2373
+ return new _global.Promise(function setTimeoutExecutor(
2374
+ resolve
2375
+ ) {
2376
+ addTimer(clock, {
2377
+ func: resolve,
2378
+ args: [arg],
2379
+ delay: timeout,
2380
+ });
2381
+ });
2382
+ };
2383
+ }
2384
+
2385
+ clock.clearTimeout = function clearTimeout(timerId) {
2386
+ return clearTimer(clock, timerId, "Timeout");
2387
+ };
2388
+
2389
+ clock.nextTick = function nextTick(func) {
2390
+ return enqueueJob(clock, {
2391
+ func: func,
2392
+ args: Array.prototype.slice.call(arguments, 1),
2393
+ error: isNearInfiniteLimit ? new Error() : null,
2394
+ });
2395
+ };
2396
+
2397
+ clock.queueMicrotask = function queueMicrotask(func) {
2398
+ return clock.nextTick(func); // explicitly drop additional arguments
2399
+ };
2400
+
2401
+ clock.setInterval = function setInterval(func, timeout) {
2402
+ // eslint-disable-next-line no-param-reassign
2403
+ timeout = parseInt(timeout, 10);
2404
+ return addTimer(clock, {
2405
+ func: func,
2406
+ args: Array.prototype.slice.call(arguments, 2),
2407
+ delay: timeout,
2408
+ interval: timeout,
2409
+ });
2410
+ };
2411
+
2412
+ clock.clearInterval = function clearInterval(timerId) {
2413
+ return clearTimer(clock, timerId, "Interval");
2414
+ };
2415
+
2416
+ if (setImmediatePresent) {
2417
+ clock.setImmediate = function setImmediate(func) {
2418
+ return addTimer(clock, {
2419
+ func: func,
2420
+ args: Array.prototype.slice.call(arguments, 1),
2421
+ immediate: true,
2422
+ });
2423
+ };
2424
+
2425
+ if (typeof _global.Promise !== "undefined" && utilPromisify) {
2426
+ clock.setImmediate[utilPromisify.custom] =
2427
+ function promisifiedSetImmediate(arg) {
2428
+ return new _global.Promise(
2429
+ function setImmediateExecutor(resolve) {
2430
+ addTimer(clock, {
2431
+ func: resolve,
2432
+ args: [arg],
2433
+ immediate: true,
2434
+ });
2435
+ }
2436
+ );
2437
+ };
2438
+ }
2439
+
2440
+ clock.clearImmediate = function clearImmediate(timerId) {
2441
+ return clearTimer(clock, timerId, "Immediate");
2442
+ };
2443
+ }
2444
+
2445
+ clock.countTimers = function countTimers() {
2446
+ return (
2447
+ Object.keys(clock.timers || {}).length +
2448
+ (clock.jobs || []).length
2449
+ );
2450
+ };
2451
+
2452
+ clock.requestAnimationFrame = function requestAnimationFrame(func) {
2453
+ const result = addTimer(clock, {
2454
+ func: func,
2455
+ delay: getTimeToNextFrame(),
2456
+ get args() {
2457
+ return [fakePerformanceNow()];
2458
+ },
2459
+ animation: true,
2460
+ });
2461
+
2462
+ return Number(result);
2463
+ };
2464
+
2465
+ clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
2466
+ return clearTimer(clock, timerId, "AnimationFrame");
2467
+ };
2468
+
2469
+ clock.runMicrotasks = function runMicrotasks() {
2470
+ runJobs(clock);
2471
+ };
2472
+
2473
+ /**
2474
+ * @param {number|string} tickValue milliseconds or a string parseable by parseTime
2475
+ * @param {boolean} isAsync
2476
+ * @param {Function} resolve
2477
+ * @param {Function} reject
2478
+ * @returns {number|undefined} will return the new `now` value or nothing for async
2479
+ */
2480
+ function doTick(tickValue, isAsync, resolve, reject) {
2481
+ const msFloat =
2482
+ typeof tickValue === "number"
2483
+ ? tickValue
2484
+ : parseTime(tickValue);
2485
+ const ms = Math.floor(msFloat);
2486
+ const remainder = nanoRemainder(msFloat);
2487
+ let nanosTotal = nanos + remainder;
2488
+ let tickTo = clock.now + ms;
2489
+
2490
+ if (msFloat < 0) {
2491
+ throw new TypeError("Negative ticks are not supported");
2492
+ }
2493
+
2494
+ // adjust for positive overflow
2495
+ if (nanosTotal >= 1e6) {
2496
+ tickTo += 1;
2497
+ nanosTotal -= 1e6;
2498
+ }
2499
+
2500
+ nanos = nanosTotal;
2501
+ let tickFrom = clock.now;
2502
+ let previous = clock.now;
2503
+ // ESLint fails to detect this correctly
2504
+ /* eslint-disable prefer-const */
2505
+ let timer,
2506
+ firstException,
2507
+ oldNow,
2508
+ nextPromiseTick,
2509
+ compensationCheck,
2510
+ postTimerCall;
2511
+ /* eslint-enable prefer-const */
2512
+
2513
+ clock.duringTick = true;
2514
+
2515
+ // perform microtasks
2516
+ oldNow = clock.now;
2517
+ runJobs(clock);
2518
+ if (oldNow !== clock.now) {
2519
+ // compensate for any setSystemTime() call during microtask callback
2520
+ tickFrom += clock.now - oldNow;
2521
+ tickTo += clock.now - oldNow;
2522
+ }
2523
+
2524
+ //eslint-disable-next-line jsdoc/require-jsdoc
2525
+ function doTickInner() {
2526
+ // perform each timer in the requested range
2527
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
2528
+ // eslint-disable-next-line no-unmodified-loop-condition
2529
+ while (timer && tickFrom <= tickTo) {
2530
+ if (clock.timers[timer.id]) {
2531
+ tickFrom = timer.callAt;
2532
+ clock.now = timer.callAt;
2533
+ oldNow = clock.now;
2534
+ try {
2535
+ runJobs(clock);
2536
+ callTimer(clock, timer);
2537
+ } catch (e) {
2538
+ firstException = firstException || e;
2539
+ }
2540
+
2541
+ if (isAsync) {
2542
+ // finish up after native setImmediate callback to allow
2543
+ // all native es6 promises to process their callbacks after
2544
+ // each timer fires.
2545
+ originalSetTimeout(nextPromiseTick);
2546
+ return;
2547
+ }
2548
+
2549
+ compensationCheck();
2550
+ }
2551
+
2552
+ postTimerCall();
2553
+ }
2554
+
2555
+ // perform process.nextTick()s again
2556
+ oldNow = clock.now;
2557
+ runJobs(clock);
2558
+ if (oldNow !== clock.now) {
2559
+ // compensate for any setSystemTime() call during process.nextTick() callback
2560
+ tickFrom += clock.now - oldNow;
2561
+ tickTo += clock.now - oldNow;
2562
+ }
2563
+ clock.duringTick = false;
2564
+
2565
+ // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
2566
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
2567
+ if (timer) {
2568
+ try {
2569
+ clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
2570
+ } catch (e) {
2571
+ firstException = firstException || e;
2572
+ }
2573
+ } else {
2574
+ // no timers remaining in the requested range: move the clock all the way to the end
2575
+ clock.now = tickTo;
2576
+
2577
+ // update nanos
2578
+ nanos = nanosTotal;
2579
+ }
2580
+ if (firstException) {
2581
+ throw firstException;
2582
+ }
2583
+
2584
+ if (isAsync) {
2585
+ resolve(clock.now);
2586
+ } else {
2587
+ return clock.now;
2588
+ }
2589
+ }
2590
+
2591
+ nextPromiseTick =
2592
+ isAsync &&
2593
+ function () {
2594
+ try {
2595
+ compensationCheck();
2596
+ postTimerCall();
2597
+ doTickInner();
2598
+ } catch (e) {
2599
+ reject(e);
2600
+ }
2601
+ };
2602
+
2603
+ compensationCheck = function () {
2604
+ // compensate for any setSystemTime() call during timer callback
2605
+ if (oldNow !== clock.now) {
2606
+ tickFrom += clock.now - oldNow;
2607
+ tickTo += clock.now - oldNow;
2608
+ previous += clock.now - oldNow;
2609
+ }
2610
+ };
2611
+
2612
+ postTimerCall = function () {
2613
+ timer = firstTimerInRange(clock, previous, tickTo);
2614
+ previous = tickFrom;
2615
+ };
2616
+
2617
+ return doTickInner();
2618
+ }
2619
+
2620
+ /**
2621
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2622
+ * @returns {number} will return the new `now` value
2623
+ */
2624
+ clock.tick = function tick(tickValue) {
2625
+ return doTick(tickValue, false);
2626
+ };
2627
+
2628
+ if (typeof _global.Promise !== "undefined") {
2629
+ /**
2630
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2631
+ * @returns {Promise}
2632
+ */
2633
+ clock.tickAsync = function tickAsync(tickValue) {
2634
+ return new _global.Promise(function (resolve, reject) {
2635
+ originalSetTimeout(function () {
2636
+ try {
2637
+ doTick(tickValue, true, resolve, reject);
2638
+ } catch (e) {
2639
+ reject(e);
2640
+ }
2641
+ });
2642
+ });
2643
+ };
2644
+ }
2645
+
2646
+ clock.next = function next() {
2647
+ runJobs(clock);
2648
+ const timer = firstTimer(clock);
2649
+ if (!timer) {
2650
+ return clock.now;
2651
+ }
2652
+
2653
+ clock.duringTick = true;
2654
+ try {
2655
+ clock.now = timer.callAt;
2656
+ callTimer(clock, timer);
2657
+ runJobs(clock);
2658
+ return clock.now;
2659
+ } finally {
2660
+ clock.duringTick = false;
2661
+ }
2662
+ };
2663
+
2664
+ if (typeof _global.Promise !== "undefined") {
2665
+ clock.nextAsync = function nextAsync() {
2666
+ return new _global.Promise(function (resolve, reject) {
2667
+ originalSetTimeout(function () {
2668
+ try {
2669
+ const timer = firstTimer(clock);
2670
+ if (!timer) {
2671
+ resolve(clock.now);
2672
+ return;
2673
+ }
2674
+
2675
+ let err;
2676
+ clock.duringTick = true;
2677
+ clock.now = timer.callAt;
2678
+ try {
2679
+ callTimer(clock, timer);
2680
+ } catch (e) {
2681
+ err = e;
2682
+ }
2683
+ clock.duringTick = false;
2684
+
2685
+ originalSetTimeout(function () {
2686
+ if (err) {
2687
+ reject(err);
2688
+ } else {
2689
+ resolve(clock.now);
2690
+ }
2691
+ });
2692
+ } catch (e) {
2693
+ reject(e);
2694
+ }
2695
+ });
2696
+ });
2697
+ };
2698
+ }
2699
+
2700
+ clock.runAll = function runAll() {
2701
+ let numTimers, i;
2702
+ runJobs(clock);
2703
+ for (i = 0; i < clock.loopLimit; i++) {
2704
+ if (!clock.timers) {
2705
+ resetIsNearInfiniteLimit();
2706
+ return clock.now;
2707
+ }
2708
+
2709
+ numTimers = Object.keys(clock.timers).length;
2710
+ if (numTimers === 0) {
2711
+ resetIsNearInfiniteLimit();
2712
+ return clock.now;
2713
+ }
2714
+
2715
+ clock.next();
2716
+ checkIsNearInfiniteLimit(clock, i);
2717
+ }
2718
+
2719
+ const excessJob = firstTimer(clock);
2720
+ throw getInfiniteLoopError(clock, excessJob);
2721
+ };
2722
+
2723
+ clock.runToFrame = function runToFrame() {
2724
+ return clock.tick(getTimeToNextFrame());
2725
+ };
2726
+
2727
+ if (typeof _global.Promise !== "undefined") {
2728
+ clock.runAllAsync = function runAllAsync() {
2729
+ return new _global.Promise(function (resolve, reject) {
2730
+ let i = 0;
2731
+ /**
2732
+ *
2733
+ */
2734
+ function doRun() {
2735
+ originalSetTimeout(function () {
2736
+ try {
2737
+ let numTimers;
2738
+ if (i < clock.loopLimit) {
2739
+ if (!clock.timers) {
2740
+ resetIsNearInfiniteLimit();
2741
+ resolve(clock.now);
2742
+ return;
2743
+ }
2744
+
2745
+ numTimers = Object.keys(
2746
+ clock.timers
2747
+ ).length;
2748
+ if (numTimers === 0) {
2749
+ resetIsNearInfiniteLimit();
2750
+ resolve(clock.now);
2751
+ return;
2752
+ }
2753
+
2754
+ clock.next();
2755
+
2756
+ i++;
2757
+
2758
+ doRun();
2759
+ checkIsNearInfiniteLimit(clock, i);
2760
+ return;
2761
+ }
2762
+
2763
+ const excessJob = firstTimer(clock);
2764
+ reject(getInfiniteLoopError(clock, excessJob));
2765
+ } catch (e) {
2766
+ reject(e);
2767
+ }
2768
+ });
2769
+ }
2770
+ doRun();
2771
+ });
2772
+ };
2773
+ }
2774
+
2775
+ clock.runToLast = function runToLast() {
2776
+ const timer = lastTimer(clock);
2777
+ if (!timer) {
2778
+ runJobs(clock);
2779
+ return clock.now;
2780
+ }
2781
+
2782
+ return clock.tick(timer.callAt - clock.now);
2783
+ };
2784
+
2785
+ if (typeof _global.Promise !== "undefined") {
2786
+ clock.runToLastAsync = function runToLastAsync() {
2787
+ return new _global.Promise(function (resolve, reject) {
2788
+ originalSetTimeout(function () {
2789
+ try {
2790
+ const timer = lastTimer(clock);
2791
+ if (!timer) {
2792
+ resolve(clock.now);
2793
+ }
2794
+
2795
+ resolve(clock.tickAsync(timer.callAt - clock.now));
2796
+ } catch (e) {
2797
+ reject(e);
2798
+ }
2799
+ });
2800
+ });
2801
+ };
2802
+ }
2803
+
2804
+ clock.reset = function reset() {
2805
+ nanos = 0;
2806
+ clock.timers = {};
2807
+ clock.jobs = [];
2808
+ clock.now = start;
2809
+ };
2810
+
2811
+ clock.setSystemTime = function setSystemTime(systemTime) {
2812
+ // determine time difference
2813
+ const newNow = getEpoch(systemTime);
2814
+ const difference = newNow - clock.now;
2815
+ let id, timer;
2816
+
2817
+ adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
2818
+ adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
2819
+ // update 'system clock'
2820
+ clock.now = newNow;
2821
+ nanos = 0;
2822
+
2823
+ // update timers and intervals to keep them stable
2824
+ for (id in clock.timers) {
2825
+ if (clock.timers.hasOwnProperty(id)) {
2826
+ timer = clock.timers[id];
2827
+ timer.createdAt += difference;
2828
+ timer.callAt += difference;
2829
+ }
2830
+ }
2831
+ };
2832
+
2833
+ /**
2834
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
2835
+ * @returns {number} will return the new `now` value
2836
+ */
2837
+ clock.jump = function jump(tickValue) {
2838
+ const msFloat =
2839
+ typeof tickValue === "number"
2840
+ ? tickValue
2841
+ : parseTime(tickValue);
2842
+ const ms = Math.floor(msFloat);
2843
+
2844
+ for (const timer of Object.values(clock.timers)) {
2845
+ if (clock.now + ms > timer.callAt) {
2846
+ timer.callAt = clock.now + ms;
2847
+ }
2848
+ }
2849
+ clock.tick(ms);
2850
+ };
2851
+
2852
+ if (performancePresent) {
2853
+ clock.performance = Object.create(null);
2854
+ clock.performance.now = fakePerformanceNow;
2855
+ }
2856
+
2857
+ if (hrtimePresent) {
2858
+ clock.hrtime = hrtime;
2859
+ }
2860
+
2861
+ return clock;
2862
+ }
2863
+
2864
+ /* eslint-disable complexity */
2865
+
2866
+ /**
2867
+ * @param {Config=} [config] Optional config
2868
+ * @returns {Clock}
2869
+ */
2870
+ function install(config) {
2871
+ if (
2872
+ arguments.length > 1 ||
2873
+ config instanceof Date ||
2874
+ Array.isArray(config) ||
2875
+ typeof config === "number"
2876
+ ) {
2877
+ throw new TypeError(
2878
+ `FakeTimers.install called with ${String(
2879
+ config
2880
+ )} install requires an object parameter`
2881
+ );
2882
+ }
2883
+
2884
+ if (_global.Date.isFake === true) {
2885
+ // Timers are already faked; this is a problem.
2886
+ // Make the user reset timers before continuing.
2887
+ throw new TypeError(
2888
+ "Can't install fake timers twice on the same global object."
2889
+ );
2890
+ }
2891
+
2892
+ // eslint-disable-next-line no-param-reassign
2893
+ config = typeof config !== "undefined" ? config : {};
2894
+ config.shouldAdvanceTime = config.shouldAdvanceTime || false;
2895
+ config.advanceTimeDelta = config.advanceTimeDelta || 20;
2896
+ config.shouldClearNativeTimers =
2897
+ config.shouldClearNativeTimers || false;
2898
+
2899
+ if (config.target) {
2900
+ throw new TypeError(
2901
+ "config.target is no longer supported. Use `withGlobal(target)` instead."
2902
+ );
2903
+ }
2904
+
2905
+ let i, l;
2906
+ const clock = createClock(config.now, config.loopLimit);
2907
+ clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
2908
+
2909
+ clock.uninstall = function () {
2910
+ return uninstall(clock, config);
2911
+ };
2912
+
2913
+ clock.methods = config.toFake || [];
2914
+
2915
+ if (clock.methods.length === 0) {
2916
+ // do not fake nextTick by default - GitHub#126
2917
+ clock.methods = Object.keys(timers).filter(function (key) {
2918
+ return key !== "nextTick" && key !== "queueMicrotask";
2919
+ });
2920
+ }
2921
+
2922
+ if (config.shouldAdvanceTime === true) {
2923
+ const intervalTick = doIntervalTick.bind(
2924
+ null,
2925
+ clock,
2926
+ config.advanceTimeDelta
2927
+ );
2928
+ const intervalId = _global.setInterval(
2929
+ intervalTick,
2930
+ config.advanceTimeDelta
2931
+ );
2932
+ clock.attachedInterval = intervalId;
2933
+ }
2934
+
2935
+ if (clock.methods.includes("performance")) {
2936
+ const proto = (() => {
2937
+ if (hasPerformancePrototype) {
2938
+ return _global.Performance.prototype;
2939
+ }
2940
+ if (hasPerformanceConstructorPrototype) {
2941
+ return _global.performance.constructor.prototype;
2942
+ }
2943
+ })();
2944
+ if (proto) {
2945
+ Object.getOwnPropertyNames(proto).forEach(function (name) {
2946
+ if (name !== "now") {
2947
+ clock.performance[name] =
2948
+ name.indexOf("getEntries") === 0
2949
+ ? NOOP_ARRAY
2950
+ : NOOP;
2951
+ }
2952
+ });
2953
+ } else if ((config.toFake || []).includes("performance")) {
2954
+ // user explicitly tried to fake performance when not present
2955
+ throw new ReferenceError(
2956
+ "non-existent performance object cannot be faked"
2957
+ );
2958
+ }
2959
+ }
2960
+ if (_global === globalObject && timersModule) {
2961
+ clock.timersModuleMethods = [];
2962
+ }
2963
+ for (i = 0, l = clock.methods.length; i < l; i++) {
2964
+ const nameOfMethodToReplace = clock.methods[i];
2965
+ if (nameOfMethodToReplace === "hrtime") {
2966
+ if (
2967
+ _global.process &&
2968
+ typeof _global.process.hrtime === "function"
2969
+ ) {
2970
+ hijackMethod(_global.process, nameOfMethodToReplace, clock);
2971
+ }
2972
+ } else if (nameOfMethodToReplace === "nextTick") {
2973
+ if (
2974
+ _global.process &&
2975
+ typeof _global.process.nextTick === "function"
2976
+ ) {
2977
+ hijackMethod(_global.process, nameOfMethodToReplace, clock);
2978
+ }
2979
+ } else {
2980
+ hijackMethod(_global, nameOfMethodToReplace, clock);
2981
+ }
2982
+ if (
2983
+ clock.timersModuleMethods !== undefined &&
2984
+ timersModule[nameOfMethodToReplace]
2985
+ ) {
2986
+ const original = timersModule[nameOfMethodToReplace];
2987
+ clock.timersModuleMethods.push({
2988
+ methodName: nameOfMethodToReplace,
2989
+ original: original,
2990
+ });
2991
+ timersModule[nameOfMethodToReplace] =
2992
+ _global[nameOfMethodToReplace];
2993
+ }
2994
+ }
2995
+
2996
+ return clock;
2997
+ }
2998
+
2999
+ /* eslint-enable complexity */
3000
+
3001
+ return {
3002
+ timers: timers,
3003
+ createClock: createClock,
3004
+ install: install,
3005
+ withGlobal: withGlobal,
3006
+ };
3007
+ }
3008
+
3009
+ /**
3010
+ * @typedef {object} FakeTimers
3011
+ * @property {Timers} timers
3012
+ * @property {createClock} createClock
3013
+ * @property {Function} install
3014
+ * @property {withGlobal} withGlobal
3015
+ */
3016
+
3017
+ /* eslint-enable complexity */
3018
+
3019
+ /** @type {FakeTimers} */
3020
+ const defaultImplementation = withGlobal(globalObject);
3021
+
3022
+ exports.timers = defaultImplementation.timers;
3023
+ exports.createClock = defaultImplementation.createClock;
3024
+ exports.install = defaultImplementation.install;
3025
+ exports.withGlobal = withGlobal;
3026
+ } (fakeTimersSrc, fakeTimersSrc.exports));
3027
+
3028
+ var fakeTimersSrcExports = fakeTimersSrc.exports;
3029
+
3030
+ const RealDate = Date;
3031
+ let now = null;
3032
+ class MockDate extends RealDate {
3033
+ constructor(y, m, d, h, M, s, ms) {
3034
+ super();
3035
+ let date;
3036
+ switch (arguments.length) {
3037
+ case 0:
3038
+ if (now !== null)
3039
+ date = new RealDate(now.valueOf());
3040
+ else
3041
+ date = new RealDate();
3042
+ break;
3043
+ case 1:
3044
+ date = new RealDate(y);
3045
+ break;
3046
+ default:
3047
+ d = typeof d === "undefined" ? 1 : d;
3048
+ h = h || 0;
3049
+ M = M || 0;
3050
+ s = s || 0;
3051
+ ms = ms || 0;
3052
+ date = new RealDate(y, m, d, h, M, s, ms);
3053
+ break;
3054
+ }
3055
+ return date;
3056
+ }
3057
+ }
3058
+ MockDate.UTC = RealDate.UTC;
3059
+ MockDate.now = function() {
3060
+ return new MockDate().valueOf();
3061
+ };
3062
+ MockDate.parse = function(dateString) {
3063
+ return RealDate.parse(dateString);
3064
+ };
3065
+ MockDate.toString = function() {
3066
+ return RealDate.toString();
3067
+ };
3068
+ function mockDate(date) {
3069
+ const dateObj = new RealDate(date.valueOf());
3070
+ if (Number.isNaN(dateObj.getTime()))
3071
+ throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
3072
+ globalThis.Date = MockDate;
3073
+ now = dateObj.valueOf();
3074
+ }
3075
+ function resetDate() {
3076
+ globalThis.Date = RealDate;
3077
+ }
3078
+
3079
+ class FakeTimers {
3080
+ _clock;
3081
+ _fakingTime;
3082
+ _fakingDate;
3083
+ _fakeTimers;
3084
+ _userConfig;
3085
+ _now = RealDate.now;
3086
+ constructor({
3087
+ global,
3088
+ config
3089
+ }) {
3090
+ this._userConfig = config;
3091
+ this._fakingDate = false;
3092
+ this._fakingTime = false;
3093
+ this._fakeTimers = fakeTimersSrcExports.withGlobal(global);
3094
+ }
3095
+ clearAllTimers() {
3096
+ if (this._fakingTime)
3097
+ this._clock.reset();
3098
+ }
3099
+ dispose() {
3100
+ this.useRealTimers();
3101
+ }
3102
+ runAllTimers() {
3103
+ if (this._checkFakeTimers())
3104
+ this._clock.runAll();
3105
+ }
3106
+ async runAllTimersAsync() {
3107
+ if (this._checkFakeTimers())
3108
+ await this._clock.runAllAsync();
3109
+ }
3110
+ runOnlyPendingTimers() {
3111
+ if (this._checkFakeTimers())
3112
+ this._clock.runToLast();
3113
+ }
3114
+ async runOnlyPendingTimersAsync() {
3115
+ if (this._checkFakeTimers())
3116
+ await this._clock.runToLastAsync();
3117
+ }
3118
+ advanceTimersToNextTimer(steps = 1) {
3119
+ if (this._checkFakeTimers()) {
3120
+ for (let i = steps; i > 0; i--) {
3121
+ this._clock.next();
3122
+ this._clock.tick(0);
3123
+ if (this._clock.countTimers() === 0)
3124
+ break;
3125
+ }
3126
+ }
3127
+ }
3128
+ async advanceTimersToNextTimerAsync(steps = 1) {
3129
+ if (this._checkFakeTimers()) {
3130
+ for (let i = steps; i > 0; i--) {
3131
+ await this._clock.nextAsync();
3132
+ this._clock.tick(0);
3133
+ if (this._clock.countTimers() === 0)
3134
+ break;
3135
+ }
3136
+ }
3137
+ }
3138
+ advanceTimersByTime(msToRun) {
3139
+ if (this._checkFakeTimers())
3140
+ this._clock.tick(msToRun);
3141
+ }
3142
+ async advanceTimersByTimeAsync(msToRun) {
3143
+ if (this._checkFakeTimers())
3144
+ await this._clock.tickAsync(msToRun);
3145
+ }
3146
+ runAllTicks() {
3147
+ if (this._checkFakeTimers()) {
3148
+ this._clock.runMicrotasks();
3149
+ }
3150
+ }
3151
+ useRealTimers() {
3152
+ if (this._fakingDate) {
3153
+ resetDate();
3154
+ this._fakingDate = false;
3155
+ }
3156
+ if (this._fakingTime) {
3157
+ this._clock.uninstall();
3158
+ this._fakingTime = false;
3159
+ }
3160
+ }
3161
+ useFakeTimers() {
3162
+ if (this._fakingDate) {
3163
+ throw new Error(
3164
+ '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.'
3165
+ );
3166
+ }
3167
+ if (!this._fakingTime) {
3168
+ const toFake = Object.keys(this._fakeTimers.timers);
3169
+ this._clock = this._fakeTimers.install({
3170
+ now: Date.now(),
3171
+ toFake,
3172
+ ...this._userConfig
3173
+ });
3174
+ this._fakingTime = true;
3175
+ }
3176
+ }
3177
+ reset() {
3178
+ if (this._checkFakeTimers()) {
3179
+ const { now } = this._clock;
3180
+ this._clock.reset();
3181
+ this._clock.setSystemTime(now);
3182
+ }
3183
+ }
3184
+ setSystemTime(now) {
3185
+ if (this._fakingTime) {
3186
+ this._clock.setSystemTime(now);
3187
+ } else {
3188
+ mockDate(now ?? this.getRealSystemTime());
3189
+ this._fakingDate = true;
3190
+ }
3191
+ }
3192
+ getRealSystemTime() {
3193
+ return this._now();
3194
+ }
3195
+ getTimerCount() {
3196
+ if (this._checkFakeTimers())
3197
+ return this._clock.countTimers();
3198
+ return 0;
3199
+ }
3200
+ configure(config) {
3201
+ this._userConfig = config;
3202
+ }
3203
+ _checkFakeTimers() {
3204
+ if (!this._fakingTime) {
3205
+ throw new Error(
3206
+ 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.'
3207
+ );
3208
+ }
3209
+ return this._fakingTime;
3210
+ }
3211
+ }
3212
+
3213
+ function createVitest() {
3214
+ const _mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, {
3215
+ get(name) {
3216
+ throw new Error(
3217
+ `Vitest mocker was not initialized in this environment. vi.${name}() is forbidden.`
3218
+ );
3219
+ }
3220
+ });
3221
+ let _mockedDate = null;
3222
+ let _config = null;
3223
+ const workerState = getWorkerState();
3224
+ if (!workerState) {
3225
+ const errorMsg = 'Vitest failed to access its internal state.\n\nOne of the following is possible:\n- "vitest" is imported directly without running "vitest" command\n- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
3226
+ throw new Error(errorMsg);
3227
+ }
3228
+ const _timers = new FakeTimers({
3229
+ global: globalThis,
3230
+ config: workerState.config.fakeTimers
3231
+ });
3232
+ const _stubsGlobal = /* @__PURE__ */ new Map();
3233
+ const _stubsEnv = /* @__PURE__ */ new Map();
3234
+ const getImporter = () => {
3235
+ const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 });
3236
+ const importerStack = stackTrace.split("\n")[4];
3237
+ const stack = parseSingleStack(importerStack);
3238
+ return (stack == null ? void 0 : stack.file) || "";
3239
+ };
3240
+ return {
3241
+ useFakeTimers(config) {
3242
+ if (config) {
3243
+ _timers.configure(config);
3244
+ } else {
3245
+ const workerState2 = getWorkerState();
3246
+ _timers.configure(workerState2.config.fakeTimers);
3247
+ }
3248
+ _timers.useFakeTimers();
3249
+ return this;
3250
+ },
3251
+ useRealTimers() {
3252
+ _timers.useRealTimers();
3253
+ _mockedDate = null;
3254
+ return this;
3255
+ },
3256
+ runOnlyPendingTimers() {
3257
+ _timers.runOnlyPendingTimers();
3258
+ return this;
3259
+ },
3260
+ async runOnlyPendingTimersAsync() {
3261
+ await _timers.runOnlyPendingTimersAsync();
3262
+ return this;
3263
+ },
3264
+ runAllTimers() {
3265
+ _timers.runAllTimers();
3266
+ return this;
3267
+ },
3268
+ async runAllTimersAsync() {
3269
+ await _timers.runAllTimersAsync();
3270
+ return this;
3271
+ },
3272
+ runAllTicks() {
3273
+ _timers.runAllTicks();
3274
+ return this;
3275
+ },
3276
+ advanceTimersByTime(ms) {
3277
+ _timers.advanceTimersByTime(ms);
3278
+ return this;
3279
+ },
3280
+ async advanceTimersByTimeAsync(ms) {
3281
+ await _timers.advanceTimersByTimeAsync(ms);
3282
+ return this;
3283
+ },
3284
+ advanceTimersToNextTimer() {
3285
+ _timers.advanceTimersToNextTimer();
3286
+ return this;
3287
+ },
3288
+ async advanceTimersToNextTimerAsync() {
3289
+ await _timers.advanceTimersToNextTimerAsync();
3290
+ return this;
3291
+ },
3292
+ getTimerCount() {
3293
+ return _timers.getTimerCount();
3294
+ },
3295
+ setSystemTime(time) {
3296
+ const date = time instanceof Date ? time : new Date(time);
3297
+ _mockedDate = date;
3298
+ _timers.setSystemTime(date);
3299
+ return this;
3300
+ },
3301
+ getMockedSystemTime() {
3302
+ return _mockedDate;
3303
+ },
3304
+ getRealSystemTime() {
3305
+ return _timers.getRealSystemTime();
3306
+ },
3307
+ clearAllTimers() {
3308
+ _timers.clearAllTimers();
3309
+ return this;
3310
+ },
3311
+ // mocks
3312
+ spyOn,
3313
+ fn,
3314
+ hoisted(factory) {
3315
+ assertTypes(factory, '"vi.hoisted" factory', ["function"]);
3316
+ return factory();
3317
+ },
3318
+ mock(path, factory) {
3319
+ const importer = getImporter();
3320
+ _mocker.queueMock(
3321
+ path,
3322
+ importer,
3323
+ factory ? () => factory(() => _mocker.importActual(path, importer)) : void 0
3324
+ );
3325
+ },
3326
+ unmock(path) {
3327
+ _mocker.queueUnmock(path, getImporter());
3328
+ },
3329
+ doMock(path, factory) {
3330
+ _mocker.queueMock(path, getImporter(), factory);
3331
+ },
3332
+ doUnmock(path) {
3333
+ _mocker.queueUnmock(path, getImporter());
3334
+ },
3335
+ async importActual(path) {
3336
+ return _mocker.importActual(path, getImporter());
3337
+ },
3338
+ async importMock(path) {
3339
+ return _mocker.importMock(path, getImporter());
3340
+ },
3341
+ mocked(item, _options = {}) {
3342
+ return item;
3343
+ },
3344
+ isMockFunction(fn2) {
3345
+ return isMockFunction(fn2);
3346
+ },
3347
+ clearAllMocks() {
3348
+ spies.forEach((spy) => spy.mockClear());
3349
+ return this;
3350
+ },
3351
+ resetAllMocks() {
3352
+ spies.forEach((spy) => spy.mockReset());
3353
+ return this;
3354
+ },
3355
+ restoreAllMocks() {
3356
+ spies.forEach((spy) => spy.mockRestore());
3357
+ return this;
3358
+ },
3359
+ stubGlobal(name, value) {
3360
+ if (!_stubsGlobal.has(name))
3361
+ _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
3362
+ Object.defineProperty(globalThis, name, {
3363
+ value,
3364
+ writable: true,
3365
+ configurable: true,
3366
+ enumerable: true
3367
+ });
3368
+ return this;
3369
+ },
3370
+ stubEnv(name, value) {
3371
+ if (!_stubsEnv.has(name))
3372
+ _stubsEnv.set(name, process.env[name]);
3373
+ process.env[name] = value;
3374
+ return this;
3375
+ },
3376
+ unstubAllGlobals() {
3377
+ _stubsGlobal.forEach((original, name) => {
3378
+ if (!original)
3379
+ Reflect.deleteProperty(globalThis, name);
3380
+ else
3381
+ Object.defineProperty(globalThis, name, original);
3382
+ });
3383
+ _stubsGlobal.clear();
3384
+ return this;
3385
+ },
3386
+ unstubAllEnvs() {
3387
+ _stubsEnv.forEach((original, name) => {
3388
+ if (original === void 0)
3389
+ delete process.env[name];
3390
+ else
3391
+ process.env[name] = original;
3392
+ });
3393
+ _stubsEnv.clear();
3394
+ return this;
3395
+ },
3396
+ resetModules() {
3397
+ const state = getWorkerState();
3398
+ resetModules(state.moduleCache);
3399
+ return this;
3400
+ },
3401
+ async dynamicImportSettled() {
3402
+ return waitForImportsToResolve();
3403
+ },
3404
+ setConfig(config) {
3405
+ const state = getWorkerState();
3406
+ if (!_config)
3407
+ _config = { ...state.config };
3408
+ Object.assign(state.config, config);
3409
+ },
3410
+ resetConfig() {
3411
+ if (_config) {
3412
+ const state = getWorkerState();
3413
+ Object.assign(state.config, _config);
3414
+ }
3415
+ }
3416
+ };
3417
+ }
3418
+ const vitest = createVitest();
3419
+ const vi = vitest;
3420
+
3421
+ export { RealDate as R, getBenchOptions as a, getBenchFn as b, createExpect as c, globalExpect as d, bench as e, vitest as f, getSnapshotClient as g, setupChaiConfig as s, vi as v };