@fangorn-network/sdk 0.1.0-dev

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 (102) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +80 -0
  3. package/lib/cli/cli.d.ts +2 -0
  4. package/lib/cli/cli.js +571 -0
  5. package/lib/cli/index.d.ts +10 -0
  6. package/lib/cli/index.js +18 -0
  7. package/lib/cli/sell.d.ts +28 -0
  8. package/lib/cli/sell.js +95 -0
  9. package/lib/cli/stage.d.ts +19 -0
  10. package/lib/cli/stage.js +94 -0
  11. package/lib/config.d.ts +697 -0
  12. package/lib/config.js +45 -0
  13. package/lib/contracts/data-registry/abi.d.ts +442 -0
  14. package/lib/contracts/data-registry/abi.js +508 -0
  15. package/lib/contracts/data-registry/index.d.ts +131 -0
  16. package/lib/contracts/data-registry/index.js +183 -0
  17. package/lib/contracts/index.d.ts +6 -0
  18. package/lib/contracts/index.js +6 -0
  19. package/lib/contracts/logs.d.ts +17 -0
  20. package/lib/contracts/logs.js +28 -0
  21. package/lib/contracts/settlement-registry/abi.d.ts +810 -0
  22. package/lib/contracts/settlement-registry/abi.js +962 -0
  23. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  24. package/lib/contracts/settlement-registry/index.js +213 -0
  25. package/lib/contracts/write.d.ts +59 -0
  26. package/lib/contracts/write.js +102 -0
  27. package/lib/crypto/aes.d.ts +19 -0
  28. package/lib/crypto/aes.js +26 -0
  29. package/lib/crypto/encryption.d.ts +38 -0
  30. package/lib/crypto/encryption.js +68 -0
  31. package/lib/crypto/paid.d.ts +104 -0
  32. package/lib/crypto/paid.js +147 -0
  33. package/lib/crypto/rand.d.ts +5 -0
  34. package/lib/crypto/rand.js +16 -0
  35. package/lib/crypto/types.d.ts +23 -0
  36. package/lib/crypto/types.js +1 -0
  37. package/lib/engine/car.d.ts +14 -0
  38. package/lib/engine/car.js +42 -0
  39. package/lib/engine/index.d.ts +206 -0
  40. package/lib/engine/index.js +377 -0
  41. package/lib/engine/records.d.ts +121 -0
  42. package/lib/engine/records.js +239 -0
  43. package/lib/engine/test-helpers.d.ts +38 -0
  44. package/lib/engine/test-helpers.js +63 -0
  45. package/lib/erc8004.d.ts +56 -0
  46. package/lib/erc8004.js +140 -0
  47. package/lib/fangorn.d.ts +342 -0
  48. package/lib/fangorn.js +642 -0
  49. package/lib/feed.d.ts +34 -0
  50. package/lib/feed.js +67 -0
  51. package/lib/index.d.ts +17 -0
  52. package/lib/index.js +16 -0
  53. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  54. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  55. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  56. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  57. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  58. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  59. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  60. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  61. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  62. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  64. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  65. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  66. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  67. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  68. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  69. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  70. package/lib/node_modules/chai/index.js +2874 -0
  71. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  72. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  73. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  74. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  75. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  76. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  77. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  78. package/lib/providers/storage/car.d.ts +36 -0
  79. package/lib/providers/storage/car.js +81 -0
  80. package/lib/providers/storage/index.d.ts +5 -0
  81. package/lib/providers/storage/index.js +5 -0
  82. package/lib/providers/storage/pinata.d.ts +53 -0
  83. package/lib/providers/storage/pinata.js +178 -0
  84. package/lib/providers/storage/signed-url.d.ts +54 -0
  85. package/lib/providers/storage/signed-url.js +122 -0
  86. package/lib/providers/storage/types.d.ts +62 -0
  87. package/lib/providers/storage/types.js +1 -0
  88. package/lib/providers/storage/utils.d.ts +30 -0
  89. package/lib/providers/storage/utils.js +107 -0
  90. package/lib/repo/index.d.ts +56 -0
  91. package/lib/repo/index.js +73 -0
  92. package/lib/test/key-server.d.ts +12 -0
  93. package/lib/test/key-server.js +30 -0
  94. package/lib/test/mem-registry.d.ts +46 -0
  95. package/lib/test/mem-registry.js +114 -0
  96. package/lib/test/sdk-suite.d.ts +10 -0
  97. package/lib/test/sdk-suite.js +155 -0
  98. package/lib/test/testbed.d.ts +16786 -0
  99. package/lib/test/testbed.js +175 -0
  100. package/lib/types/index.d.ts +37 -0
  101. package/lib/types/index.js +1 -0
  102. package/package.json +87 -0
