vitest 2.1.1 → 2.1.2

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