@antdv-next/x-sdk 0.0.1 → 0.0.2

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