@@ -0,0 +1,2578 @@
1
+ import { assertTypes, createSimpleStackTrace } from "../../../@vitest/utils/dist/helpers.js";
2
+ import { clearAllMocks, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn } from "../../../@vitest/spy/dist/index.js";
3
+ import { Assertion, assert as assert$1, expect, should as should$1, use, utils_exports } from "../../../chai/index.js";
4
+ import { ASYMMETRIC_MATCHERS_OBJECT, GLOBAL_EXPECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, addCustomEqualityTesters, customMatchers, equals, getState, iterableEquality, setState, subsetEquality } from "../../../@vitest/expect/dist/index.js";
5
+ import { delay, getSafeTimers } from "../../../@vitest/utils/dist/timers.js";
6
+ import { parseSingleStack } from "../../../@vitest/utils/dist/source-map.js";
7
+ import { getNames } from "../../../@vitest/runner/dist/chunk-tasks.js";
8
+ import { getCurrentTest } from "../../../@vitest/runner/dist/index.js";
9
+ import { getWorkerState, isChildProcess, resetModules, waitForImportsToResolve } from "./utils.DvEY5TfP.js";
10
+ import "../../../@vitest/runner/dist/utils.js";
11
+ import { SnapshotClient, addSerializer, stripSnapshotIndentation } from "../../../@vitest/snapshot/dist/index.js";
12
+ import { commonjsGlobal } from "./_commonjsHelpers.D26ty3Ew.js";
13
+ import { RealDate, mockDate, resetDate } from "./date.Bq6ZW5rf.js";
14
+
15
+ //#region node_modules/vitest/dist/chunks/vi.2VT5v0um.js
16
+ const unsupported = [
17
+ "matchSnapshot",
18
+ "toMatchSnapshot",
19
+ "toMatchInlineSnapshot",
20
+ "toThrowErrorMatchingSnapshot",
21
+ "toThrowErrorMatchingInlineSnapshot",
22
+ "throws",
23
+ "Throw",
24
+ "throw",
25
+ "toThrow",
26
+ "toThrowError"
27
+ ];
28
+ /**
29
+ * Attaches a `cause` property to the error if missing, copies the stack trace from the source, and throws.
30
+ *
31
+ * @param error - The error to throw
32
+ * @param source - Error to copy the stack trace from
33
+ *
34
+ * @throws Always throws the provided error with an amended stack trace
35
+ */
36
+ function throwWithCause(error, source) {
37
+ if (error.cause == null) error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.");
38
+ throw copyStackTrace$1(error, source);
39
+ }
40
+ function createExpectPoll(expect$1) {
41
+ return function poll(fn$1, options = {}) {
42
+ const defaults = getWorkerState().config.expect?.poll ?? {};
43
+ const { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options;
44
+ const assertion = expect$1(null, message).withContext({ poll: true });
45
+ fn$1 = fn$1.bind(assertion);
46
+ const test = utils_exports.flag(assertion, "vitest-test");
47
+ if (!test) throw new Error("expect.poll() must be called inside a test");
48
+ const proxy = new Proxy(assertion, { get(target, key, receiver) {
49
+ const assertionFunction = Reflect.get(target, key, receiver);
50
+ if (typeof assertionFunction !== "function") return assertionFunction instanceof Assertion ? proxy : assertionFunction;
51
+ if (key === "assert") return assertionFunction;
52
+ if (typeof key === "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
53
+ return function(...args) {
54
+ const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
55
+ const promise = async () => {
56
+ const { setTimeout, clearTimeout } = getSafeTimers();
57
+ let executionPhase = "fn";
58
+ let hasTimedOut = false;
59
+ const timerId = setTimeout(() => {
60
+ hasTimedOut = true;
61
+ }, timeout);
62
+ utils_exports.flag(assertion, "_name", key);
63
+ try {
64
+ while (true) {
65
+ const isLastAttempt = hasTimedOut;
66
+ if (isLastAttempt) utils_exports.flag(assertion, "_isLastPollAttempt", true);
67
+ try {
68
+ executionPhase = "fn";
69
+ const obj = await fn$1();
70
+ utils_exports.flag(assertion, "object", obj);
71
+ executionPhase = "assertion";
72
+ return await assertionFunction.call(assertion, ...args);
73
+ } catch (err) {
74
+ if (isLastAttempt || executionPhase === "assertion" && utils_exports.flag(assertion, "_poll.assert_once")) throwWithCause(err, STACK_TRACE_ERROR);
75
+ await delay(interval, setTimeout);
76
+ }
77
+ }
78
+ } finally {
79
+ clearTimeout(timerId);
80
+ }
81
+ };
82
+ let awaited = false;
83
+ test.onFinished ??= [];
84
+ test.onFinished.push(() => {
85
+ if (!awaited) {
86
+ const negated = utils_exports.flag(assertion, "negate") ? "not." : "";
87
+ const assertionString = `expect.${utils_exports.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`;
88
+ throw copyStackTrace$1(/* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`), STACK_TRACE_ERROR);
89
+ }
90
+ });
91
+ let resultPromise;
92
+ return {
93
+ then(onFulfilled, onRejected) {
94
+ awaited = true;
95
+ return (resultPromise ||= promise()).then(onFulfilled, onRejected);
96
+ },
97
+ catch(onRejected) {
98
+ return (resultPromise ||= promise()).catch(onRejected);
99
+ },
100
+ finally(onFinally) {
101
+ return (resultPromise ||= promise()).finally(onFinally);
102
+ },
103
+ [Symbol.toStringTag]: "Promise"
104
+ };
105
+ };
106
+ } });
107
+ return proxy;
108
+ };
109
+ }
110
+ function copyStackTrace$1(target, source) {
111
+ if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
112
+ return target;
113
+ }
114
+ function createAssertionMessage(util, assertion, hasArgs) {
115
+ const not = util.flag(assertion, "negate") ? "not." : "";
116
+ const name = `${util.flag(assertion, "_name")}(expected)`;
117
+ const promiseName = util.flag(assertion, "promise");
118
+ return `expect(actual)${promiseName ? `.${promiseName}` : ""}.${not}${name}`;
119
+ }
120
+ function recordAsyncExpect(_test, promise, assertion, error) {
121
+ const test = _test;
122
+ if (test && promise instanceof Promise) {
123
+ promise = promise.finally(() => {
124
+ if (!test.promises) return;
125
+ const index = test.promises.indexOf(promise);
126
+ if (index !== -1) test.promises.splice(index, 1);
127
+ });
128
+ if (!test.promises) test.promises = [];
129
+ test.promises.push(promise);
130
+ let resolved = false;
131
+ test.onFinished ??= [];
132
+ test.onFinished.push(() => {
133
+ if (!resolved) {
134
+ const stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
135
+ console.warn([
136
+ `Promise returned by \`${assertion}\` was not awaited. `,
137
+ "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
138
+ "Please remember to await the assertion.\n",
139
+ stack
140
+ ].join(""));
141
+ }
142
+ });
143
+ return {
144
+ then(onFulfilled, onRejected) {
145
+ resolved = true;
146
+ return promise.then(onFulfilled, onRejected);
147
+ },
148
+ catch(onRejected) {
149
+ return promise.catch(onRejected);
150
+ },
151
+ finally(onFinally) {
152
+ return promise.finally(onFinally);
153
+ },
154
+ [Symbol.toStringTag]: "Promise"
155
+ };
156
+ }
157
+ return promise;
158
+ }
159
+ let _client;
160
+ function getSnapshotClient() {
161
+ if (!_client) _client = new SnapshotClient({ isEqual: (received, expected) => {
162
+ return equals(received, expected, [iterableEquality, subsetEquality]);
163
+ } });
164
+ return _client;
165
+ }
166
+ function getError(expected, promise) {
167
+ if (typeof expected !== "function") {
168
+ if (!promise) throw new Error(`expected must be a function, received ${typeof expected}`);
169
+ return expected;
170
+ }
171
+ try {
172
+ expected();
173
+ } catch (e) {
174
+ return e;
175
+ }
176
+ throw new Error("snapshot function didn't throw");
177
+ }
178
+ function getTestNames(test) {
179
+ return {
180
+ filepath: test.file.filepath,
181
+ name: getNames(test).slice(1).join(" > "),
182
+ testId: test.id
183
+ };
184
+ }
185
+ const SnapshotPlugin = (chai, utils) => {
186
+ function getTest(assertionName, obj) {
187
+ const test = utils.flag(obj, "vitest-test");
188
+ if (!test) throw new Error(`'${assertionName}' cannot be used without test context`);
189
+ return test;
190
+ }
191
+ for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
192
+ utils.flag(this, "_name", key);
193
+ if (utils.flag(this, "negate")) throw new Error(`${key} cannot be used with "not"`);
194
+ const expected = utils.flag(this, "object");
195
+ const test = getTest(key, this);
196
+ if (typeof properties === "string" && typeof message === "undefined") {
197
+ message = properties;
198
+ properties = void 0;
199
+ }
200
+ const errorMessage = utils.flag(this, "message");
201
+ getSnapshotClient().assert({
202
+ received: expected,
203
+ message,
204
+ isInline: false,
205
+ properties,
206
+ errorMessage,
207
+ ...getTestNames(test)
208
+ });
209
+ });
210
+ utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
211
+ utils.flag(this, "_name", "toMatchFileSnapshot");
212
+ if (utils.flag(this, "negate")) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
213
+ const error = /* @__PURE__ */ new Error("resolves");
214
+ const expected = utils.flag(this, "object");
215
+ const test = getTest("toMatchFileSnapshot", this);
216
+ const errorMessage = utils.flag(this, "message");
217
+ return recordAsyncExpect(test, getSnapshotClient().assertRaw({
218
+ received: expected,
219
+ message,
220
+ isInline: false,
221
+ rawSnapshot: { file },
222
+ errorMessage,
223
+ ...getTestNames(test)
224
+ }), createAssertionMessage(utils, this), error);
225
+ });
226
+ utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
227
+ utils.flag(this, "_name", "toMatchInlineSnapshot");
228
+ if (utils.flag(this, "negate")) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
229
+ const test = getTest("toMatchInlineSnapshot", this);
230
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
231
+ const expected = utils.flag(this, "object");
232
+ const error = utils.flag(this, "error");
233
+ if (typeof properties === "string") {
234
+ message = inlineSnapshot;
235
+ inlineSnapshot = properties;
236
+ properties = void 0;
237
+ }
238
+ if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
239
+ const errorMessage = utils.flag(this, "message");
240
+ getSnapshotClient().assert({
241
+ received: expected,
242
+ message,
243
+ isInline: true,
244
+ properties,
245
+ inlineSnapshot,
246
+ error,
247
+ errorMessage,
248
+ ...getTestNames(test)
249
+ });
250
+ });
251
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
252
+ utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
253
+ if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
254
+ const expected = utils.flag(this, "object");
255
+ const test = getTest("toThrowErrorMatchingSnapshot", this);
256
+ const promise = utils.flag(this, "promise");
257
+ const errorMessage = utils.flag(this, "message");
258
+ getSnapshotClient().assert({
259
+ received: getError(expected, promise),
260
+ message,
261
+ errorMessage,
262
+ ...getTestNames(test)
263
+ });
264
+ });
265
+ utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
266
+ if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
267
+ const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
268
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
269
+ const expected = utils.flag(this, "object");
270
+ const error = utils.flag(this, "error");
271
+ const promise = utils.flag(this, "promise");
272
+ const errorMessage = utils.flag(this, "message");
273
+ if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
274
+ getSnapshotClient().assert({
275
+ received: getError(expected, promise),
276
+ message,
277
+ inlineSnapshot,
278
+ isInline: true,
279
+ error,
280
+ errorMessage,
281
+ ...getTestNames(test)
282
+ });
283
+ });
284
+ utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
285
+ };
286
+ use(JestExtend);
287
+ use(JestChaiExpect);
288
+ use(SnapshotPlugin);
289
+ use(JestAsymmetricMatchers);
290
+ function createExpect(test) {
291
+ const expect$1 = ((value, message) => {
292
+ const { assertionCalls } = getState(expect$1);
293
+ setState({ assertionCalls: assertionCalls + 1 }, expect$1);
294
+ const assert$2 = expect(value, message);
295
+ const _test = test || getCurrentTest();
296
+ if (_test) return assert$2.withTest(_test);
297
+ else return assert$2;
298
+ });
299
+ Object.assign(expect$1, expect);
300
+ Object.assign(expect$1, globalThis[ASYMMETRIC_MATCHERS_OBJECT]);
301
+ expect$1.getState = () => getState(expect$1);
302
+ expect$1.setState = (state) => setState(state, expect$1);
303
+ const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
304
+ setState({
305
+ ...globalState,
306
+ assertionCalls: 0,
307
+ isExpectingAssertions: false,
308
+ isExpectingAssertionsError: null,
309
+ expectedAssertionsNumber: null,
310
+ expectedAssertionsNumberErrorGen: null,
311
+ get testPath() {
312
+ return getWorkerState().filepath;
313
+ },
314
+ currentTestName: test ? test.fullTestName ?? "" : globalState.currentTestName
315
+ }, expect$1);
316
+ expect$1.assert = assert$1;
317
+ expect$1.extend = (matchers) => expect.extend(expect$1, matchers);
318
+ expect$1.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters);
319
+ expect$1.soft = (...args) => {
320
+ return expect$1(...args).withContext({ soft: true });
321
+ };
322
+ expect$1.poll = createExpectPoll(expect$1);
323
+ expect$1.unreachable = (message) => {
324
+ assert$1.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
325
+ };
326
+ function assertions(expected) {
327
+ const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect$1.getState().assertionCalls}`);
328
+ if (Error.captureStackTrace) Error.captureStackTrace(errorGen(), assertions);
329
+ expect$1.setState({
330
+ expectedAssertionsNumber: expected,
331
+ expectedAssertionsNumberErrorGen: errorGen
332
+ });
333
+ }
334
+ function hasAssertions() {
335
+ const error = /* @__PURE__ */ new Error("expected any number of assertion, but got none");
336
+ if (Error.captureStackTrace) Error.captureStackTrace(error, hasAssertions);
337
+ expect$1.setState({
338
+ isExpectingAssertions: true,
339
+ isExpectingAssertionsError: error
340
+ });
341
+ }
342
+ utils_exports.addMethod(expect$1, "assertions", assertions);
343
+ utils_exports.addMethod(expect$1, "hasAssertions", hasAssertions);
344
+ expect$1.extend(customMatchers);
345
+ return expect$1;
346
+ }
347
+ const globalExpect = createExpect();
348
+ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
349
+ value: globalExpect,
350
+ writable: true,
351
+ configurable: true
352
+ });
353
+ const assert = assert$1;
354
+ const should = should$1;
355
+ var fakeTimersSrc = {};
356
+ var global;
357
+ var hasRequiredGlobal;
358
+ function requireGlobal() {
359
+ if (hasRequiredGlobal) return global;
360
+ hasRequiredGlobal = 1;
361
+ /**
362
+ * A reference to the global object
363
+ * @type {object} globalObject
364
+ */
365
+ var globalObject;
366
+ /* istanbul ignore else */
367
+ if (typeof commonjsGlobal !== "undefined") globalObject = commonjsGlobal;
368
+ else if (typeof window !== "undefined") globalObject = window;
369
+ else globalObject = self;
370
+ global = globalObject;
371
+ return global;
372
+ }
373
+ var throwsOnProto_1;
374
+ var hasRequiredThrowsOnProto;
375
+ function requireThrowsOnProto() {
376
+ if (hasRequiredThrowsOnProto) return throwsOnProto_1;
377
+ hasRequiredThrowsOnProto = 1;
378
+ /**
379
+ * Is true when the environment causes an error to be thrown for accessing the
380
+ * __proto__ property.
381
+ * This is necessary in order to support `node --disable-proto=throw`.
382
+ *
383
+ * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
384
+ * @type {boolean}
385
+ */
386
+ let throwsOnProto;
387
+ try {
388
+ ({}).__proto__;
389
+ throwsOnProto = false;
390
+ } catch (_) {
391
+ /* istanbul ignore next */
392
+ throwsOnProto = true;
393
+ }
394
+ throwsOnProto_1 = throwsOnProto;
395
+ return throwsOnProto_1;
396
+ }
397
+ var copyPrototypeMethods;
398
+ var hasRequiredCopyPrototypeMethods;
399
+ function requireCopyPrototypeMethods() {
400
+ if (hasRequiredCopyPrototypeMethods) return copyPrototypeMethods;
401
+ hasRequiredCopyPrototypeMethods = 1;
402
+ var call = Function.call;
403
+ var throwsOnProto = requireThrowsOnProto();
404
+ var disallowedProperties = [
405
+ "size",
406
+ "caller",
407
+ "callee",
408
+ "arguments"
409
+ ];
410
+ /* istanbul ignore next */
411
+ if (throwsOnProto) disallowedProperties.push("__proto__");
412
+ copyPrototypeMethods = function copyPrototypeMethods$1(prototype) {
413
+ return Object.getOwnPropertyNames(prototype).reduce(function(result, name) {
414
+ if (disallowedProperties.includes(name)) return result;
415
+ if (typeof prototype[name] !== "function") return result;
416
+ result[name] = call.bind(prototype[name]);
417
+ return result;
418
+ }, Object.create(null));
419
+ };
420
+ return copyPrototypeMethods;
421
+ }
422
+ var array;
423
+ var hasRequiredArray;
424
+ function requireArray() {
425
+ if (hasRequiredArray) return array;
426
+ hasRequiredArray = 1;
427
+ array = requireCopyPrototypeMethods()(Array.prototype);
428
+ return array;
429
+ }
430
+ var calledInOrder_1;
431
+ var hasRequiredCalledInOrder;
432
+ function requireCalledInOrder() {
433
+ if (hasRequiredCalledInOrder) return calledInOrder_1;
434
+ hasRequiredCalledInOrder = 1;
435
+ var every$1 = requireArray().every;
436
+ /**
437
+ * @private
438
+ */
439
+ function hasCallsLeft(callMap, spy) {
440
+ if (callMap[spy.id] === void 0) callMap[spy.id] = 0;
441
+ return callMap[spy.id] < spy.callCount;
442
+ }
443
+ /**
444
+ * @private
445
+ */
446
+ function checkAdjacentCalls(callMap, spy, index, spies) {
447
+ var calledBeforeNext = true;
448
+ if (index !== spies.length - 1) calledBeforeNext = spy.calledBefore(spies[index + 1]);
449
+ if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
450
+ callMap[spy.id] += 1;
451
+ return true;
452
+ }
453
+ return false;
454
+ }
455
+ /**
456
+ * A Sinon proxy object (fake, spy, stub)
457
+ * @typedef {object} SinonProxy
458
+ * @property {Function} calledBefore - A method that determines if this proxy was called before another one
459
+ * @property {string} id - Some id
460
+ * @property {number} callCount - Number of times this proxy has been called
461
+ */
462
+ /**
463
+ * Returns true when the spies have been called in the order they were supplied in
464
+ * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
465
+ * @returns {boolean} true when spies are called in order, false otherwise
466
+ */
467
+ function calledInOrder(spies) {
468
+ return every$1(arguments.length > 1 ? arguments : spies, checkAdjacentCalls.bind(null, {}));
469
+ }
470
+ calledInOrder_1 = calledInOrder;
471
+ return calledInOrder_1;
472
+ }
473
+ var className_1;
474
+ var hasRequiredClassName;
475
+ function requireClassName() {
476
+ if (hasRequiredClassName) return className_1;
477
+ hasRequiredClassName = 1;
478
+ /**
479
+ * Returns a display name for a value from a constructor
480
+ * @param {object} value A value to examine
481
+ * @returns {(string|null)} A string or null
482
+ */
483
+ function className(value) {
484
+ return value.constructor && value.constructor.name || null;
485
+ }
486
+ className_1 = className;
487
+ return className_1;
488
+ }
489
+ var deprecated = {};
490
+ var hasRequiredDeprecated;
491
+ function requireDeprecated() {
492
+ if (hasRequiredDeprecated) return deprecated;
493
+ hasRequiredDeprecated = 1;
494
+ (function(exports$1) {
495
+ /**
496
+ * Returns a function that will invoke the supplied function and print a
497
+ * deprecation warning to the console each time it is called.
498
+ * @param {Function} func
499
+ * @param {string} msg
500
+ * @returns {Function}
501
+ */
502
+ exports$1.wrap = function(func, msg) {
503
+ var wrapped = function() {
504
+ exports$1.printWarning(msg);
505
+ return func.apply(this, arguments);
506
+ };
507
+ if (func.prototype) wrapped.prototype = func.prototype;
508
+ return wrapped;
509
+ };
510
+ /**
511
+ * Returns a string which can be supplied to `wrap()` to notify the user that a
512
+ * particular part of the sinon API has been deprecated.
513
+ * @param {string} packageName
514
+ * @param {string} funcName
515
+ * @returns {string}
516
+ */
517
+ exports$1.defaultMsg = function(packageName, funcName) {
518
+ return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
519
+ };
520
+ /**
521
+ * Prints a warning on the console, when it exists
522
+ * @param {string} msg
523
+ * @returns {undefined}
524
+ */
525
+ exports$1.printWarning = function(msg) {
526
+ /* istanbul ignore next */
527
+ if (typeof process === "object" && process.emitWarning) process.emitWarning(msg);
528
+ else if (console.info) console.info(msg);
529
+ else console.log(msg);
530
+ };
531
+ })(deprecated);
532
+ return deprecated;
533
+ }
534
+ var every;
535
+ var hasRequiredEvery;
536
+ function requireEvery() {
537
+ if (hasRequiredEvery) return every;
538
+ hasRequiredEvery = 1;
539
+ /**
540
+ * Returns true when fn returns true for all members of obj.
541
+ * This is an every implementation that works for all iterables
542
+ * @param {object} obj
543
+ * @param {Function} fn
544
+ * @returns {boolean}
545
+ */
546
+ every = function every$1(obj, fn$1) {
547
+ var pass = true;
548
+ try {
549
+ obj.forEach(function() {
550
+ if (!fn$1.apply(this, arguments)) throw new Error();
551
+ });
552
+ } catch (e) {
553
+ pass = false;
554
+ }
555
+ return pass;
556
+ };
557
+ return every;
558
+ }
559
+ var functionName;
560
+ var hasRequiredFunctionName;
561
+ function requireFunctionName() {
562
+ if (hasRequiredFunctionName) return functionName;
563
+ hasRequiredFunctionName = 1;
564
+ /**
565
+ * Returns a display name for a function
566
+ * @param {Function} func
567
+ * @returns {string}
568
+ */
569
+ functionName = function functionName$1(func) {
570
+ if (!func) return "";
571
+ try {
572
+ return func.displayName || func.name || (String(func).match(/function ([^\s(]+)/) || [])[1];
573
+ } catch (e) {
574
+ return "";
575
+ }
576
+ };
577
+ return functionName;
578
+ }
579
+ var orderByFirstCall_1;
580
+ var hasRequiredOrderByFirstCall;
581
+ function requireOrderByFirstCall() {
582
+ if (hasRequiredOrderByFirstCall) return orderByFirstCall_1;
583
+ hasRequiredOrderByFirstCall = 1;
584
+ var sort = requireArray().sort;
585
+ var slice = requireArray().slice;
586
+ /**
587
+ * @private
588
+ */
589
+ function comparator(a, b) {
590
+ var aCall = a.getCall(0);
591
+ var bCall = b.getCall(0);
592
+ return (aCall && aCall.callId || -1) < (bCall && bCall.callId || -1) ? -1 : 1;
593
+ }
594
+ /**
595
+ * A Sinon proxy object (fake, spy, stub)
596
+ * @typedef {object} SinonProxy
597
+ * @property {Function} getCall - A method that can return the first call
598
+ */
599
+ /**
600
+ * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
601
+ * @param {SinonProxy[] | SinonProxy} spies
602
+ * @returns {SinonProxy[]}
603
+ */
604
+ function orderByFirstCall(spies) {
605
+ return sort(slice(spies), comparator);
606
+ }
607
+ orderByFirstCall_1 = orderByFirstCall;
608
+ return orderByFirstCall_1;
609
+ }
610
+ var _function;
611
+ var hasRequired_function;
612
+ function require_function() {
613
+ if (hasRequired_function) return _function;
614
+ hasRequired_function = 1;
615
+ _function = requireCopyPrototypeMethods()(Function.prototype);
616
+ return _function;
617
+ }
618
+ var map;
619
+ var hasRequiredMap;
620
+ function requireMap() {
621
+ if (hasRequiredMap) return map;
622
+ hasRequiredMap = 1;
623
+ map = requireCopyPrototypeMethods()(Map.prototype);
624
+ return map;
625
+ }
626
+ var object;
627
+ var hasRequiredObject;
628
+ function requireObject() {
629
+ if (hasRequiredObject) return object;
630
+ hasRequiredObject = 1;
631
+ object = requireCopyPrototypeMethods()(Object.prototype);
632
+ return object;
633
+ }
634
+ var set;
635
+ var hasRequiredSet;
636
+ function requireSet() {
637
+ if (hasRequiredSet) return set;
638
+ hasRequiredSet = 1;
639
+ set = requireCopyPrototypeMethods()(Set.prototype);
640
+ return set;
641
+ }
642
+ var string;
643
+ var hasRequiredString;
644
+ function requireString() {
645
+ if (hasRequiredString) return string;
646
+ hasRequiredString = 1;
647
+ string = requireCopyPrototypeMethods()(String.prototype);
648
+ return string;
649
+ }
650
+ var prototypes;
651
+ var hasRequiredPrototypes;
652
+ function requirePrototypes() {
653
+ if (hasRequiredPrototypes) return prototypes;
654
+ hasRequiredPrototypes = 1;
655
+ prototypes = {
656
+ array: requireArray(),
657
+ function: require_function(),
658
+ map: requireMap(),
659
+ object: requireObject(),
660
+ set: requireSet(),
661
+ string: requireString()
662
+ };
663
+ return prototypes;
664
+ }
665
+ var typeDetect$1 = { exports: {} };
666
+ var typeDetect = typeDetect$1.exports;
667
+ var hasRequiredTypeDetect;
668
+ function requireTypeDetect() {
669
+ if (hasRequiredTypeDetect) return typeDetect$1.exports;
670
+ hasRequiredTypeDetect = 1;
671
+ (function(module, exports$1) {
672
+ (function(global$1, factory) {
673
+ module.exports = factory();
674
+ })(typeDetect, (function() {
675
+ var promiseExists = typeof Promise === "function";
676
+ var globalObject = typeof self === "object" ? self : commonjsGlobal;
677
+ var symbolExists = typeof Symbol !== "undefined";
678
+ var mapExists = typeof Map !== "undefined";
679
+ var setExists = typeof Set !== "undefined";
680
+ var weakMapExists = typeof WeakMap !== "undefined";
681
+ var weakSetExists = typeof WeakSet !== "undefined";
682
+ var dataViewExists = typeof DataView !== "undefined";
683
+ var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== "undefined";
684
+ var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== "undefined";
685
+ var setEntriesExists = setExists && typeof Set.prototype.entries === "function";
686
+ var mapEntriesExists = mapExists && typeof Map.prototype.entries === "function";
687
+ var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Set()).entries());
688
+ var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Map()).entries());
689
+ var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === "function";
690
+ var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
691
+ var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === "function";
692
+ var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(""[Symbol.iterator]());
693
+ var toStringLeftSliceLength = 8;
694
+ var toStringRightSliceLength = -1;
695
+ /**
696
+ * ### typeOf (obj)
697
+ *
698
+ * Uses `Object.prototype.toString` to determine the type of an object,
699
+ * normalising behaviour across engine versions & well optimised.
700
+ *
701
+ * @param {Mixed} object
702
+ * @return {String} object type
703
+ * @api public
704
+ */
705
+ function typeDetect$2(obj) {
706
+ var typeofObj = typeof obj;
707
+ if (typeofObj !== "object") return typeofObj;
708
+ if (obj === null) return "null";
709
+ if (obj === globalObject) return "global";
710
+ if (Array.isArray(obj) && (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))) return "Array";
711
+ if (typeof window === "object" && window !== null) {
712
+ if (typeof window.location === "object" && obj === window.location) return "Location";
713
+ if (typeof window.document === "object" && obj === window.document) return "Document";
714
+ if (typeof window.navigator === "object") {
715
+ if (typeof window.navigator.mimeTypes === "object" && obj === window.navigator.mimeTypes) return "MimeTypeArray";
716
+ if (typeof window.navigator.plugins === "object" && obj === window.navigator.plugins) return "PluginArray";
717
+ }
718
+ if ((typeof window.HTMLElement === "function" || typeof window.HTMLElement === "object") && obj instanceof window.HTMLElement) {
719
+ if (obj.tagName === "BLOCKQUOTE") return "HTMLQuoteElement";
720
+ if (obj.tagName === "TD") return "HTMLTableDataCellElement";
721
+ if (obj.tagName === "TH") return "HTMLTableHeaderCellElement";
722
+ }
723
+ }
724
+ var stringTag = symbolToStringTagExists && obj[Symbol.toStringTag];
725
+ if (typeof stringTag === "string") return stringTag;
726
+ var objPrototype = Object.getPrototypeOf(obj);
727
+ if (objPrototype === RegExp.prototype) return "RegExp";
728
+ if (objPrototype === Date.prototype) return "Date";
729
+ if (promiseExists && objPrototype === Promise.prototype) return "Promise";
730
+ if (setExists && objPrototype === Set.prototype) return "Set";
731
+ if (mapExists && objPrototype === Map.prototype) return "Map";
732
+ if (weakSetExists && objPrototype === WeakSet.prototype) return "WeakSet";
733
+ if (weakMapExists && objPrototype === WeakMap.prototype) return "WeakMap";
734
+ if (dataViewExists && objPrototype === DataView.prototype) return "DataView";
735
+ if (mapExists && objPrototype === mapIteratorPrototype) return "Map Iterator";
736
+ if (setExists && objPrototype === setIteratorPrototype) return "Set Iterator";
737
+ if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) return "Array Iterator";
738
+ if (stringIteratorExists && objPrototype === stringIteratorPrototype) return "String Iterator";
739
+ if (objPrototype === null) return "Object";
740
+ return Object.prototype.toString.call(obj).slice(toStringLeftSliceLength, toStringRightSliceLength);
741
+ }
742
+ return typeDetect$2;
743
+ }));
744
+ })(typeDetect$1);
745
+ return typeDetect$1.exports;
746
+ }
747
+ var typeOf;
748
+ var hasRequiredTypeOf;
749
+ function requireTypeOf() {
750
+ if (hasRequiredTypeOf) return typeOf;
751
+ hasRequiredTypeOf = 1;
752
+ var type = requireTypeDetect();
753
+ /**
754
+ * Returns the lower-case result of running type from type-detect on the value
755
+ * @param {*} value
756
+ * @returns {string}
757
+ */
758
+ typeOf = function typeOf$1(value) {
759
+ return type(value).toLowerCase();
760
+ };
761
+ return typeOf;
762
+ }
763
+ var valueToString_1;
764
+ var hasRequiredValueToString;
765
+ function requireValueToString() {
766
+ if (hasRequiredValueToString) return valueToString_1;
767
+ hasRequiredValueToString = 1;
768
+ /**
769
+ * Returns a string representation of the value
770
+ * @param {*} value
771
+ * @returns {string}
772
+ */
773
+ function valueToString(value) {
774
+ if (value && value.toString) return value.toString();
775
+ return String(value);
776
+ }
777
+ valueToString_1 = valueToString;
778
+ return valueToString_1;
779
+ }
780
+ var lib;
781
+ var hasRequiredLib;
782
+ function requireLib() {
783
+ if (hasRequiredLib) return lib;
784
+ hasRequiredLib = 1;
785
+ lib = {
786
+ global: requireGlobal(),
787
+ calledInOrder: requireCalledInOrder(),
788
+ className: requireClassName(),
789
+ deprecated: requireDeprecated(),
790
+ every: requireEvery(),
791
+ functionName: requireFunctionName(),
792
+ orderByFirstCall: requireOrderByFirstCall(),
793
+ prototypes: requirePrototypes(),
794
+ typeOf: requireTypeOf(),
795
+ valueToString: requireValueToString()
796
+ };
797
+ return lib;
798
+ }
799
+ var hasRequiredFakeTimersSrc;
800
+ function requireFakeTimersSrc() {
801
+ if (hasRequiredFakeTimersSrc) return fakeTimersSrc;
802
+ hasRequiredFakeTimersSrc = 1;
803
+ const globalObject = requireLib().global;
804
+ let timersModule, timersPromisesModule;
805
+ if (typeof __vitest_required__ !== "undefined") {
806
+ try {
807
+ timersModule = __vitest_required__.timers;
808
+ } catch (e) {}
809
+ try {
810
+ timersPromisesModule = __vitest_required__.timersPromises;
811
+ } catch (e) {}
812
+ }
813
+ /**
814
+ * @typedef {object} IdleDeadline
815
+ * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
816
+ * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
817
+ */
818
+ /**
819
+ * Queues a function to be called during a browser's idle periods
820
+ * @callback RequestIdleCallback
821
+ * @param {function(IdleDeadline)} callback
822
+ * @param {{timeout: number}} options - an options object
823
+ * @returns {number} the id
824
+ */
825
+ /**
826
+ * @callback NextTick
827
+ * @param {VoidVarArgsFunc} callback - the callback to run
828
+ * @param {...*} args - optional arguments to call the callback with
829
+ * @returns {void}
830
+ */
831
+ /**
832
+ * @callback SetImmediate
833
+ * @param {VoidVarArgsFunc} callback - the callback to run
834
+ * @param {...*} args - optional arguments to call the callback with
835
+ * @returns {NodeImmediate}
836
+ */
837
+ /**
838
+ * @callback VoidVarArgsFunc
839
+ * @param {...*} callback - the callback to run
840
+ * @returns {void}
841
+ */
842
+ /**
843
+ * @typedef RequestAnimationFrame
844
+ * @property {function(number):void} requestAnimationFrame
845
+ * @returns {number} - the id
846
+ */
847
+ /**
848
+ * @typedef Performance
849
+ * @property {function(): number} now
850
+ */
851
+ /**
852
+ * @typedef {object} Clock
853
+ * @property {number} now - the current time
854
+ * @property {Date} Date - the Date constructor
855
+ * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
856
+ * @property {RequestIdleCallback} requestIdleCallback
857
+ * @property {function(number):void} cancelIdleCallback
858
+ * @property {setTimeout} setTimeout
859
+ * @property {clearTimeout} clearTimeout
860
+ * @property {NextTick} nextTick
861
+ * @property {queueMicrotask} queueMicrotask
862
+ * @property {setInterval} setInterval
863
+ * @property {clearInterval} clearInterval
864
+ * @property {SetImmediate} setImmediate
865
+ * @property {function(NodeImmediate):void} clearImmediate
866
+ * @property {function():number} countTimers
867
+ * @property {RequestAnimationFrame} requestAnimationFrame
868
+ * @property {function(number):void} cancelAnimationFrame
869
+ * @property {function():void} runMicrotasks
870
+ * @property {function(string | number): number} tick
871
+ * @property {function(string | number): Promise<number>} tickAsync
872
+ * @property {function(): number} next
873
+ * @property {function(): Promise<number>} nextAsync
874
+ * @property {function(): number} runAll
875
+ * @property {function(): number} runToFrame
876
+ * @property {function(): Promise<number>} runAllAsync
877
+ * @property {function(): number} runToLast
878
+ * @property {function(): Promise<number>} runToLastAsync
879
+ * @property {function(): void} reset
880
+ * @property {function(number | Date): void} setSystemTime
881
+ * @property {function(number): void} jump
882
+ * @property {Performance} performance
883
+ * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
884
+ * @property {function(): void} uninstall Uninstall the clock.
885
+ * @property {Function[]} methods - the methods that are faked
886
+ * @property {boolean} [shouldClearNativeTimers] inherited from config
887
+ * @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
888
+ * @property {{methodName:string, original:any}[] | undefined} timersPromisesModuleMethods
889
+ * @property {Map<function(): void, AbortSignal>} abortListenerMap
890
+ */
891
+ /**
892
+ * Configuration object for the `install` method.
893
+ * @typedef {object} Config
894
+ * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
895
+ * @property {string[]} [toFake] names of the methods that should be faked.
896
+ * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
897
+ * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
898
+ * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
899
+ * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
900
+ * @property {boolean} [ignoreMissingTimers] default is false, meaning asking to fake timers that are not present will throw an error
901
+ */
902
+ /**
903
+ * The internal structure to describe a scheduled fake timer
904
+ * @typedef {object} Timer
905
+ * @property {Function} func
906
+ * @property {*[]} args
907
+ * @property {number} delay
908
+ * @property {number} callAt
909
+ * @property {number} createdAt
910
+ * @property {boolean} immediate
911
+ * @property {number} id
912
+ * @property {Error} [error]
913
+ */
914
+ /**
915
+ * A Node timer
916
+ * @typedef {object} NodeImmediate
917
+ * @property {function(): boolean} hasRef
918
+ * @property {function(): NodeImmediate} ref
919
+ * @property {function(): NodeImmediate} unref
920
+ */
921
+ /**
922
+ * Mocks available features in the specified global namespace.
923
+ * @param {*} _global Namespace to mock (e.g. `window`)
924
+ * @returns {FakeTimers}
925
+ */
926
+ function withGlobal(_global) {
927
+ const maxTimeout = Math.pow(2, 31) - 1;
928
+ const idCounterStart = 0xe8d4a51000;
929
+ const NOOP = function() {};
930
+ const NOOP_ARRAY = function() {
931
+ return [];
932
+ };
933
+ const isPresent = {};
934
+ let timeoutResult, addTimerReturnsObject = false;
935
+ if (_global.setTimeout) {
936
+ isPresent.setTimeout = true;
937
+ timeoutResult = _global.setTimeout(NOOP, 0);
938
+ addTimerReturnsObject = typeof timeoutResult === "object";
939
+ }
940
+ isPresent.clearTimeout = Boolean(_global.clearTimeout);
941
+ isPresent.setInterval = Boolean(_global.setInterval);
942
+ isPresent.clearInterval = Boolean(_global.clearInterval);
943
+ isPresent.hrtime = _global.process && typeof _global.process.hrtime === "function";
944
+ isPresent.hrtimeBigint = isPresent.hrtime && typeof _global.process.hrtime.bigint === "function";
945
+ isPresent.nextTick = _global.process && typeof _global.process.nextTick === "function";
946
+ const utilPromisify = _global.process && _global.__vitest_required__ && _global.__vitest_required__.util.promisify;
947
+ isPresent.performance = _global.performance && typeof _global.performance.now === "function";
948
+ const hasPerformancePrototype = _global.Performance && (typeof _global.Performance).match(/^(function|object)$/);
949
+ const hasPerformanceConstructorPrototype = _global.performance && _global.performance.constructor && _global.performance.constructor.prototype;
950
+ isPresent.queueMicrotask = _global.hasOwnProperty("queueMicrotask");
951
+ isPresent.requestAnimationFrame = _global.requestAnimationFrame && typeof _global.requestAnimationFrame === "function";
952
+ isPresent.cancelAnimationFrame = _global.cancelAnimationFrame && typeof _global.cancelAnimationFrame === "function";
953
+ isPresent.requestIdleCallback = _global.requestIdleCallback && typeof _global.requestIdleCallback === "function";
954
+ isPresent.cancelIdleCallbackPresent = _global.cancelIdleCallback && typeof _global.cancelIdleCallback === "function";
955
+ isPresent.setImmediate = _global.setImmediate && typeof _global.setImmediate === "function";
956
+ isPresent.clearImmediate = _global.clearImmediate && typeof _global.clearImmediate === "function";
957
+ isPresent.Intl = _global.Intl && typeof _global.Intl === "object";
958
+ if (_global.clearTimeout) _global.clearTimeout(timeoutResult);
959
+ const NativeDate = _global.Date;
960
+ const NativeIntl = isPresent.Intl ? Object.defineProperties(Object.create(null), Object.getOwnPropertyDescriptors(_global.Intl)) : void 0;
961
+ let uniqueTimerId = idCounterStart;
962
+ if (NativeDate === void 0) throw new Error("The global scope doesn't have a `Date` object (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)");
963
+ isPresent.Date = true;
964
+ /**
965
+ * The PerformanceEntry object encapsulates a single performance metric
966
+ * that is part of the browser's performance timeline.
967
+ *
968
+ * This is an object returned by the `mark` and `measure` methods on the Performance prototype
969
+ */
970
+ class FakePerformanceEntry {
971
+ constructor(name, entryType, startTime, duration) {
972
+ this.name = name;
973
+ this.entryType = entryType;
974
+ this.startTime = startTime;
975
+ this.duration = duration;
976
+ }
977
+ toJSON() {
978
+ return JSON.stringify({ ...this });
979
+ }
980
+ }
981
+ /**
982
+ * @param {number} num
983
+ * @returns {boolean}
984
+ */
985
+ function isNumberFinite(num) {
986
+ if (Number.isFinite) return Number.isFinite(num);
987
+ return isFinite(num);
988
+ }
989
+ let isNearInfiniteLimit = false;
990
+ /**
991
+ * @param {Clock} clock
992
+ * @param {number} i
993
+ */
994
+ function checkIsNearInfiniteLimit(clock, i) {
995
+ if (clock.loopLimit && i === clock.loopLimit - 1) isNearInfiniteLimit = true;
996
+ }
997
+ /**
998
+ *
999
+ */
1000
+ function resetIsNearInfiniteLimit() {
1001
+ isNearInfiniteLimit = false;
1002
+ }
1003
+ /**
1004
+ * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
1005
+ * number of milliseconds. This is used to support human-readable strings passed
1006
+ * to clock.tick()
1007
+ * @param {string} str
1008
+ * @returns {number}
1009
+ */
1010
+ function parseTime(str) {
1011
+ if (!str) return 0;
1012
+ const strings = str.split(":");
1013
+ const l = strings.length;
1014
+ let i = l;
1015
+ let ms = 0;
1016
+ let parsed;
1017
+ if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) throw new Error("tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits");
1018
+ while (i--) {
1019
+ parsed = parseInt(strings[i], 10);
1020
+ if (parsed >= 60) throw new Error(`Invalid time ${str}`);
1021
+ ms += parsed * Math.pow(60, l - i - 1);
1022
+ }
1023
+ return ms * 1e3;
1024
+ }
1025
+ /**
1026
+ * Get the decimal part of the millisecond value as nanoseconds
1027
+ * @param {number} msFloat the number of milliseconds
1028
+ * @returns {number} an integer number of nanoseconds in the range [0,1e6)
1029
+ *
1030
+ * Example: nanoRemainer(123.456789) -> 456789
1031
+ */
1032
+ function nanoRemainder(msFloat) {
1033
+ const modulo = 1e6;
1034
+ const remainder = msFloat * 1e6 % modulo;
1035
+ const positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
1036
+ return Math.floor(positiveRemainder);
1037
+ }
1038
+ /**
1039
+ * Used to grok the `now` parameter to createClock.
1040
+ * @param {Date|number} epoch the system time
1041
+ * @returns {number}
1042
+ */
1043
+ function getEpoch(epoch) {
1044
+ if (!epoch) return 0;
1045
+ if (typeof epoch.getTime === "function") return epoch.getTime();
1046
+ if (typeof epoch === "number") return epoch;
1047
+ throw new TypeError("now should be milliseconds since UNIX epoch");
1048
+ }
1049
+ /**
1050
+ * @param {number} from
1051
+ * @param {number} to
1052
+ * @param {Timer} timer
1053
+ * @returns {boolean}
1054
+ */
1055
+ function inRange(from, to, timer) {
1056
+ return timer && timer.callAt >= from && timer.callAt <= to;
1057
+ }
1058
+ /**
1059
+ * @param {Clock} clock
1060
+ * @param {Timer} job
1061
+ */
1062
+ function getInfiniteLoopError(clock, job) {
1063
+ const infiniteLoopError = /* @__PURE__ */ new Error(`Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`);
1064
+ if (!job.error) return infiniteLoopError;
1065
+ const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
1066
+ let clockMethodPattern = new RegExp(String(Object.keys(clock).join("|")));
1067
+ if (addTimerReturnsObject) clockMethodPattern = /* @__PURE__ */ new RegExp(`\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`);
1068
+ let matchedLineIndex = -1;
1069
+ job.error.stack.split("\n").some(function(line, i) {
1070
+ /* istanbul ignore if */
1071
+ if (line.match(computedTargetPattern)) {
1072
+ matchedLineIndex = i;
1073
+ return true;
1074
+ }
1075
+ if (line.match(clockMethodPattern)) {
1076
+ matchedLineIndex = i;
1077
+ return false;
1078
+ }
1079
+ return matchedLineIndex >= 0;
1080
+ });
1081
+ const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${job.func.name || "anonymous"}\n${job.error.stack.split("\n").slice(matchedLineIndex + 1).join("\n")}`;
1082
+ try {
1083
+ Object.defineProperty(infiniteLoopError, "stack", { value: stack });
1084
+ } catch (e) {}
1085
+ return infiniteLoopError;
1086
+ }
1087
+ function createDate() {
1088
+ class ClockDate extends NativeDate {
1089
+ /**
1090
+ * @param {number} year
1091
+ * @param {number} month
1092
+ * @param {number} date
1093
+ * @param {number} hour
1094
+ * @param {number} minute
1095
+ * @param {number} second
1096
+ * @param {number} ms
1097
+ * @returns void
1098
+ */
1099
+ constructor(year, month, date, hour, minute, second, ms) {
1100
+ if (arguments.length === 0) super(ClockDate.clock.now);
1101
+ else super(...arguments);
1102
+ Object.defineProperty(this, "constructor", {
1103
+ value: NativeDate,
1104
+ enumerable: false
1105
+ });
1106
+ }
1107
+ static [Symbol.hasInstance](instance) {
1108
+ return instance instanceof NativeDate;
1109
+ }
1110
+ }
1111
+ ClockDate.isFake = true;
1112
+ if (NativeDate.now) ClockDate.now = function now() {
1113
+ return ClockDate.clock.now;
1114
+ };
1115
+ if (NativeDate.toSource) ClockDate.toSource = function toSource() {
1116
+ return NativeDate.toSource();
1117
+ };
1118
+ ClockDate.toString = function toString() {
1119
+ return NativeDate.toString();
1120
+ };
1121
+ return new Proxy(ClockDate, { apply() {
1122
+ if (this instanceof ClockDate) throw new TypeError("A Proxy should only capture `new` calls with the `construct` handler. This is not supposed to be possible, so check the logic.");
1123
+ return new NativeDate(ClockDate.clock.now).toString();
1124
+ } });
1125
+ }
1126
+ /**
1127
+ * Mirror Intl by default on our fake implementation
1128
+ *
1129
+ * Most of the properties are the original native ones,
1130
+ * but we need to take control of those that have a
1131
+ * dependency on the current clock.
1132
+ * @returns {object} the partly fake Intl implementation
1133
+ */
1134
+ function createIntl() {
1135
+ const ClockIntl = {};
1136
+ Object.getOwnPropertyNames(NativeIntl).forEach((property) => ClockIntl[property] = NativeIntl[property]);
1137
+ ClockIntl.DateTimeFormat = function(...args) {
1138
+ const realFormatter = new NativeIntl.DateTimeFormat(...args);
1139
+ const formatter = {};
1140
+ [
1141
+ "formatRange",
1142
+ "formatRangeToParts",
1143
+ "resolvedOptions"
1144
+ ].forEach((method) => {
1145
+ formatter[method] = realFormatter[method].bind(realFormatter);
1146
+ });
1147
+ ["format", "formatToParts"].forEach((method) => {
1148
+ formatter[method] = function(date) {
1149
+ return realFormatter[method](date || ClockIntl.clock.now);
1150
+ };
1151
+ });
1152
+ return formatter;
1153
+ };
1154
+ ClockIntl.DateTimeFormat.prototype = Object.create(NativeIntl.DateTimeFormat.prototype);
1155
+ ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;
1156
+ return ClockIntl;
1157
+ }
1158
+ function enqueueJob(clock, job) {
1159
+ if (!clock.jobs) clock.jobs = [];
1160
+ clock.jobs.push(job);
1161
+ }
1162
+ function runJobs(clock) {
1163
+ if (!clock.jobs) return;
1164
+ for (let i = 0; i < clock.jobs.length; i++) {
1165
+ const job = clock.jobs[i];
1166
+ job.func.apply(null, job.args);
1167
+ checkIsNearInfiniteLimit(clock, i);
1168
+ if (clock.loopLimit && i > clock.loopLimit) throw getInfiniteLoopError(clock, job);
1169
+ }
1170
+ resetIsNearInfiniteLimit();
1171
+ clock.jobs = [];
1172
+ }
1173
+ /**
1174
+ * @param {Clock} clock
1175
+ * @param {Timer} timer
1176
+ * @returns {number} id of the created timer
1177
+ */
1178
+ function addTimer(clock, timer) {
1179
+ if (timer.func === void 0) throw new Error("Callback must be provided to timer calls");
1180
+ if (addTimerReturnsObject) {
1181
+ if (typeof timer.func !== "function") throw new TypeError(`[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${timer.func} of type ${typeof timer.func}`);
1182
+ }
1183
+ if (isNearInfiniteLimit) timer.error = /* @__PURE__ */ new Error();
1184
+ timer.type = timer.immediate ? "Immediate" : "Timeout";
1185
+ if (timer.hasOwnProperty("delay")) {
1186
+ if (typeof timer.delay !== "number") timer.delay = parseInt(timer.delay, 10);
1187
+ if (!isNumberFinite(timer.delay)) timer.delay = 0;
1188
+ timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
1189
+ timer.delay = Math.max(0, timer.delay);
1190
+ }
1191
+ if (timer.hasOwnProperty("interval")) {
1192
+ timer.type = "Interval";
1193
+ timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
1194
+ }
1195
+ if (timer.hasOwnProperty("animation")) {
1196
+ timer.type = "AnimationFrame";
1197
+ timer.animation = true;
1198
+ }
1199
+ if (timer.hasOwnProperty("idleCallback")) {
1200
+ timer.type = "IdleCallback";
1201
+ timer.idleCallback = true;
1202
+ }
1203
+ if (!clock.timers) clock.timers = {};
1204
+ timer.id = uniqueTimerId++;
1205
+ timer.createdAt = clock.now;
1206
+ timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1207
+ clock.timers[timer.id] = timer;
1208
+ if (addTimerReturnsObject) {
1209
+ const res = {
1210
+ refed: true,
1211
+ ref: function() {
1212
+ this.refed = true;
1213
+ return res;
1214
+ },
1215
+ unref: function() {
1216
+ this.refed = false;
1217
+ return res;
1218
+ },
1219
+ hasRef: function() {
1220
+ return this.refed;
1221
+ },
1222
+ refresh: function() {
1223
+ timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
1224
+ clock.timers[timer.id] = timer;
1225
+ return res;
1226
+ },
1227
+ [Symbol.toPrimitive]: function() {
1228
+ return timer.id;
1229
+ }
1230
+ };
1231
+ return res;
1232
+ }
1233
+ return timer.id;
1234
+ }
1235
+ /**
1236
+ * Timer comparitor
1237
+ * @param {Timer} a
1238
+ * @param {Timer} b
1239
+ * @returns {number}
1240
+ */
1241
+ function compareTimers(a, b) {
1242
+ if (a.callAt < b.callAt) return -1;
1243
+ if (a.callAt > b.callAt) return 1;
1244
+ if (a.immediate && !b.immediate) return -1;
1245
+ if (!a.immediate && b.immediate) return 1;
1246
+ if (a.createdAt < b.createdAt) return -1;
1247
+ if (a.createdAt > b.createdAt) return 1;
1248
+ if (a.id < b.id) return -1;
1249
+ if (a.id > b.id) return 1;
1250
+ }
1251
+ /**
1252
+ * @param {Clock} clock
1253
+ * @param {number} from
1254
+ * @param {number} to
1255
+ * @returns {Timer}
1256
+ */
1257
+ function firstTimerInRange(clock, from, to) {
1258
+ const timers$1 = clock.timers;
1259
+ let timer = null;
1260
+ let id, isInRange;
1261
+ for (id in timers$1) if (timers$1.hasOwnProperty(id)) {
1262
+ isInRange = inRange(from, to, timers$1[id]);
1263
+ if (isInRange && (!timer || compareTimers(timer, timers$1[id]) === 1)) timer = timers$1[id];
1264
+ }
1265
+ return timer;
1266
+ }
1267
+ /**
1268
+ * @param {Clock} clock
1269
+ * @returns {Timer}
1270
+ */
1271
+ function firstTimer(clock) {
1272
+ const timers$1 = clock.timers;
1273
+ let timer = null;
1274
+ let id;
1275
+ for (id in timers$1) if (timers$1.hasOwnProperty(id)) {
1276
+ if (!timer || compareTimers(timer, timers$1[id]) === 1) timer = timers$1[id];
1277
+ }
1278
+ return timer;
1279
+ }
1280
+ /**
1281
+ * @param {Clock} clock
1282
+ * @returns {Timer}
1283
+ */
1284
+ function lastTimer(clock) {
1285
+ const timers$1 = clock.timers;
1286
+ let timer = null;
1287
+ let id;
1288
+ for (id in timers$1) if (timers$1.hasOwnProperty(id)) {
1289
+ if (!timer || compareTimers(timer, timers$1[id]) === -1) timer = timers$1[id];
1290
+ }
1291
+ return timer;
1292
+ }
1293
+ /**
1294
+ * @param {Clock} clock
1295
+ * @param {Timer} timer
1296
+ */
1297
+ function callTimer(clock, timer) {
1298
+ if (typeof timer.interval === "number") clock.timers[timer.id].callAt += timer.interval;
1299
+ else delete clock.timers[timer.id];
1300
+ if (typeof timer.func === "function") timer.func.apply(null, timer.args);
1301
+ else {
1302
+ const eval2 = eval;
1303
+ (function() {
1304
+ eval2(timer.func);
1305
+ })();
1306
+ }
1307
+ }
1308
+ /**
1309
+ * Gets clear handler name for a given timer type
1310
+ * @param {string} ttype
1311
+ */
1312
+ function getClearHandler(ttype) {
1313
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") return `cancel${ttype}`;
1314
+ return `clear${ttype}`;
1315
+ }
1316
+ /**
1317
+ * Gets schedule handler name for a given timer type
1318
+ * @param {string} ttype
1319
+ */
1320
+ function getScheduleHandler(ttype) {
1321
+ if (ttype === "IdleCallback" || ttype === "AnimationFrame") return `request${ttype}`;
1322
+ return `set${ttype}`;
1323
+ }
1324
+ /**
1325
+ * Creates an anonymous function to warn only once
1326
+ */
1327
+ function createWarnOnce() {
1328
+ let calls = 0;
1329
+ return function(msg) {
1330
+ !calls++ && console.warn(msg);
1331
+ };
1332
+ }
1333
+ const warnOnce = createWarnOnce();
1334
+ /**
1335
+ * @param {Clock} clock
1336
+ * @param {number} timerId
1337
+ * @param {string} ttype
1338
+ */
1339
+ function clearTimer(clock, timerId, ttype) {
1340
+ if (!timerId) return;
1341
+ if (!clock.timers) clock.timers = {};
1342
+ const id = Number(timerId);
1343
+ if (Number.isNaN(id) || id < idCounterStart) {
1344
+ const handlerName = getClearHandler(ttype);
1345
+ if (clock.shouldClearNativeTimers === true) {
1346
+ const nativeHandler = clock[`_${handlerName}`];
1347
+ return typeof nativeHandler === "function" ? nativeHandler(timerId) : void 0;
1348
+ }
1349
+ warnOnce(`FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.
1350
+ To automatically clean-up native timers, use \`shouldClearNativeTimers\`.`);
1351
+ }
1352
+ if (clock.timers.hasOwnProperty(id)) {
1353
+ const timer = clock.timers[id];
1354
+ if (timer.type === ttype || timer.type === "Timeout" && ttype === "Interval" || timer.type === "Interval" && ttype === "Timeout") delete clock.timers[id];
1355
+ else {
1356
+ const clear = getClearHandler(ttype);
1357
+ const schedule = getScheduleHandler(timer.type);
1358
+ throw new Error(`Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`);
1359
+ }
1360
+ }
1361
+ }
1362
+ /**
1363
+ * @param {Clock} clock
1364
+ * @param {Config} config
1365
+ * @returns {Timer[]}
1366
+ */
1367
+ function uninstall(clock, config) {
1368
+ let method, i, l;
1369
+ const installedHrTime = "_hrtime";
1370
+ const installedNextTick = "_nextTick";
1371
+ for (i = 0, l = clock.methods.length; i < l; i++) {
1372
+ method = clock.methods[i];
1373
+ if (method === "hrtime" && _global.process) _global.process.hrtime = clock[installedHrTime];
1374
+ else if (method === "nextTick" && _global.process) _global.process.nextTick = clock[installedNextTick];
1375
+ else if (method === "performance") {
1376
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(clock, `_${method}`);
1377
+ if (originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set) Object.defineProperty(_global, method, originalPerfDescriptor);
1378
+ else if (originalPerfDescriptor.configurable) _global[method] = clock[`_${method}`];
1379
+ } else if (_global[method] && _global[method].hadOwnProperty) _global[method] = clock[`_${method}`];
1380
+ else try {
1381
+ delete _global[method];
1382
+ } catch (ignore) {}
1383
+ if (clock.timersModuleMethods !== void 0) for (let j = 0; j < clock.timersModuleMethods.length; j++) {
1384
+ const entry = clock.timersModuleMethods[j];
1385
+ timersModule[entry.methodName] = entry.original;
1386
+ }
1387
+ if (clock.timersPromisesModuleMethods !== void 0) for (let j = 0; j < clock.timersPromisesModuleMethods.length; j++) {
1388
+ const entry = clock.timersPromisesModuleMethods[j];
1389
+ timersPromisesModule[entry.methodName] = entry.original;
1390
+ }
1391
+ }
1392
+ if (config.shouldAdvanceTime === true) _global.clearInterval(clock.attachedInterval);
1393
+ clock.methods = [];
1394
+ for (const [listener, signal] of clock.abortListenerMap.entries()) {
1395
+ signal.removeEventListener("abort", listener);
1396
+ clock.abortListenerMap.delete(listener);
1397
+ }
1398
+ if (!clock.timers) return [];
1399
+ return Object.keys(clock.timers).map(function mapper(key) {
1400
+ return clock.timers[key];
1401
+ });
1402
+ }
1403
+ /**
1404
+ * @param {object} target the target containing the method to replace
1405
+ * @param {string} method the keyname of the method on the target
1406
+ * @param {Clock} clock
1407
+ */
1408
+ function hijackMethod(target, method, clock) {
1409
+ clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method);
1410
+ clock[`_${method}`] = target[method];
1411
+ if (method === "Date") target[method] = clock[method];
1412
+ else if (method === "Intl") target[method] = clock[method];
1413
+ else if (method === "performance") {
1414
+ const originalPerfDescriptor = Object.getOwnPropertyDescriptor(target, method);
1415
+ if (originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set) {
1416
+ Object.defineProperty(clock, `_${method}`, originalPerfDescriptor);
1417
+ const perfDescriptor = Object.getOwnPropertyDescriptor(clock, method);
1418
+ Object.defineProperty(target, method, perfDescriptor);
1419
+ } else target[method] = clock[method];
1420
+ } else {
1421
+ target[method] = function() {
1422
+ return clock[method].apply(clock, arguments);
1423
+ };
1424
+ Object.defineProperties(target[method], Object.getOwnPropertyDescriptors(clock[method]));
1425
+ }
1426
+ target[method].clock = clock;
1427
+ }
1428
+ /**
1429
+ * @param {Clock} clock
1430
+ * @param {number} advanceTimeDelta
1431
+ */
1432
+ function doIntervalTick(clock, advanceTimeDelta) {
1433
+ clock.tick(advanceTimeDelta);
1434
+ }
1435
+ /**
1436
+ * @typedef {object} Timers
1437
+ * @property {setTimeout} setTimeout
1438
+ * @property {clearTimeout} clearTimeout
1439
+ * @property {setInterval} setInterval
1440
+ * @property {clearInterval} clearInterval
1441
+ * @property {Date} Date
1442
+ * @property {Intl} Intl
1443
+ * @property {SetImmediate=} setImmediate
1444
+ * @property {function(NodeImmediate): void=} clearImmediate
1445
+ * @property {function(number[]):number[]=} hrtime
1446
+ * @property {NextTick=} nextTick
1447
+ * @property {Performance=} performance
1448
+ * @property {RequestAnimationFrame=} requestAnimationFrame
1449
+ * @property {boolean=} queueMicrotask
1450
+ * @property {function(number): void=} cancelAnimationFrame
1451
+ * @property {RequestIdleCallback=} requestIdleCallback
1452
+ * @property {function(number): void=} cancelIdleCallback
1453
+ */
1454
+ /** @type {Timers} */
1455
+ const timers = {
1456
+ setTimeout: _global.setTimeout,
1457
+ clearTimeout: _global.clearTimeout,
1458
+ setInterval: _global.setInterval,
1459
+ clearInterval: _global.clearInterval,
1460
+ Date: _global.Date
1461
+ };
1462
+ if (isPresent.setImmediate) timers.setImmediate = _global.setImmediate;
1463
+ if (isPresent.clearImmediate) timers.clearImmediate = _global.clearImmediate;
1464
+ if (isPresent.hrtime) timers.hrtime = _global.process.hrtime;
1465
+ if (isPresent.nextTick) timers.nextTick = _global.process.nextTick;
1466
+ if (isPresent.performance) timers.performance = _global.performance;
1467
+ if (isPresent.requestAnimationFrame) timers.requestAnimationFrame = _global.requestAnimationFrame;
1468
+ if (isPresent.queueMicrotask) timers.queueMicrotask = _global.queueMicrotask;
1469
+ if (isPresent.cancelAnimationFrame) timers.cancelAnimationFrame = _global.cancelAnimationFrame;
1470
+ if (isPresent.requestIdleCallback) timers.requestIdleCallback = _global.requestIdleCallback;
1471
+ if (isPresent.cancelIdleCallback) timers.cancelIdleCallback = _global.cancelIdleCallback;
1472
+ if (isPresent.Intl) timers.Intl = NativeIntl;
1473
+ const originalSetTimeout = _global.setImmediate || _global.setTimeout;
1474
+ /**
1475
+ * @param {Date|number} [start] the system time - non-integer values are floored
1476
+ * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
1477
+ * @returns {Clock}
1478
+ */
1479
+ function createClock(start, loopLimit) {
1480
+ start = Math.floor(getEpoch(start));
1481
+ loopLimit = loopLimit || 1e3;
1482
+ let nanos = 0;
1483
+ const adjustedSystemTime = [0, 0];
1484
+ const clock = {
1485
+ now: start,
1486
+ Date: createDate(),
1487
+ loopLimit
1488
+ };
1489
+ clock.Date.clock = clock;
1490
+ function getTimeToNextFrame() {
1491
+ return 16 - (clock.now - start) % 16;
1492
+ }
1493
+ function hrtime(prev) {
1494
+ const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
1495
+ const secsSinceStart = Math.floor(millisSinceStart / 1e3);
1496
+ const remainderInNanos = (millisSinceStart - secsSinceStart * 1e3) * 1e6 + nanos - adjustedSystemTime[1];
1497
+ if (Array.isArray(prev)) {
1498
+ if (prev[1] > 1e9) throw new TypeError("Number of nanoseconds can't exceed a billion");
1499
+ const oldSecs = prev[0];
1500
+ let nanoDiff = remainderInNanos - prev[1];
1501
+ let secDiff = secsSinceStart - oldSecs;
1502
+ if (nanoDiff < 0) {
1503
+ nanoDiff += 1e9;
1504
+ secDiff -= 1;
1505
+ }
1506
+ return [secDiff, nanoDiff];
1507
+ }
1508
+ return [secsSinceStart, remainderInNanos];
1509
+ }
1510
+ /**
1511
+ * A high resolution timestamp in milliseconds.
1512
+ * @typedef {number} DOMHighResTimeStamp
1513
+ */
1514
+ /**
1515
+ * performance.now()
1516
+ * @returns {DOMHighResTimeStamp}
1517
+ */
1518
+ function fakePerformanceNow() {
1519
+ const hrt = hrtime();
1520
+ return hrt[0] * 1e3 + hrt[1] / 1e6;
1521
+ }
1522
+ if (isPresent.hrtimeBigint) hrtime.bigint = function() {
1523
+ const parts = hrtime();
1524
+ return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]);
1525
+ };
1526
+ if (isPresent.Intl) {
1527
+ clock.Intl = createIntl();
1528
+ clock.Intl.clock = clock;
1529
+ }
1530
+ clock.requestIdleCallback = function requestIdleCallback(func, timeout) {
1531
+ let timeToNextIdlePeriod = 0;
1532
+ if (clock.countTimers() > 0) timeToNextIdlePeriod = 50;
1533
+ const result = addTimer(clock, {
1534
+ func,
1535
+ args: Array.prototype.slice.call(arguments, 2),
1536
+ delay: typeof timeout === "undefined" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod),
1537
+ idleCallback: true
1538
+ });
1539
+ return Number(result);
1540
+ };
1541
+ clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
1542
+ return clearTimer(clock, timerId, "IdleCallback");
1543
+ };
1544
+ clock.setTimeout = function setTimeout(func, timeout) {
1545
+ return addTimer(clock, {
1546
+ func,
1547
+ args: Array.prototype.slice.call(arguments, 2),
1548
+ delay: timeout
1549
+ });
1550
+ };
1551
+ if (typeof _global.Promise !== "undefined" && utilPromisify) clock.setTimeout[utilPromisify.custom] = function promisifiedSetTimeout(timeout, arg) {
1552
+ return new _global.Promise(function setTimeoutExecutor(resolve) {
1553
+ addTimer(clock, {
1554
+ func: resolve,
1555
+ args: [arg],
1556
+ delay: timeout
1557
+ });
1558
+ });
1559
+ };
1560
+ clock.clearTimeout = function clearTimeout(timerId) {
1561
+ return clearTimer(clock, timerId, "Timeout");
1562
+ };
1563
+ clock.nextTick = function nextTick(func) {
1564
+ return enqueueJob(clock, {
1565
+ func,
1566
+ args: Array.prototype.slice.call(arguments, 1),
1567
+ error: isNearInfiniteLimit ? /* @__PURE__ */ new Error() : null
1568
+ });
1569
+ };
1570
+ clock.queueMicrotask = function queueMicrotask(func) {
1571
+ return clock.nextTick(func);
1572
+ };
1573
+ clock.setInterval = function setInterval(func, timeout) {
1574
+ timeout = parseInt(timeout, 10);
1575
+ return addTimer(clock, {
1576
+ func,
1577
+ args: Array.prototype.slice.call(arguments, 2),
1578
+ delay: timeout,
1579
+ interval: timeout
1580
+ });
1581
+ };
1582
+ clock.clearInterval = function clearInterval(timerId) {
1583
+ return clearTimer(clock, timerId, "Interval");
1584
+ };
1585
+ if (isPresent.setImmediate) {
1586
+ clock.setImmediate = function setImmediate(func) {
1587
+ return addTimer(clock, {
1588
+ func,
1589
+ args: Array.prototype.slice.call(arguments, 1),
1590
+ immediate: true
1591
+ });
1592
+ };
1593
+ if (typeof _global.Promise !== "undefined" && utilPromisify) clock.setImmediate[utilPromisify.custom] = function promisifiedSetImmediate(arg) {
1594
+ return new _global.Promise(function setImmediateExecutor(resolve) {
1595
+ addTimer(clock, {
1596
+ func: resolve,
1597
+ args: [arg],
1598
+ immediate: true
1599
+ });
1600
+ });
1601
+ };
1602
+ clock.clearImmediate = function clearImmediate(timerId) {
1603
+ return clearTimer(clock, timerId, "Immediate");
1604
+ };
1605
+ }
1606
+ clock.countTimers = function countTimers() {
1607
+ return Object.keys(clock.timers || {}).length + (clock.jobs || []).length;
1608
+ };
1609
+ clock.requestAnimationFrame = function requestAnimationFrame(func) {
1610
+ const result = addTimer(clock, {
1611
+ func,
1612
+ delay: getTimeToNextFrame(),
1613
+ get args() {
1614
+ return [fakePerformanceNow()];
1615
+ },
1616
+ animation: true
1617
+ });
1618
+ return Number(result);
1619
+ };
1620
+ clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
1621
+ return clearTimer(clock, timerId, "AnimationFrame");
1622
+ };
1623
+ clock.runMicrotasks = function runMicrotasks() {
1624
+ runJobs(clock);
1625
+ };
1626
+ /**
1627
+ * @param {number|string} tickValue milliseconds or a string parseable by parseTime
1628
+ * @param {boolean} isAsync
1629
+ * @param {Function} resolve
1630
+ * @param {Function} reject
1631
+ * @returns {number|undefined} will return the new `now` value or nothing for async
1632
+ */
1633
+ function doTick(tickValue, isAsync, resolve, reject) {
1634
+ const msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
1635
+ const ms = Math.floor(msFloat);
1636
+ const remainder = nanoRemainder(msFloat);
1637
+ let nanosTotal = nanos + remainder;
1638
+ let tickTo = clock.now + ms;
1639
+ if (msFloat < 0) throw new TypeError("Negative ticks are not supported");
1640
+ if (nanosTotal >= 1e6) {
1641
+ tickTo += 1;
1642
+ nanosTotal -= 1e6;
1643
+ }
1644
+ nanos = nanosTotal;
1645
+ let tickFrom = clock.now;
1646
+ let previous = clock.now;
1647
+ let timer, firstException, oldNow, nextPromiseTick, compensationCheck, postTimerCall;
1648
+ clock.duringTick = true;
1649
+ oldNow = clock.now;
1650
+ runJobs(clock);
1651
+ if (oldNow !== clock.now) {
1652
+ tickFrom += clock.now - oldNow;
1653
+ tickTo += clock.now - oldNow;
1654
+ }
1655
+ function doTickInner() {
1656
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
1657
+ while (timer && tickFrom <= tickTo) {
1658
+ if (clock.timers[timer.id]) {
1659
+ tickFrom = timer.callAt;
1660
+ clock.now = timer.callAt;
1661
+ oldNow = clock.now;
1662
+ try {
1663
+ runJobs(clock);
1664
+ callTimer(clock, timer);
1665
+ } catch (e) {
1666
+ firstException = firstException || e;
1667
+ }
1668
+ if (isAsync) {
1669
+ originalSetTimeout(nextPromiseTick);
1670
+ return;
1671
+ }
1672
+ compensationCheck();
1673
+ }
1674
+ postTimerCall();
1675
+ }
1676
+ oldNow = clock.now;
1677
+ runJobs(clock);
1678
+ if (oldNow !== clock.now) {
1679
+ tickFrom += clock.now - oldNow;
1680
+ tickTo += clock.now - oldNow;
1681
+ }
1682
+ clock.duringTick = false;
1683
+ timer = firstTimerInRange(clock, tickFrom, tickTo);
1684
+ if (timer) try {
1685
+ clock.tick(tickTo - clock.now);
1686
+ } catch (e) {
1687
+ firstException = firstException || e;
1688
+ }
1689
+ else {
1690
+ clock.now = tickTo;
1691
+ nanos = nanosTotal;
1692
+ }
1693
+ if (firstException) throw firstException;
1694
+ if (isAsync) resolve(clock.now);
1695
+ else return clock.now;
1696
+ }
1697
+ nextPromiseTick = isAsync && function() {
1698
+ try {
1699
+ compensationCheck();
1700
+ postTimerCall();
1701
+ doTickInner();
1702
+ } catch (e) {
1703
+ reject(e);
1704
+ }
1705
+ };
1706
+ compensationCheck = function() {
1707
+ if (oldNow !== clock.now) {
1708
+ tickFrom += clock.now - oldNow;
1709
+ tickTo += clock.now - oldNow;
1710
+ previous += clock.now - oldNow;
1711
+ }
1712
+ };
1713
+ postTimerCall = function() {
1714
+ timer = firstTimerInRange(clock, previous, tickTo);
1715
+ previous = tickFrom;
1716
+ };
1717
+ return doTickInner();
1718
+ }
1719
+ /**
1720
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1721
+ * @returns {number} will return the new `now` value
1722
+ */
1723
+ clock.tick = function tick(tickValue) {
1724
+ return doTick(tickValue, false);
1725
+ };
1726
+ if (typeof _global.Promise !== "undefined")
1727
+ /**
1728
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1729
+ * @returns {Promise}
1730
+ */
1731
+ clock.tickAsync = function tickAsync(tickValue) {
1732
+ return new _global.Promise(function(resolve, reject) {
1733
+ originalSetTimeout(function() {
1734
+ try {
1735
+ doTick(tickValue, true, resolve, reject);
1736
+ } catch (e) {
1737
+ reject(e);
1738
+ }
1739
+ });
1740
+ });
1741
+ };
1742
+ clock.next = function next() {
1743
+ runJobs(clock);
1744
+ const timer = firstTimer(clock);
1745
+ if (!timer) return clock.now;
1746
+ clock.duringTick = true;
1747
+ try {
1748
+ clock.now = timer.callAt;
1749
+ callTimer(clock, timer);
1750
+ runJobs(clock);
1751
+ return clock.now;
1752
+ } finally {
1753
+ clock.duringTick = false;
1754
+ }
1755
+ };
1756
+ if (typeof _global.Promise !== "undefined") clock.nextAsync = function nextAsync() {
1757
+ return new _global.Promise(function(resolve, reject) {
1758
+ originalSetTimeout(function() {
1759
+ try {
1760
+ const timer = firstTimer(clock);
1761
+ if (!timer) {
1762
+ resolve(clock.now);
1763
+ return;
1764
+ }
1765
+ let err;
1766
+ clock.duringTick = true;
1767
+ clock.now = timer.callAt;
1768
+ try {
1769
+ callTimer(clock, timer);
1770
+ } catch (e) {
1771
+ err = e;
1772
+ }
1773
+ clock.duringTick = false;
1774
+ originalSetTimeout(function() {
1775
+ if (err) reject(err);
1776
+ else resolve(clock.now);
1777
+ });
1778
+ } catch (e) {
1779
+ reject(e);
1780
+ }
1781
+ });
1782
+ });
1783
+ };
1784
+ clock.runAll = function runAll() {
1785
+ let numTimers, i;
1786
+ runJobs(clock);
1787
+ for (i = 0; i < clock.loopLimit; i++) {
1788
+ if (!clock.timers) {
1789
+ resetIsNearInfiniteLimit();
1790
+ return clock.now;
1791
+ }
1792
+ numTimers = Object.keys(clock.timers).length;
1793
+ if (numTimers === 0) {
1794
+ resetIsNearInfiniteLimit();
1795
+ return clock.now;
1796
+ }
1797
+ clock.next();
1798
+ checkIsNearInfiniteLimit(clock, i);
1799
+ }
1800
+ throw getInfiniteLoopError(clock, firstTimer(clock));
1801
+ };
1802
+ clock.runToFrame = function runToFrame() {
1803
+ return clock.tick(getTimeToNextFrame());
1804
+ };
1805
+ if (typeof _global.Promise !== "undefined") clock.runAllAsync = function runAllAsync() {
1806
+ return new _global.Promise(function(resolve, reject) {
1807
+ let i = 0;
1808
+ /**
1809
+ *
1810
+ */
1811
+ function doRun() {
1812
+ originalSetTimeout(function() {
1813
+ try {
1814
+ runJobs(clock);
1815
+ let numTimers;
1816
+ if (i < clock.loopLimit) {
1817
+ if (!clock.timers) {
1818
+ resetIsNearInfiniteLimit();
1819
+ resolve(clock.now);
1820
+ return;
1821
+ }
1822
+ numTimers = Object.keys(clock.timers).length;
1823
+ if (numTimers === 0) {
1824
+ resetIsNearInfiniteLimit();
1825
+ resolve(clock.now);
1826
+ return;
1827
+ }
1828
+ clock.next();
1829
+ i++;
1830
+ doRun();
1831
+ checkIsNearInfiniteLimit(clock, i);
1832
+ return;
1833
+ }
1834
+ reject(getInfiniteLoopError(clock, firstTimer(clock)));
1835
+ } catch (e) {
1836
+ reject(e);
1837
+ }
1838
+ });
1839
+ }
1840
+ doRun();
1841
+ });
1842
+ };
1843
+ clock.runToLast = function runToLast() {
1844
+ const timer = lastTimer(clock);
1845
+ if (!timer) {
1846
+ runJobs(clock);
1847
+ return clock.now;
1848
+ }
1849
+ return clock.tick(timer.callAt - clock.now);
1850
+ };
1851
+ if (typeof _global.Promise !== "undefined") clock.runToLastAsync = function runToLastAsync() {
1852
+ return new _global.Promise(function(resolve, reject) {
1853
+ originalSetTimeout(function() {
1854
+ try {
1855
+ const timer = lastTimer(clock);
1856
+ if (!timer) {
1857
+ runJobs(clock);
1858
+ resolve(clock.now);
1859
+ }
1860
+ resolve(clock.tickAsync(timer.callAt - clock.now));
1861
+ } catch (e) {
1862
+ reject(e);
1863
+ }
1864
+ });
1865
+ });
1866
+ };
1867
+ clock.reset = function reset() {
1868
+ nanos = 0;
1869
+ clock.timers = {};
1870
+ clock.jobs = [];
1871
+ clock.now = start;
1872
+ };
1873
+ clock.setSystemTime = function setSystemTime(systemTime) {
1874
+ const newNow = getEpoch(systemTime);
1875
+ const difference = newNow - clock.now;
1876
+ let id, timer;
1877
+ adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
1878
+ adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
1879
+ clock.now = newNow;
1880
+ nanos = 0;
1881
+ for (id in clock.timers) if (clock.timers.hasOwnProperty(id)) {
1882
+ timer = clock.timers[id];
1883
+ timer.createdAt += difference;
1884
+ timer.callAt += difference;
1885
+ }
1886
+ };
1887
+ /**
1888
+ * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
1889
+ * @returns {number} will return the new `now` value
1890
+ */
1891
+ clock.jump = function jump(tickValue) {
1892
+ const msFloat = typeof tickValue === "number" ? tickValue : parseTime(tickValue);
1893
+ const ms = Math.floor(msFloat);
1894
+ for (const timer of Object.values(clock.timers)) if (clock.now + ms > timer.callAt) timer.callAt = clock.now + ms;
1895
+ clock.tick(ms);
1896
+ };
1897
+ if (isPresent.performance) {
1898
+ clock.performance = Object.create(null);
1899
+ clock.performance.now = fakePerformanceNow;
1900
+ }
1901
+ if (isPresent.hrtime) clock.hrtime = hrtime;
1902
+ return clock;
1903
+ }
1904
+ /**
1905
+ * @param {Config=} [config] Optional config
1906
+ * @returns {Clock}
1907
+ */
1908
+ function install(config) {
1909
+ if (arguments.length > 1 || config instanceof Date || Array.isArray(config) || typeof config === "number") throw new TypeError(`FakeTimers.install called with ${String(config)} install requires an object parameter`);
1910
+ if (_global.Date.isFake === true) throw new TypeError("Can't install fake timers twice on the same global object.");
1911
+ config = typeof config !== "undefined" ? config : {};
1912
+ config.shouldAdvanceTime = config.shouldAdvanceTime || false;
1913
+ config.advanceTimeDelta = config.advanceTimeDelta || 20;
1914
+ config.shouldClearNativeTimers = config.shouldClearNativeTimers || false;
1915
+ if (config.target) throw new TypeError("config.target is no longer supported. Use `withGlobal(target)` instead.");
1916
+ /**
1917
+ * @param {string} timer/object the name of the thing that is not present
1918
+ * @param timer
1919
+ */
1920
+ function handleMissingTimer(timer) {
1921
+ if (config.ignoreMissingTimers) return;
1922
+ throw new ReferenceError(`non-existent timers and/or objects cannot be faked: '${timer}'`);
1923
+ }
1924
+ let i, l;
1925
+ const clock = createClock(config.now, config.loopLimit);
1926
+ clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
1927
+ clock.uninstall = function() {
1928
+ return uninstall(clock, config);
1929
+ };
1930
+ clock.abortListenerMap = /* @__PURE__ */ new Map();
1931
+ clock.methods = config.toFake || [];
1932
+ if (clock.methods.length === 0) clock.methods = Object.keys(timers);
1933
+ if (config.shouldAdvanceTime === true) {
1934
+ const intervalTick = doIntervalTick.bind(null, clock, config.advanceTimeDelta);
1935
+ clock.attachedInterval = _global.setInterval(intervalTick, config.advanceTimeDelta);
1936
+ }
1937
+ if (clock.methods.includes("performance")) {
1938
+ const proto = (() => {
1939
+ if (hasPerformanceConstructorPrototype) return _global.performance.constructor.prototype;
1940
+ if (hasPerformancePrototype) return _global.Performance.prototype;
1941
+ })();
1942
+ if (proto) {
1943
+ Object.getOwnPropertyNames(proto).forEach(function(name) {
1944
+ if (name !== "now") clock.performance[name] = name.indexOf("getEntries") === 0 ? NOOP_ARRAY : NOOP;
1945
+ });
1946
+ clock.performance.mark = (name) => new FakePerformanceEntry(name, "mark", 0, 0);
1947
+ clock.performance.measure = (name) => new FakePerformanceEntry(name, "measure", 0, 100);
1948
+ clock.performance.timeOrigin = getEpoch(config.now);
1949
+ } else if ((config.toFake || []).includes("performance")) return handleMissingTimer("performance");
1950
+ }
1951
+ if (_global === globalObject && timersModule) clock.timersModuleMethods = [];
1952
+ if (_global === globalObject && timersPromisesModule) clock.timersPromisesModuleMethods = [];
1953
+ for (i = 0, l = clock.methods.length; i < l; i++) {
1954
+ const nameOfMethodToReplace = clock.methods[i];
1955
+ if (!isPresent[nameOfMethodToReplace]) {
1956
+ handleMissingTimer(nameOfMethodToReplace);
1957
+ continue;
1958
+ }
1959
+ if (nameOfMethodToReplace === "hrtime") {
1960
+ if (_global.process && typeof _global.process.hrtime === "function") hijackMethod(_global.process, nameOfMethodToReplace, clock);
1961
+ } else if (nameOfMethodToReplace === "nextTick") {
1962
+ if (_global.process && typeof _global.process.nextTick === "function") hijackMethod(_global.process, nameOfMethodToReplace, clock);
1963
+ } else hijackMethod(_global, nameOfMethodToReplace, clock);
1964
+ if (clock.timersModuleMethods !== void 0 && timersModule[nameOfMethodToReplace]) {
1965
+ const original = timersModule[nameOfMethodToReplace];
1966
+ clock.timersModuleMethods.push({
1967
+ methodName: nameOfMethodToReplace,
1968
+ original
1969
+ });
1970
+ timersModule[nameOfMethodToReplace] = _global[nameOfMethodToReplace];
1971
+ }
1972
+ if (clock.timersPromisesModuleMethods !== void 0) {
1973
+ if (nameOfMethodToReplace === "setTimeout") {
1974
+ clock.timersPromisesModuleMethods.push({
1975
+ methodName: "setTimeout",
1976
+ original: timersPromisesModule.setTimeout
1977
+ });
1978
+ timersPromisesModule.setTimeout = (delay$1, value, options = {}) => new Promise((resolve, reject) => {
1979
+ const abort = () => {
1980
+ options.signal.removeEventListener("abort", abort);
1981
+ clock.abortListenerMap.delete(abort);
1982
+ clock.clearTimeout(handle);
1983
+ reject(options.signal.reason);
1984
+ };
1985
+ const handle = clock.setTimeout(() => {
1986
+ if (options.signal) {
1987
+ options.signal.removeEventListener("abort", abort);
1988
+ clock.abortListenerMap.delete(abort);
1989
+ }
1990
+ resolve(value);
1991
+ }, delay$1);
1992
+ if (options.signal) if (options.signal.aborted) abort();
1993
+ else {
1994
+ options.signal.addEventListener("abort", abort);
1995
+ clock.abortListenerMap.set(abort, options.signal);
1996
+ }
1997
+ });
1998
+ } else if (nameOfMethodToReplace === "setImmediate") {
1999
+ clock.timersPromisesModuleMethods.push({
2000
+ methodName: "setImmediate",
2001
+ original: timersPromisesModule.setImmediate
2002
+ });
2003
+ timersPromisesModule.setImmediate = (value, options = {}) => new Promise((resolve, reject) => {
2004
+ const abort = () => {
2005
+ options.signal.removeEventListener("abort", abort);
2006
+ clock.abortListenerMap.delete(abort);
2007
+ clock.clearImmediate(handle);
2008
+ reject(options.signal.reason);
2009
+ };
2010
+ const handle = clock.setImmediate(() => {
2011
+ if (options.signal) {
2012
+ options.signal.removeEventListener("abort", abort);
2013
+ clock.abortListenerMap.delete(abort);
2014
+ }
2015
+ resolve(value);
2016
+ });
2017
+ if (options.signal) if (options.signal.aborted) abort();
2018
+ else {
2019
+ options.signal.addEventListener("abort", abort);
2020
+ clock.abortListenerMap.set(abort, options.signal);
2021
+ }
2022
+ });
2023
+ } else if (nameOfMethodToReplace === "setInterval") {
2024
+ clock.timersPromisesModuleMethods.push({
2025
+ methodName: "setInterval",
2026
+ original: timersPromisesModule.setInterval
2027
+ });
2028
+ timersPromisesModule.setInterval = (delay$1, value, options = {}) => ({ [Symbol.asyncIterator]: () => {
2029
+ const createResolvable = () => {
2030
+ let resolve, reject;
2031
+ const promise = new Promise((res, rej) => {
2032
+ resolve = res;
2033
+ reject = rej;
2034
+ });
2035
+ promise.resolve = resolve;
2036
+ promise.reject = reject;
2037
+ return promise;
2038
+ };
2039
+ let done = false;
2040
+ let hasThrown = false;
2041
+ let returnCall;
2042
+ let nextAvailable = 0;
2043
+ const nextQueue = [];
2044
+ const handle = clock.setInterval(() => {
2045
+ if (nextQueue.length > 0) nextQueue.shift().resolve();
2046
+ else nextAvailable++;
2047
+ }, delay$1);
2048
+ const abort = () => {
2049
+ options.signal.removeEventListener("abort", abort);
2050
+ clock.abortListenerMap.delete(abort);
2051
+ clock.clearInterval(handle);
2052
+ done = true;
2053
+ for (const resolvable of nextQueue) resolvable.resolve();
2054
+ };
2055
+ if (options.signal) if (options.signal.aborted) done = true;
2056
+ else {
2057
+ options.signal.addEventListener("abort", abort);
2058
+ clock.abortListenerMap.set(abort, options.signal);
2059
+ }
2060
+ return {
2061
+ next: async () => {
2062
+ if (options.signal?.aborted && !hasThrown) {
2063
+ hasThrown = true;
2064
+ throw options.signal.reason;
2065
+ }
2066
+ if (done) return {
2067
+ done: true,
2068
+ value: void 0
2069
+ };
2070
+ if (nextAvailable > 0) {
2071
+ nextAvailable--;
2072
+ return {
2073
+ done: false,
2074
+ value
2075
+ };
2076
+ }
2077
+ const resolvable = createResolvable();
2078
+ nextQueue.push(resolvable);
2079
+ await resolvable;
2080
+ if (returnCall && nextQueue.length === 0) returnCall.resolve();
2081
+ if (options.signal?.aborted && !hasThrown) {
2082
+ hasThrown = true;
2083
+ throw options.signal.reason;
2084
+ }
2085
+ if (done) return {
2086
+ done: true,
2087
+ value: void 0
2088
+ };
2089
+ return {
2090
+ done: false,
2091
+ value
2092
+ };
2093
+ },
2094
+ return: async () => {
2095
+ if (done) return {
2096
+ done: true,
2097
+ value: void 0
2098
+ };
2099
+ if (nextQueue.length > 0) {
2100
+ returnCall = createResolvable();
2101
+ await returnCall;
2102
+ }
2103
+ clock.clearInterval(handle);
2104
+ done = true;
2105
+ if (options.signal) {
2106
+ options.signal.removeEventListener("abort", abort);
2107
+ clock.abortListenerMap.delete(abort);
2108
+ }
2109
+ return {
2110
+ done: true,
2111
+ value: void 0
2112
+ };
2113
+ }
2114
+ };
2115
+ } });
2116
+ }
2117
+ }
2118
+ }
2119
+ return clock;
2120
+ }
2121
+ return {
2122
+ timers,
2123
+ createClock,
2124
+ install,
2125
+ withGlobal
2126
+ };
2127
+ }
2128
+ /**
2129
+ * @typedef {object} FakeTimers
2130
+ * @property {Timers} timers
2131
+ * @property {createClock} createClock
2132
+ * @property {Function} install
2133
+ * @property {withGlobal} withGlobal
2134
+ */
2135
+ /** @type {FakeTimers} */
2136
+ const defaultImplementation = withGlobal(globalObject);
2137
+ fakeTimersSrc.timers = defaultImplementation.timers;
2138
+ fakeTimersSrc.createClock = defaultImplementation.createClock;
2139
+ fakeTimersSrc.install = defaultImplementation.install;
2140
+ fakeTimersSrc.withGlobal = withGlobal;
2141
+ return fakeTimersSrc;
2142
+ }
2143
+ var fakeTimersSrcExports = requireFakeTimersSrc();
2144
+ var FakeTimers = class {
2145
+ _global;
2146
+ _clock;
2147
+ _fakingTime;
2148
+ _fakingDate;
2149
+ _fakeTimers;
2150
+ _userConfig;
2151
+ _now = RealDate.now;
2152
+ constructor({ global: global$1, config }) {
2153
+ this._userConfig = config;
2154
+ this._fakingDate = null;
2155
+ this._fakingTime = false;
2156
+ this._fakeTimers = fakeTimersSrcExports.withGlobal(global$1);
2157
+ this._global = global$1;
2158
+ }
2159
+ clearAllTimers() {
2160
+ if (this._fakingTime) this._clock.reset();
2161
+ }
2162
+ dispose() {
2163
+ this.useRealTimers();
2164
+ }
2165
+ runAllTimers() {
2166
+ if (this._checkFakeTimers()) this._clock.runAll();
2167
+ }
2168
+ async runAllTimersAsync() {
2169
+ if (this._checkFakeTimers()) await this._clock.runAllAsync();
2170
+ }
2171
+ runOnlyPendingTimers() {
2172
+ if (this._checkFakeTimers()) this._clock.runToLast();
2173
+ }
2174
+ async runOnlyPendingTimersAsync() {
2175
+ if (this._checkFakeTimers()) await this._clock.runToLastAsync();
2176
+ }
2177
+ advanceTimersToNextTimer(steps = 1) {
2178
+ if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
2179
+ this._clock.next();
2180
+ this._clock.tick(0);
2181
+ if (this._clock.countTimers() === 0) break;
2182
+ }
2183
+ }
2184
+ async advanceTimersToNextTimerAsync(steps = 1) {
2185
+ if (this._checkFakeTimers()) for (let i = steps; i > 0; i--) {
2186
+ await this._clock.nextAsync();
2187
+ this._clock.tick(0);
2188
+ if (this._clock.countTimers() === 0) break;
2189
+ }
2190
+ }
2191
+ advanceTimersByTime(msToRun) {
2192
+ if (this._checkFakeTimers()) this._clock.tick(msToRun);
2193
+ }
2194
+ async advanceTimersByTimeAsync(msToRun) {
2195
+ if (this._checkFakeTimers()) await this._clock.tickAsync(msToRun);
2196
+ }
2197
+ advanceTimersToNextFrame() {
2198
+ if (this._checkFakeTimers()) this._clock.runToFrame();
2199
+ }
2200
+ runAllTicks() {
2201
+ if (this._checkFakeTimers()) this._clock.runMicrotasks();
2202
+ }
2203
+ useRealTimers() {
2204
+ if (this._fakingDate) {
2205
+ resetDate();
2206
+ this._fakingDate = null;
2207
+ }
2208
+ if (this._fakingTime) {
2209
+ this._clock.uninstall();
2210
+ this._fakingTime = false;
2211
+ }
2212
+ }
2213
+ useFakeTimers() {
2214
+ const fakeDate = this._fakingDate || Date.now();
2215
+ if (this._fakingDate) {
2216
+ resetDate();
2217
+ this._fakingDate = null;
2218
+ }
2219
+ if (this._fakingTime) this._clock.uninstall();
2220
+ const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
2221
+ if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
2222
+ this._clock = this._fakeTimers.install({
2223
+ now: fakeDate,
2224
+ ...this._userConfig,
2225
+ toFake: this._userConfig?.toFake || toFake,
2226
+ ignoreMissingTimers: true
2227
+ });
2228
+ this._fakingTime = true;
2229
+ }
2230
+ reset() {
2231
+ if (this._checkFakeTimers()) {
2232
+ const { now } = this._clock;
2233
+ this._clock.reset();
2234
+ this._clock.setSystemTime(now);
2235
+ }
2236
+ }
2237
+ setSystemTime(now) {
2238
+ const date = typeof now === "undefined" || now instanceof Date ? now : new Date(now);
2239
+ if (this._fakingTime) this._clock.setSystemTime(date);
2240
+ else {
2241
+ this._fakingDate = date ?? new Date(this.getRealSystemTime());
2242
+ mockDate(this._fakingDate);
2243
+ }
2244
+ }
2245
+ getMockedSystemTime() {
2246
+ return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
2247
+ }
2248
+ getRealSystemTime() {
2249
+ return this._now();
2250
+ }
2251
+ getTimerCount() {
2252
+ if (this._checkFakeTimers()) return this._clock.countTimers();
2253
+ return 0;
2254
+ }
2255
+ configure(config) {
2256
+ this._userConfig = config;
2257
+ }
2258
+ isFakeTimers() {
2259
+ return this._fakingTime;
2260
+ }
2261
+ _checkFakeTimers() {
2262
+ if (!this._fakingTime) throw new Error("A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.");
2263
+ return this._fakingTime;
2264
+ }
2265
+ };
2266
+ function copyStackTrace(target, source) {
2267
+ if (source.stack !== void 0) target.stack = source.stack.replace(source.message, target.message);
2268
+ return target;
2269
+ }
2270
+ function waitFor(callback, options = {}) {
2271
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
2272
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
2273
+ const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
2274
+ return new Promise((resolve, reject) => {
2275
+ let lastError;
2276
+ let promiseStatus = "idle";
2277
+ let timeoutId;
2278
+ let intervalId;
2279
+ const onResolve = (result) => {
2280
+ if (timeoutId) clearTimeout(timeoutId);
2281
+ if (intervalId) clearInterval(intervalId);
2282
+ resolve(result);
2283
+ };
2284
+ const handleTimeout = () => {
2285
+ if (intervalId) clearInterval(intervalId);
2286
+ let error = lastError;
2287
+ if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR);
2288
+ reject(error);
2289
+ };
2290
+ const checkCallback = () => {
2291
+ if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
2292
+ if (promiseStatus === "pending") return;
2293
+ try {
2294
+ const result = callback();
2295
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
2296
+ const thenable = result;
2297
+ promiseStatus = "pending";
2298
+ thenable.then((resolvedValue) => {
2299
+ promiseStatus = "resolved";
2300
+ onResolve(resolvedValue);
2301
+ }, (rejectedValue) => {
2302
+ promiseStatus = "rejected";
2303
+ lastError = rejectedValue;
2304
+ });
2305
+ } else {
2306
+ onResolve(result);
2307
+ return true;
2308
+ }
2309
+ } catch (error) {
2310
+ lastError = error;
2311
+ }
2312
+ };
2313
+ if (checkCallback() === true) return;
2314
+ timeoutId = setTimeout(handleTimeout, timeout);
2315
+ intervalId = setInterval(checkCallback, interval);
2316
+ });
2317
+ }
2318
+ function waitUntil(callback, options = {}) {
2319
+ const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers();
2320
+ const { interval = 50, timeout = 1e3 } = typeof options === "number" ? { timeout: options } : options;
2321
+ const STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
2322
+ return new Promise((resolve, reject) => {
2323
+ let promiseStatus = "idle";
2324
+ let timeoutId;
2325
+ let intervalId;
2326
+ const onReject = (error) => {
2327
+ if (intervalId) clearInterval(intervalId);
2328
+ if (!error) error = copyStackTrace(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR);
2329
+ reject(error);
2330
+ };
2331
+ const onResolve = (result) => {
2332
+ if (!result) return;
2333
+ if (timeoutId) clearTimeout(timeoutId);
2334
+ if (intervalId) clearInterval(intervalId);
2335
+ resolve(result);
2336
+ return true;
2337
+ };
2338
+ const checkCallback = () => {
2339
+ if (vi.isFakeTimers()) vi.advanceTimersByTime(interval);
2340
+ if (promiseStatus === "pending") return;
2341
+ try {
2342
+ const result = callback();
2343
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
2344
+ const thenable = result;
2345
+ promiseStatus = "pending";
2346
+ thenable.then((resolvedValue) => {
2347
+ promiseStatus = "resolved";
2348
+ onResolve(resolvedValue);
2349
+ }, (rejectedValue) => {
2350
+ promiseStatus = "rejected";
2351
+ onReject(rejectedValue);
2352
+ });
2353
+ } else return onResolve(result);
2354
+ } catch (error) {
2355
+ onReject(error);
2356
+ }
2357
+ };
2358
+ if (checkCallback() === true) return;
2359
+ timeoutId = setTimeout(onReject, timeout);
2360
+ intervalId = setInterval(checkCallback, interval);
2361
+ });
2362
+ }
2363
+ function createVitest() {
2364
+ let _config = null;
2365
+ const state = () => getWorkerState();
2366
+ let _timers;
2367
+ const timers = () => _timers ||= new FakeTimers({
2368
+ global: globalThis,
2369
+ config: state().config.fakeTimers
2370
+ });
2371
+ const _stubsGlobal = /* @__PURE__ */ new Map();
2372
+ const _stubsEnv = /* @__PURE__ */ new Map();
2373
+ const _envBooleans = [
2374
+ "PROD",
2375
+ "DEV",
2376
+ "SSR"
2377
+ ];
2378
+ const utils = {
2379
+ useFakeTimers(config) {
2380
+ if (isChildProcess()) {
2381
+ if (config?.toFake?.includes("nextTick") || state().config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
2382
+ }
2383
+ if (config) timers().configure({
2384
+ ...state().config.fakeTimers,
2385
+ ...config
2386
+ });
2387
+ else timers().configure(state().config.fakeTimers);
2388
+ timers().useFakeTimers();
2389
+ return utils;
2390
+ },
2391
+ isFakeTimers() {
2392
+ return timers().isFakeTimers();
2393
+ },
2394
+ useRealTimers() {
2395
+ timers().useRealTimers();
2396
+ return utils;
2397
+ },
2398
+ runOnlyPendingTimers() {
2399
+ timers().runOnlyPendingTimers();
2400
+ return utils;
2401
+ },
2402
+ async runOnlyPendingTimersAsync() {
2403
+ await timers().runOnlyPendingTimersAsync();
2404
+ return utils;
2405
+ },
2406
+ runAllTimers() {
2407
+ timers().runAllTimers();
2408
+ return utils;
2409
+ },
2410
+ async runAllTimersAsync() {
2411
+ await timers().runAllTimersAsync();
2412
+ return utils;
2413
+ },
2414
+ runAllTicks() {
2415
+ timers().runAllTicks();
2416
+ return utils;
2417
+ },
2418
+ advanceTimersByTime(ms) {
2419
+ timers().advanceTimersByTime(ms);
2420
+ return utils;
2421
+ },
2422
+ async advanceTimersByTimeAsync(ms) {
2423
+ await timers().advanceTimersByTimeAsync(ms);
2424
+ return utils;
2425
+ },
2426
+ advanceTimersToNextTimer() {
2427
+ timers().advanceTimersToNextTimer();
2428
+ return utils;
2429
+ },
2430
+ async advanceTimersToNextTimerAsync() {
2431
+ await timers().advanceTimersToNextTimerAsync();
2432
+ return utils;
2433
+ },
2434
+ advanceTimersToNextFrame() {
2435
+ timers().advanceTimersToNextFrame();
2436
+ return utils;
2437
+ },
2438
+ getTimerCount() {
2439
+ return timers().getTimerCount();
2440
+ },
2441
+ setSystemTime(time) {
2442
+ timers().setSystemTime(time);
2443
+ return utils;
2444
+ },
2445
+ getMockedSystemTime() {
2446
+ return timers().getMockedSystemTime();
2447
+ },
2448
+ getRealSystemTime() {
2449
+ return timers().getRealSystemTime();
2450
+ },
2451
+ clearAllTimers() {
2452
+ timers().clearAllTimers();
2453
+ return utils;
2454
+ },
2455
+ spyOn,
2456
+ fn,
2457
+ waitFor,
2458
+ waitUntil,
2459
+ hoisted(factory) {
2460
+ assertTypes(factory, "\"vi.hoisted\" factory", ["function"]);
2461
+ return factory();
2462
+ },
2463
+ mock(path, factory) {
2464
+ if (typeof path !== "string") throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
2465
+ const importer = getImporter("mock");
2466
+ _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
2467
+ },
2468
+ unmock(path) {
2469
+ if (typeof path !== "string") throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
2470
+ _mocker().queueUnmock(path, getImporter("unmock"));
2471
+ },
2472
+ doMock(path, factory) {
2473
+ if (typeof path !== "string") throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
2474
+ const importer = getImporter("doMock");
2475
+ _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
2476
+ },
2477
+ doUnmock(path) {
2478
+ if (typeof path !== "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
2479
+ const importer = getImporter("doUnmock");
2480
+ _mocker().queueUnmock(path, importer);
2481
+ },
2482
+ async importActual(path) {
2483
+ const importer = getImporter("importActual");
2484
+ return _mocker().importActual(path, importer, _mocker().getMockContext().callstack);
2485
+ },
2486
+ async importMock(path) {
2487
+ const importer = getImporter("importMock");
2488
+ return _mocker().importMock(path, importer);
2489
+ },
2490
+ mockObject(value, options) {
2491
+ return _mocker().mockObject({ value }, void 0, options?.spy ? "autospy" : "automock").value;
2492
+ },
2493
+ mocked(item, _options = {}) {
2494
+ return item;
2495
+ },
2496
+ isMockFunction(fn$1) {
2497
+ return isMockFunction(fn$1);
2498
+ },
2499
+ clearAllMocks() {
2500
+ clearAllMocks();
2501
+ return utils;
2502
+ },
2503
+ resetAllMocks() {
2504
+ resetAllMocks();
2505
+ return utils;
2506
+ },
2507
+ restoreAllMocks() {
2508
+ restoreAllMocks();
2509
+ return utils;
2510
+ },
2511
+ stubGlobal(name, value) {
2512
+ if (!_stubsGlobal.has(name)) _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
2513
+ Object.defineProperty(globalThis, name, {
2514
+ value,
2515
+ writable: true,
2516
+ configurable: true,
2517
+ enumerable: true
2518
+ });
2519
+ return utils;
2520
+ },
2521
+ stubEnv(name, value) {
2522
+ const env = state().metaEnv;
2523
+ if (!_stubsEnv.has(name)) _stubsEnv.set(name, env[name]);
2524
+ if (_envBooleans.includes(name)) env[name] = value ? "1" : "";
2525
+ else if (value === void 0) delete env[name];
2526
+ else env[name] = String(value);
2527
+ return utils;
2528
+ },
2529
+ unstubAllGlobals() {
2530
+ _stubsGlobal.forEach((original, name) => {
2531
+ if (!original) Reflect.deleteProperty(globalThis, name);
2532
+ else Object.defineProperty(globalThis, name, original);
2533
+ });
2534
+ _stubsGlobal.clear();
2535
+ return utils;
2536
+ },
2537
+ unstubAllEnvs() {
2538
+ const env = state().metaEnv;
2539
+ _stubsEnv.forEach((original, name) => {
2540
+ if (original === void 0) delete env[name];
2541
+ else env[name] = original;
2542
+ });
2543
+ _stubsEnv.clear();
2544
+ return utils;
2545
+ },
2546
+ resetModules() {
2547
+ resetModules(state().evaluatedModules);
2548
+ return utils;
2549
+ },
2550
+ async dynamicImportSettled() {
2551
+ return waitForImportsToResolve();
2552
+ },
2553
+ setConfig(config) {
2554
+ if (!_config) _config = { ...state().config };
2555
+ Object.assign(state().config, config);
2556
+ },
2557
+ resetConfig() {
2558
+ if (_config) Object.assign(state().config, _config);
2559
+ }
2560
+ };
2561
+ return utils;
2562
+ }
2563
+ const vitest = createVitest();
2564
+ const vi = vitest;
2565
+ function _mocker() {
2566
+ return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : new Proxy({}, { get(_, name) {
2567
+ throw new Error(`Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`);
2568
+ } });
2569
+ }
2570
+ function getImporter(name) {
2571
+ const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n");
2572
+ return parseSingleStack(stackArray[stackArray.findLastIndex((stack) => {
2573
+ return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`) || stack.includes(` at ${name} (`);
2574
+ }) + 1])?.file || "";
2575
+ }
2576
+
2577
+ //#endregion
2578
+ export { globalExpect };