@noma.to/qwik-mock 1.0.2 → 1.1.1

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