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