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