@fangorn-network/sdk 2026.9.22-dev → 2026.10.1-9.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +190 -194
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +177 -201
  4. package/lib/cli/index.d.ts +3 -91
  5. package/lib/cli/index.js +5 -2
  6. package/lib/config.d.ts +358 -117
  7. package/lib/config.js +43 -23
  8. package/lib/contracts/app-registry/abi.d.ts +1033 -277
  9. package/lib/contracts/app-registry/abi.js +1214 -335
  10. package/lib/contracts/app-registry/index.d.ts +105 -65
  11. package/lib/contracts/app-registry/index.js +182 -175
  12. package/lib/contracts/data-registry/abi.d.ts +166 -187
  13. package/lib/contracts/data-registry/abi.js +207 -237
  14. package/lib/contracts/data-registry/index.d.ts +4 -151
  15. package/lib/contracts/data-registry/index.js +5 -279
  16. package/lib/contracts/index.d.ts +6 -7
  17. package/lib/contracts/index.js +6 -8
  18. package/lib/contracts/logs.d.ts +4 -1
  19. package/lib/contracts/logs.js +9 -2
  20. package/lib/contracts/membership-registry/abi.d.ts +1145 -0
  21. package/lib/contracts/membership-registry/abi.js +1333 -0
  22. package/lib/contracts/membership-registry/index.d.ts +79 -0
  23. package/lib/contracts/membership-registry/index.js +104 -0
  24. package/lib/contracts/types.d.ts +3 -1
  25. package/lib/contracts/types.js +3 -1
  26. package/lib/contracts/write.d.ts +34 -2
  27. package/lib/contracts/write.js +48 -1
  28. package/lib/crypto/encryption.js +4 -4
  29. package/lib/engine/car.d.ts +2 -2
  30. package/lib/engine/car.js +10 -5
  31. package/lib/engine/index.d.ts +99 -143
  32. package/lib/engine/index.js +156 -295
  33. package/lib/engine/records.d.ts +110 -0
  34. package/lib/engine/records.js +165 -0
  35. package/lib/engine/test-helpers.d.ts +7 -14
  36. package/lib/engine/test-helpers.js +7 -18
  37. package/lib/fangorn.d.ts +129 -156
  38. package/lib/fangorn.js +250 -250
  39. package/lib/feed.d.ts +7 -4
  40. package/lib/feed.js +4 -1
  41. package/lib/index.d.ts +9 -9
  42. package/lib/index.js +8 -9
  43. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  44. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  45. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  46. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  47. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  48. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  49. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  50. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  51. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  52. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  53. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  54. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  55. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  56. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  57. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  58. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  59. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  60. package/lib/node_modules/chai/index.js +2874 -0
  61. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  62. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  64. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  65. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  66. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  67. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  68. package/lib/providers/storage/signed-url.d.ts +16 -6
  69. package/lib/providers/storage/signed-url.js +20 -8
  70. package/lib/registry.d.ts +116 -0
  71. package/lib/registry.js +182 -0
  72. package/lib/test/mem-registry.d.ts +51 -0
  73. package/lib/test/mem-registry.js +107 -0
  74. package/lib/test/sdk-suite.d.ts +13 -0
  75. package/lib/test/sdk-suite.js +226 -0
  76. package/lib/test/testbed.d.ts +16411 -61
  77. package/lib/test/testbed.js +190 -84
  78. package/lib/types/index.d.ts +13 -11
  79. package/package.json +89 -73
  80. package/lib/contracts/data-registry/test.d.ts +0 -1
  81. package/lib/contracts/data-registry/test.js +0 -1
  82. package/lib/contracts/settlement-registry/abi.d.ts +0 -466
  83. package/lib/contracts/settlement-registry/abi.js +0 -535
  84. package/lib/contracts/settlement-registry/index.d.ts +0 -163
  85. package/lib/contracts/settlement-registry/index.js +0 -264
  86. package/lib/contracts/subscription-registry/abi.d.ts +0 -179
  87. package/lib/contracts/subscription-registry/abi.js +0 -195
  88. package/lib/contracts/subscription-registry/index.d.ts +0 -59
  89. package/lib/contracts/subscription-registry/index.js +0 -116
  90. package/lib/engine/graph.d.ts +0 -70
  91. package/lib/engine/graph.js +0 -73
@@ -0,0 +1,1199 @@
1
+ import { format, formatRegExp, objDisplay } from "../../utils/dist/display.js";
2
+ import { assertTypes, createDefer, isNegativeNaN, isObject, objectAttr, toArray } from "../../utils/dist/helpers.js";
3
+ import { getSafeTimers } from "../../utils/dist/timers.js";
4
+ import { createChainable, createTaskName, findTestFileStackTrace } from "./chunk-tasks.js";
5
+
6
+ //#region node_modules/@vitest/runner/dist/index.js
7
+ var PendingError = class extends Error {
8
+ code = "VITEST_PENDING";
9
+ taskId;
10
+ constructor(message, task, note) {
11
+ super(message);
12
+ this.message = message;
13
+ this.note = note;
14
+ this.taskId = task.id;
15
+ }
16
+ };
17
+ const fnMap = /* @__PURE__ */ new WeakMap();
18
+ const testFixtureMap = /* @__PURE__ */ new WeakMap();
19
+ const hooksMap = /* @__PURE__ */ new WeakMap();
20
+ function setFn(key, fn) {
21
+ fnMap.set(key, fn);
22
+ }
23
+ function setTestFixture(key, fixture) {
24
+ testFixtureMap.set(key, fixture);
25
+ }
26
+ function getTestFixture(key) {
27
+ return testFixtureMap.get(key);
28
+ }
29
+ function setHooks(key, hooks) {
30
+ hooksMap.set(key, hooks);
31
+ }
32
+ function getHooks(key) {
33
+ return hooksMap.get(key);
34
+ }
35
+ function mergeScopedFixtures(testFixtures, scopedFixtures) {
36
+ const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
37
+ map[fixture.prop] = fixture;
38
+ return map;
39
+ }, {});
40
+ const newFixtures = {};
41
+ testFixtures.forEach((fixture) => {
42
+ const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
43
+ newFixtures[useFixture.prop] = useFixture;
44
+ });
45
+ for (const fixtureKep in newFixtures) {
46
+ var _fixture$deps;
47
+ const fixture = newFixtures[fixtureKep];
48
+ fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
49
+ }
50
+ return Object.values(newFixtures);
51
+ }
52
+ function mergeContextFixtures(fixtures, context, runner$1) {
53
+ const fixtureOptionKeys = [
54
+ "auto",
55
+ "injected",
56
+ "scope"
57
+ ];
58
+ const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
59
+ const fixtureItem = { value };
60
+ if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
61
+ var _runner$injectValue;
62
+ Object.assign(fixtureItem, value[1]);
63
+ const userValue = value[0];
64
+ fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner$1.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner$1, prop)) ?? userValue : userValue;
65
+ }
66
+ fixtureItem.scope = fixtureItem.scope || "test";
67
+ if (fixtureItem.scope === "worker" && !runner$1.getWorkerContext) fixtureItem.scope = "file";
68
+ fixtureItem.prop = prop;
69
+ fixtureItem.isFn = typeof fixtureItem.value === "function";
70
+ return fixtureItem;
71
+ });
72
+ if (Array.isArray(context.fixtures)) context.fixtures = context.fixtures.concat(fixtureArray);
73
+ else context.fixtures = fixtureArray;
74
+ fixtureArray.forEach((fixture) => {
75
+ if (fixture.isFn) {
76
+ const usedProps = getUsedProps(fixture.value);
77
+ if (usedProps.length) fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
78
+ if (fixture.scope !== "test") {
79
+ var _fixture$deps2;
80
+ (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 || _fixture$deps2.forEach((dep) => {
81
+ if (!dep.isFn) return;
82
+ if (fixture.scope === "worker" && dep.scope === "worker") return;
83
+ if (fixture.scope === "file" && dep.scope !== "test") return;
84
+ throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`);
85
+ });
86
+ }
87
+ }
88
+ });
89
+ return context;
90
+ }
91
+ const fixtureValueMaps = /* @__PURE__ */ new Map();
92
+ const cleanupFnArrayMap = /* @__PURE__ */ new Map();
93
+ function withFixtures(runner$1, fn, testContext) {
94
+ return (hookContext) => {
95
+ const context = hookContext || testContext;
96
+ if (!context) return fn({});
97
+ const fixtures = getTestFixture(context);
98
+ if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) return fn(context);
99
+ const usedProps = getUsedProps(fn);
100
+ const hasAutoFixture = fixtures.some(({ auto }) => auto);
101
+ if (!usedProps.length && !hasAutoFixture) return fn(context);
102
+ if (!fixtureValueMaps.get(context)) fixtureValueMaps.set(context, /* @__PURE__ */ new Map());
103
+ const fixtureValueMap = fixtureValueMaps.get(context);
104
+ if (!cleanupFnArrayMap.has(context)) cleanupFnArrayMap.set(context, []);
105
+ const cleanupFnArray = cleanupFnArrayMap.get(context);
106
+ const pendingFixtures = resolveDeps(fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop)));
107
+ if (!pendingFixtures.length) return fn(context);
108
+ async function resolveFixtures() {
109
+ for (const fixture of pendingFixtures) {
110
+ if (fixtureValueMap.has(fixture)) continue;
111
+ const resolvedValue = await resolveFixtureValue(runner$1, fixture, context, cleanupFnArray);
112
+ context[fixture.prop] = resolvedValue;
113
+ fixtureValueMap.set(fixture, resolvedValue);
114
+ if (fixture.scope === "test") cleanupFnArray.unshift(() => {
115
+ fixtureValueMap.delete(fixture);
116
+ });
117
+ }
118
+ }
119
+ return resolveFixtures().then(() => fn(context));
120
+ };
121
+ }
122
+ const globalFixturePromise = /* @__PURE__ */ new WeakMap();
123
+ function resolveFixtureValue(runner$1, fixture, context, cleanupFnArray) {
124
+ var _runner$getWorkerCont;
125
+ const fileContext = getFileContext(context.task.file);
126
+ const workerContext = (_runner$getWorkerCont = runner$1.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner$1);
127
+ if (!fixture.isFn) {
128
+ var _fixture$prop;
129
+ fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value);
130
+ if (workerContext) {
131
+ var _fixture$prop2;
132
+ workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value);
133
+ }
134
+ return fixture.value;
135
+ }
136
+ if (fixture.scope === "test") return resolveFixtureFunction(fixture.value, context, cleanupFnArray);
137
+ if (globalFixturePromise.has(fixture)) return globalFixturePromise.get(fixture);
138
+ let fixtureContext;
139
+ if (fixture.scope === "worker") {
140
+ if (!workerContext) throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.");
141
+ fixtureContext = workerContext;
142
+ } else fixtureContext = fileContext;
143
+ if (fixture.prop in fixtureContext) return fixtureContext[fixture.prop];
144
+ if (!cleanupFnArrayMap.has(fixtureContext)) cleanupFnArrayMap.set(fixtureContext, []);
145
+ const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
146
+ const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => {
147
+ fixtureContext[fixture.prop] = value;
148
+ globalFixturePromise.delete(fixture);
149
+ return value;
150
+ });
151
+ globalFixturePromise.set(fixture, promise);
152
+ return promise;
153
+ }
154
+ async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
155
+ const useFnArgPromise = createDefer();
156
+ let isUseFnArgResolved = false;
157
+ const fixtureReturn = fixtureFn(context, async (useFnArg) => {
158
+ isUseFnArgResolved = true;
159
+ useFnArgPromise.resolve(useFnArg);
160
+ const useReturnPromise = createDefer();
161
+ cleanupFnArray.push(async () => {
162
+ useReturnPromise.resolve();
163
+ await fixtureReturn;
164
+ });
165
+ await useReturnPromise;
166
+ }).catch((e) => {
167
+ if (!isUseFnArgResolved) {
168
+ useFnArgPromise.reject(e);
169
+ return;
170
+ }
171
+ throw e;
172
+ });
173
+ return useFnArgPromise;
174
+ }
175
+ function resolveDeps(fixtures, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
176
+ fixtures.forEach((fixture) => {
177
+ if (pendingFixtures.includes(fixture)) return;
178
+ if (!fixture.isFn || !fixture.deps) {
179
+ pendingFixtures.push(fixture);
180
+ return;
181
+ }
182
+ if (depSet.has(fixture)) throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
183
+ depSet.add(fixture);
184
+ resolveDeps(fixture.deps, depSet, pendingFixtures);
185
+ pendingFixtures.push(fixture);
186
+ depSet.clear();
187
+ });
188
+ return pendingFixtures;
189
+ }
190
+ function getUsedProps(fn) {
191
+ let fnString = filterOutComments(fn.toString());
192
+ if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) fnString = fnString.split(/__async\((?:this|null),/)[1];
193
+ const match = fnString.match(/[^(]*\(([^)]*)/);
194
+ if (!match) return [];
195
+ const args = splitByComma(match[1]);
196
+ if (!args.length) return [];
197
+ let first = args[0];
198
+ if ("__VITEST_FIXTURE_INDEX__" in fn) {
199
+ first = args[fn.__VITEST_FIXTURE_INDEX__];
200
+ if (!first) return [];
201
+ }
202
+ if (!(first[0] === "{" && first.endsWith("}"))) throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
203
+ const props = splitByComma(first.slice(1, -1).replace(/\s/g, "")).map((prop) => {
204
+ return prop.replace(/:.*|=.*/g, "");
205
+ });
206
+ const last = props.at(-1);
207
+ if (last && last.startsWith("...")) throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
208
+ return props;
209
+ }
210
+ function filterOutComments(s) {
211
+ const result = [];
212
+ let commentState = "none";
213
+ for (let i = 0; i < s.length; ++i) if (commentState === "singleline") {
214
+ if (s[i] === "\n") commentState = "none";
215
+ } else if (commentState === "multiline") {
216
+ if (s[i - 1] === "*" && s[i] === "/") commentState = "none";
217
+ } else if (commentState === "none") if (s[i] === "/" && s[i + 1] === "/") commentState = "singleline";
218
+ else if (s[i] === "/" && s[i + 1] === "*") {
219
+ commentState = "multiline";
220
+ i += 2;
221
+ } else result.push(s[i]);
222
+ return result.join("");
223
+ }
224
+ function splitByComma(s) {
225
+ const result = [];
226
+ const stack = [];
227
+ let start = 0;
228
+ for (let i = 0; i < s.length; i++) if (s[i] === "{" || s[i] === "[") stack.push(s[i] === "{" ? "}" : "]");
229
+ else if (s[i] === stack.at(-1)) stack.pop();
230
+ else if (!stack.length && s[i] === ",") {
231
+ const token = s.substring(start, i).trim();
232
+ if (token) result.push(token);
233
+ start = i + 1;
234
+ }
235
+ const lastToken = s.substring(start).trim();
236
+ if (lastToken) result.push(lastToken);
237
+ return result;
238
+ }
239
+ let _test;
240
+ function getCurrentTest() {
241
+ return _test;
242
+ }
243
+ function getDefaultHookTimeout() {
244
+ return getRunner().config.hookTimeout;
245
+ }
246
+ const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
247
+ const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
248
+ /**
249
+ * Registers a callback function to be executed once before all tests within the current suite.
250
+ * This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
251
+ *
252
+ * **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
253
+ *
254
+ * @param {Function} fn - The callback function to be executed before all tests.
255
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
256
+ * @returns {void}
257
+ * @example
258
+ * ```ts
259
+ * // Example of using beforeAll to set up a database connection
260
+ * beforeAll(async () => {
261
+ * await database.connect();
262
+ * });
263
+ * ```
264
+ */
265
+ function beforeAll(fn, timeout = getDefaultHookTimeout()) {
266
+ assertTypes(fn, "\"beforeAll\" callback", ["function"]);
267
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
268
+ return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), {
269
+ [CLEANUP_TIMEOUT_KEY]: timeout,
270
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
271
+ }));
272
+ }
273
+ /**
274
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
275
+ * This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
276
+ *
277
+ * **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
278
+ *
279
+ * @param {Function} fn - The callback function to be executed after all tests.
280
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
281
+ * @returns {void}
282
+ * @example
283
+ * ```ts
284
+ * // Example of using afterAll to close a database connection
285
+ * afterAll(async () => {
286
+ * await database.disconnect();
287
+ * });
288
+ * ```
289
+ */
290
+ function afterAll(fn, timeout) {
291
+ assertTypes(fn, "\"afterAll\" callback", ["function"]);
292
+ return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR")));
293
+ }
294
+ /**
295
+ * Registers a callback function to be executed before each test within the current suite.
296
+ * This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
297
+ *
298
+ * **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
299
+ *
300
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
301
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
302
+ * @returns {void}
303
+ * @example
304
+ * ```ts
305
+ * // Example of using beforeEach to reset a database state
306
+ * beforeEach(async () => {
307
+ * await database.reset();
308
+ * });
309
+ * ```
310
+ */
311
+ function beforeEach(fn, timeout = getDefaultHookTimeout()) {
312
+ assertTypes(fn, "\"beforeEach\" callback", ["function"]);
313
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
314
+ const runner$1 = getRunner();
315
+ return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner$1, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
316
+ [CLEANUP_TIMEOUT_KEY]: timeout,
317
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
318
+ }));
319
+ }
320
+ /**
321
+ * Registers a callback function to be executed after each test within the current suite has completed.
322
+ * This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
323
+ *
324
+ * **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
325
+ *
326
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
327
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
328
+ * @returns {void}
329
+ * @example
330
+ * ```ts
331
+ * // Example of using afterEach to delete temporary files created during a test
332
+ * afterEach(async () => {
333
+ * await fileSystem.deleteTempFiles();
334
+ * });
335
+ * ```
336
+ */
337
+ function afterEach(fn, timeout) {
338
+ assertTypes(fn, "\"afterEach\" callback", ["function"]);
339
+ const runner$1 = getRunner();
340
+ return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner$1, fn), timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
341
+ }
342
+ /**
343
+ * Registers a callback function to be executed when a test fails within the current suite.
344
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
345
+ *
346
+ * **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
347
+ *
348
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
349
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
350
+ * @throws {Error} Throws an error if the function is not called within a test.
351
+ * @returns {void}
352
+ * @example
353
+ * ```ts
354
+ * // Example of using onTestFailed to log failure details
355
+ * onTestFailed(({ errors }) => {
356
+ * console.log(`Test failed: ${test.name}`, errors);
357
+ * });
358
+ * ```
359
+ */
360
+ const onTestFailed = createTestHook("onTestFailed", (test$1, handler, timeout) => {
361
+ test$1.onFailed || (test$1.onFailed = []);
362
+ test$1.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
363
+ });
364
+ /**
365
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
366
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
367
+ *
368
+ * This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
369
+ *
370
+ * **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
371
+ *
372
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
373
+ *
374
+ * @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
375
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
376
+ * @throws {Error} Throws an error if the function is not called within a test.
377
+ * @returns {void}
378
+ * @example
379
+ * ```ts
380
+ * // Example of using onTestFinished for cleanup
381
+ * const db = await connectToDatabase();
382
+ * onTestFinished(async () => {
383
+ * await db.disconnect();
384
+ * });
385
+ * ```
386
+ */
387
+ const onTestFinished = createTestHook("onTestFinished", (test$1, handler, timeout) => {
388
+ test$1.onFinished || (test$1.onFinished = []);
389
+ test$1.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
390
+ });
391
+ function createTestHook(name, handler) {
392
+ return (fn, timeout) => {
393
+ assertTypes(fn, `"${name}" callback`, ["function"]);
394
+ const current = getCurrentTest();
395
+ if (!current) throw new Error(`Hook ${name}() can only be called inside a test`);
396
+ return handler(current, fn, timeout);
397
+ };
398
+ }
399
+ /**
400
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
401
+ * Suites can contain both tests and other suites, enabling complex test structures.
402
+ *
403
+ * @param {string} name - The name of the suite, used for identification and reporting.
404
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
405
+ * @example
406
+ * ```ts
407
+ * // Define a suite with two tests
408
+ * suite('Math operations', () => {
409
+ * test('should add two numbers', () => {
410
+ * expect(add(1, 2)).toBe(3);
411
+ * });
412
+ *
413
+ * test('should subtract two numbers', () => {
414
+ * expect(subtract(5, 2)).toBe(3);
415
+ * });
416
+ * });
417
+ * ```
418
+ * @example
419
+ * ```ts
420
+ * // Define nested suites
421
+ * suite('String operations', () => {
422
+ * suite('Trimming', () => {
423
+ * test('should trim whitespace from start and end', () => {
424
+ * expect(' hello '.trim()).toBe('hello');
425
+ * });
426
+ * });
427
+ *
428
+ * suite('Concatenation', () => {
429
+ * test('should concatenate two strings', () => {
430
+ * expect('hello' + ' ' + 'world').toBe('hello world');
431
+ * });
432
+ * });
433
+ * });
434
+ * ```
435
+ */
436
+ const suite = createSuite();
437
+ /**
438
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
439
+ *
440
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
441
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
442
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
443
+ * @throws {Error} If called inside another test function.
444
+ * @example
445
+ * ```ts
446
+ * // Define a simple test
447
+ * test('should add two numbers', () => {
448
+ * expect(add(1, 2)).toBe(3);
449
+ * });
450
+ * ```
451
+ * @example
452
+ * ```ts
453
+ * // Define a test with options
454
+ * test('should subtract two numbers', { retry: 3 }, () => {
455
+ * expect(subtract(5, 2)).toBe(3);
456
+ * });
457
+ * ```
458
+ */
459
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
460
+ if (getCurrentTest()) throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected.");
461
+ getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
462
+ });
463
+ /**
464
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
465
+ * Suites can contain both tests and other suites, enabling complex test structures.
466
+ *
467
+ * @param {string} name - The name of the suite, used for identification and reporting.
468
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
469
+ * @example
470
+ * ```ts
471
+ * // Define a suite with two tests
472
+ * describe('Math operations', () => {
473
+ * test('should add two numbers', () => {
474
+ * expect(add(1, 2)).toBe(3);
475
+ * });
476
+ *
477
+ * test('should subtract two numbers', () => {
478
+ * expect(subtract(5, 2)).toBe(3);
479
+ * });
480
+ * });
481
+ * ```
482
+ * @example
483
+ * ```ts
484
+ * // Define nested suites
485
+ * describe('String operations', () => {
486
+ * describe('Trimming', () => {
487
+ * test('should trim whitespace from start and end', () => {
488
+ * expect(' hello '.trim()).toBe('hello');
489
+ * });
490
+ * });
491
+ *
492
+ * describe('Concatenation', () => {
493
+ * test('should concatenate two strings', () => {
494
+ * expect('hello' + ' ' + 'world').toBe('hello world');
495
+ * });
496
+ * });
497
+ * });
498
+ * ```
499
+ */
500
+ const describe = suite;
501
+ /**
502
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
503
+ *
504
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
505
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
506
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
507
+ * @throws {Error} If called inside another test function.
508
+ * @example
509
+ * ```ts
510
+ * // Define a simple test
511
+ * it('adds two numbers', () => {
512
+ * expect(add(1, 2)).toBe(3);
513
+ * });
514
+ * ```
515
+ * @example
516
+ * ```ts
517
+ * // Define a test with options
518
+ * it('subtracts two numbers', { retry: 3 }, () => {
519
+ * expect(subtract(5, 2)).toBe(3);
520
+ * });
521
+ * ```
522
+ */
523
+ const it = test;
524
+ let runner;
525
+ let defaultSuite;
526
+ let currentTestFilepath;
527
+ function assert(condition, message) {
528
+ if (!condition) throw new Error(`Vitest failed to find ${message}. One of the following is possible:
529
+ - "vitest" is imported directly without running "vitest" command
530
+ - "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)
531
+ - "vitest" is imported inside Vite / Vitest config file
532
+ - Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues
533
+ `);
534
+ }
535
+ function getRunner() {
536
+ assert(runner, "the runner");
537
+ return runner;
538
+ }
539
+ function getCurrentSuite() {
540
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
541
+ assert(currentSuite, "the current suite");
542
+ return currentSuite;
543
+ }
544
+ function createSuiteHooks() {
545
+ return {
546
+ beforeAll: [],
547
+ afterAll: [],
548
+ beforeEach: [],
549
+ afterEach: []
550
+ };
551
+ }
552
+ function parseArguments(optionsOrFn, timeoutOrTest) {
553
+ if (timeoutOrTest != null && typeof timeoutOrTest === "object") throw new TypeError(`Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.`);
554
+ let options = {};
555
+ let fn;
556
+ if (typeof timeoutOrTest === "number") options = { timeout: timeoutOrTest };
557
+ else if (typeof optionsOrFn === "object") options = optionsOrFn;
558
+ if (typeof optionsOrFn === "function") {
559
+ if (typeof timeoutOrTest === "function") throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
560
+ fn = optionsOrFn;
561
+ } else if (typeof timeoutOrTest === "function") fn = timeoutOrTest;
562
+ return {
563
+ options,
564
+ handler: fn
565
+ };
566
+ }
567
+ function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) {
568
+ const tasks = [];
569
+ let suite$1;
570
+ initSuite(true);
571
+ const task = function(name$1 = "", options = {}) {
572
+ var _collectorContext$cur, _collectorContext$cur2, _collectorContext$cur3;
573
+ const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
574
+ const currentSuite = (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite;
575
+ const task$1 = {
576
+ id: "",
577
+ name: name$1,
578
+ fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 || (_collectorContext$cur2 = _collectorContext$cur2.file) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.fullName), name$1]),
579
+ fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name$1]),
580
+ suite: currentSuite,
581
+ each: options.each,
582
+ fails: options.fails,
583
+ context: void 0,
584
+ type: "test",
585
+ file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur3 = collectorContext.currentSuite) === null || _collectorContext$cur3 === void 0 ? void 0 : _collectorContext$cur3.file),
586
+ timeout,
587
+ retry: options.retry ?? runner.config.retry,
588
+ repeats: options.repeats,
589
+ mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
590
+ meta: options.meta ?? Object.create(null),
591
+ annotations: [],
592
+ artifacts: []
593
+ };
594
+ const handler = options.handler;
595
+ if (task$1.mode === "run" && !handler) task$1.mode = "todo";
596
+ if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) task$1.concurrent = true;
597
+ task$1.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
598
+ const context = createTestContext(task$1, runner);
599
+ Object.defineProperty(task$1, "context", {
600
+ value: context,
601
+ enumerable: false
602
+ });
603
+ setTestFixture(context, options.fixtures);
604
+ const limit = Error.stackTraceLimit;
605
+ Error.stackTraceLimit = 15;
606
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
607
+ Error.stackTraceLimit = limit;
608
+ if (handler) setFn(task$1, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task$1), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
609
+ if (runner.config.includeTaskLocation) {
610
+ const error = stackTraceError.stack;
611
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
612
+ if (stack) task$1.location = {
613
+ line: stack.line,
614
+ column: stack.column
615
+ };
616
+ }
617
+ tasks.push(task$1);
618
+ return task$1;
619
+ };
620
+ const test$1 = createTest(function(name$1, optionsOrFn, timeoutOrTest) {
621
+ let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
622
+ if (typeof suiteOptions === "object") options = Object.assign({}, suiteOptions, options);
623
+ options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
624
+ options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
625
+ const test$2 = task(formatName(name$1), {
626
+ ...this,
627
+ ...options,
628
+ handler
629
+ });
630
+ test$2.type = "test";
631
+ });
632
+ let collectorFixtures = parentCollectorFixtures;
633
+ const collector = {
634
+ type: "collector",
635
+ name,
636
+ mode,
637
+ suite: suite$1,
638
+ options: suiteOptions,
639
+ test: test$1,
640
+ tasks,
641
+ collect,
642
+ task,
643
+ clear,
644
+ on: addHook,
645
+ fixtures() {
646
+ return collectorFixtures;
647
+ },
648
+ scoped(fixtures) {
649
+ const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner);
650
+ if (parsed.fixtures) collectorFixtures = parsed.fixtures;
651
+ }
652
+ };
653
+ function addHook(name$1, ...fn) {
654
+ getHooks(suite$1)[name$1].push(...fn);
655
+ }
656
+ function initSuite(includeLocation) {
657
+ var _collectorContext$cur4, _collectorContext$cur5, _collectorContext$cur6;
658
+ if (typeof suiteOptions === "number") suiteOptions = { timeout: suiteOptions };
659
+ const currentSuite = (_collectorContext$cur4 = collectorContext.currentSuite) === null || _collectorContext$cur4 === void 0 ? void 0 : _collectorContext$cur4.suite;
660
+ suite$1 = {
661
+ id: "",
662
+ type: "suite",
663
+ name,
664
+ fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur5 = collectorContext.currentSuite) === null || _collectorContext$cur5 === void 0 || (_collectorContext$cur5 = _collectorContext$cur5.file) === null || _collectorContext$cur5 === void 0 ? void 0 : _collectorContext$cur5.fullName), name]),
665
+ fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name]),
666
+ suite: currentSuite,
667
+ mode,
668
+ each,
669
+ file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur6 = collectorContext.currentSuite) === null || _collectorContext$cur6 === void 0 ? void 0 : _collectorContext$cur6.file),
670
+ shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
671
+ tasks: [],
672
+ meta: Object.create(null),
673
+ concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
674
+ };
675
+ if (runner && includeLocation && runner.config.includeTaskLocation) {
676
+ const limit = Error.stackTraceLimit;
677
+ Error.stackTraceLimit = 15;
678
+ const error = (/* @__PURE__ */ new Error("stacktrace")).stack;
679
+ Error.stackTraceLimit = limit;
680
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
681
+ if (stack) suite$1.location = {
682
+ line: stack.line,
683
+ column: stack.column
684
+ };
685
+ }
686
+ setHooks(suite$1, createSuiteHooks());
687
+ }
688
+ function clear() {
689
+ tasks.length = 0;
690
+ initSuite(false);
691
+ }
692
+ async function collect(file) {
693
+ if (!file) throw new TypeError("File is required to collect tasks.");
694
+ if (factory) await runWithSuite(collector, () => factory(test$1));
695
+ const allChildren = [];
696
+ for (const i of tasks) allChildren.push(i.type === "collector" ? await i.collect(file) : i);
697
+ suite$1.tasks = allChildren;
698
+ return suite$1;
699
+ }
700
+ collectTask(collector);
701
+ return collector;
702
+ }
703
+ function withAwaitAsyncAssertions(fn, task) {
704
+ return (async (...args) => {
705
+ const fnResult = await fn(...args);
706
+ if (task.promises) {
707
+ const errors = (await Promise.allSettled(task.promises)).map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
708
+ if (errors.length) throw errors;
709
+ }
710
+ return fnResult;
711
+ });
712
+ }
713
+ function createSuite() {
714
+ function suiteFn(name, factoryOrOptions, optionsOrFactory) {
715
+ var _currentSuite$options;
716
+ if (getCurrentTest()) throw new Error("Calling the suite function inside test function is not allowed. It can be only called at the top level or inside another suite function.");
717
+ let mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
718
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
719
+ let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
720
+ if (mode === "run" && !factory) mode = "todo";
721
+ const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
722
+ const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
723
+ options = {
724
+ ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
725
+ ...options,
726
+ shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle)
727
+ };
728
+ const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
729
+ const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
730
+ options.concurrent = isConcurrent && !isSequential;
731
+ options.sequential = isSequential && !isConcurrent;
732
+ return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
733
+ }
734
+ suiteFn.each = function(cases, ...args) {
735
+ const suite$1 = this.withContext();
736
+ this.setContext("each", true);
737
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
738
+ return (name, optionsOrFn, fnOrOptions) => {
739
+ const _name = formatName(name);
740
+ const arrayOnlyCases = cases.every(Array.isArray);
741
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
742
+ const fnFirst = typeof optionsOrFn === "function";
743
+ cases.forEach((i, idx) => {
744
+ const items = Array.isArray(i) ? i : [i];
745
+ if (fnFirst) if (arrayOnlyCases) suite$1(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout);
746
+ else suite$1(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options.timeout);
747
+ else if (arrayOnlyCases) suite$1(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
748
+ else suite$1(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
749
+ });
750
+ this.setContext("each", void 0);
751
+ };
752
+ };
753
+ suiteFn.for = function(cases, ...args) {
754
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
755
+ return (name, optionsOrFn, fnOrOptions) => {
756
+ const name_ = formatName(name);
757
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
758
+ cases.forEach((item, idx) => {
759
+ suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
760
+ });
761
+ };
762
+ };
763
+ suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
764
+ suiteFn.runIf = (condition) => condition ? suite : suite.skip;
765
+ return createChainable([
766
+ "concurrent",
767
+ "sequential",
768
+ "shuffle",
769
+ "skip",
770
+ "only",
771
+ "todo"
772
+ ], suiteFn);
773
+ }
774
+ function createTaskCollector(fn, context) {
775
+ const taskFn = fn;
776
+ taskFn.each = function(cases, ...args) {
777
+ const test$1 = this.withContext();
778
+ this.setContext("each", true);
779
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
780
+ return (name, optionsOrFn, fnOrOptions) => {
781
+ const _name = formatName(name);
782
+ const arrayOnlyCases = cases.every(Array.isArray);
783
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
784
+ const fnFirst = typeof optionsOrFn === "function";
785
+ cases.forEach((i, idx) => {
786
+ const items = Array.isArray(i) ? i : [i];
787
+ if (fnFirst) if (arrayOnlyCases) test$1(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout);
788
+ else test$1(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options.timeout);
789
+ else if (arrayOnlyCases) test$1(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
790
+ else test$1(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
791
+ });
792
+ this.setContext("each", void 0);
793
+ };
794
+ };
795
+ taskFn.for = function(cases, ...args) {
796
+ const test$1 = this.withContext();
797
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
798
+ return (name, optionsOrFn, fnOrOptions) => {
799
+ const _name = formatName(name);
800
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
801
+ cases.forEach((item, idx) => {
802
+ const handlerWrapper = handler ? (ctx) => handler(item, ctx) : void 0;
803
+ if (handlerWrapper) {
804
+ handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
805
+ handlerWrapper.toString = () => handler.toString();
806
+ }
807
+ test$1(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
808
+ });
809
+ };
810
+ };
811
+ taskFn.skipIf = function(condition) {
812
+ return condition ? this.skip : this;
813
+ };
814
+ taskFn.runIf = function(condition) {
815
+ return condition ? this : this.skip;
816
+ };
817
+ taskFn.scoped = function(fixtures) {
818
+ getCurrentSuite().scoped(fixtures);
819
+ };
820
+ taskFn.extend = function(fixtures) {
821
+ const _context = mergeContextFixtures(fixtures, context || {}, runner);
822
+ const originalWrapper = fn;
823
+ return createTest(function(name, optionsOrFn, optionsOrTest) {
824
+ const scopedFixtures = getCurrentSuite().fixtures();
825
+ const context$1 = { ...this };
826
+ if (scopedFixtures) context$1.fixtures = mergeScopedFixtures(context$1.fixtures || [], scopedFixtures);
827
+ originalWrapper.call(context$1, formatName(name), optionsOrFn, optionsOrTest);
828
+ }, _context);
829
+ };
830
+ taskFn.beforeEach = beforeEach;
831
+ taskFn.afterEach = afterEach;
832
+ taskFn.beforeAll = beforeAll;
833
+ taskFn.afterAll = afterAll;
834
+ const _test$1 = createChainable([
835
+ "concurrent",
836
+ "sequential",
837
+ "skip",
838
+ "only",
839
+ "todo",
840
+ "fails"
841
+ ], taskFn);
842
+ if (context) _test$1.mergeContext(context);
843
+ return _test$1;
844
+ }
845
+ function createTest(fn, context) {
846
+ return createTaskCollector(fn, context);
847
+ }
848
+ function formatName(name) {
849
+ return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
850
+ }
851
+ function formatTitle(template, items, idx) {
852
+ if (template.includes("%#") || template.includes("%$")) template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
853
+ const count = template.split("%").length - 1;
854
+ if (template.includes("%f")) (template.match(/%f/g) || []).forEach((_, i$1) => {
855
+ if (isNegativeNaN(items[i$1]) || Object.is(items[i$1], -0)) {
856
+ let occurrence = 0;
857
+ template = template.replace(/%f/g, (match) => {
858
+ occurrence++;
859
+ return occurrence === i$1 + 1 ? "-%f" : match;
860
+ });
861
+ }
862
+ });
863
+ const isObjectItem = isObject(items[0]);
864
+ function formatAttribute(s) {
865
+ return s.replace(/\$([$\w.]+)/g, (_, key) => {
866
+ var _runner$config;
867
+ const isArrayKey = /^\d+$/.test(key);
868
+ if (!isObjectItem && !isArrayKey) return `$${key}`;
869
+ const arrayElement = isArrayKey ? objectAttr(items, key) : void 0;
870
+ return objDisplay(isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold });
871
+ });
872
+ }
873
+ let output = "";
874
+ let i = 0;
875
+ handleRegexMatch(template, formatRegExp, (match) => {
876
+ if (i < count) output += format(match[0], items[i++]);
877
+ else output += match[0];
878
+ }, (nonMatch) => {
879
+ output += formatAttribute(nonMatch);
880
+ });
881
+ return output;
882
+ }
883
+ function handleRegexMatch(input, regex, onMatch, onNonMatch) {
884
+ let lastIndex = 0;
885
+ for (const m of input.matchAll(regex)) {
886
+ if (lastIndex < m.index) onNonMatch(input.slice(lastIndex, m.index));
887
+ onMatch(m);
888
+ lastIndex = m.index + m[0].length;
889
+ }
890
+ if (lastIndex < input.length) onNonMatch(input.slice(lastIndex));
891
+ }
892
+ function formatTemplateString(cases, args) {
893
+ const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
894
+ const res = [];
895
+ for (let i = 0; i < Math.floor(args.length / header.length); i++) {
896
+ const oneCase = {};
897
+ for (let j = 0; j < header.length; j++) oneCase[header[j]] = args[i * header.length + j];
898
+ res.push(oneCase);
899
+ }
900
+ return res;
901
+ }
902
+ const now$2 = Date.now;
903
+ const collectorContext = {
904
+ tasks: [],
905
+ currentSuite: null
906
+ };
907
+ function collectTask(task) {
908
+ var _collectorContext$cur;
909
+ (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 || _collectorContext$cur.tasks.push(task);
910
+ }
911
+ async function runWithSuite(suite$1, fn) {
912
+ const prev = collectorContext.currentSuite;
913
+ collectorContext.currentSuite = suite$1;
914
+ await fn();
915
+ collectorContext.currentSuite = prev;
916
+ }
917
+ function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
918
+ if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) return fn;
919
+ const { setTimeout: setTimeout$1, clearTimeout: clearTimeout$1 } = getSafeTimers();
920
+ return (function runWithTimeout(...args) {
921
+ const startTime = now$2();
922
+ const runner$1 = getRunner();
923
+ runner$1._currentTaskStartTime = startTime;
924
+ runner$1._currentTaskTimeout = timeout;
925
+ return new Promise((resolve_, reject_) => {
926
+ var _timer$unref;
927
+ const timer = setTimeout$1(() => {
928
+ clearTimeout$1(timer);
929
+ rejectTimeoutError();
930
+ }, timeout);
931
+ (_timer$unref = timer.unref) === null || _timer$unref === void 0 || _timer$unref.call(timer);
932
+ function rejectTimeoutError() {
933
+ const error = makeTimeoutError(isHook, timeout, stackTraceError);
934
+ onTimeout === null || onTimeout === void 0 || onTimeout(args, error);
935
+ reject_(error);
936
+ }
937
+ function resolve(result) {
938
+ runner$1._currentTaskStartTime = void 0;
939
+ runner$1._currentTaskTimeout = void 0;
940
+ clearTimeout$1(timer);
941
+ if (now$2() - startTime >= timeout) {
942
+ rejectTimeoutError();
943
+ return;
944
+ }
945
+ resolve_(result);
946
+ }
947
+ function reject(error) {
948
+ runner$1._currentTaskStartTime = void 0;
949
+ runner$1._currentTaskTimeout = void 0;
950
+ clearTimeout$1(timer);
951
+ reject_(error);
952
+ }
953
+ try {
954
+ const result = fn(...args);
955
+ if (typeof result === "object" && result != null && typeof result.then === "function") result.then(resolve, reject);
956
+ else resolve(result);
957
+ } catch (error) {
958
+ reject(error);
959
+ }
960
+ });
961
+ });
962
+ }
963
+ const abortControllers = /* @__PURE__ */ new WeakMap();
964
+ function abortIfTimeout([context], error) {
965
+ if (context) abortContextSignal(context, error);
966
+ }
967
+ function abortContextSignal(context, error) {
968
+ const abortController = abortControllers.get(context);
969
+ abortController === null || abortController === void 0 || abortController.abort(error);
970
+ }
971
+ function createTestContext(test$1, runner$1) {
972
+ var _runner$extendTaskCon;
973
+ const context = function() {
974
+ throw new Error("done() callback is deprecated, use promise instead");
975
+ };
976
+ let abortController = abortControllers.get(context);
977
+ if (!abortController) {
978
+ abortController = new AbortController();
979
+ abortControllers.set(context, abortController);
980
+ }
981
+ context.signal = abortController.signal;
982
+ context.task = test$1;
983
+ context.skip = (condition, note) => {
984
+ if (condition === false) return;
985
+ test$1.result ?? (test$1.result = { state: "skip" });
986
+ test$1.result.pending = true;
987
+ throw new PendingError("test is skipped; abort execution", test$1, typeof condition === "string" ? condition : note);
988
+ };
989
+ context.annotate = ((message, type, attachment) => {
990
+ if (test$1.result && test$1.result.state !== "run") throw new Error(`Cannot annotate tests outside of the test run. The test "${test$1.name}" finished running with the "${test$1.result.state}" state already.`);
991
+ const annotation = {
992
+ message,
993
+ type: typeof type === "object" || type === void 0 ? "notice" : type
994
+ };
995
+ const annotationAttachment = typeof type === "object" ? type : attachment;
996
+ if (annotationAttachment) {
997
+ annotation.attachment = annotationAttachment;
998
+ manageArtifactAttachment(annotation.attachment);
999
+ }
1000
+ return recordAsyncOperation(test$1, recordArtifact(test$1, {
1001
+ type: "internal:annotation",
1002
+ annotation
1003
+ }).then(async ({ annotation: annotation$1 }) => {
1004
+ if (!runner$1.onTestAnnotate) throw new Error(`Test runner doesn't support test annotations.`);
1005
+ await finishSendTasksUpdate(runner$1);
1006
+ const resolvedAnnotation = await runner$1.onTestAnnotate(test$1, annotation$1);
1007
+ test$1.annotations.push(resolvedAnnotation);
1008
+ return resolvedAnnotation;
1009
+ }));
1010
+ });
1011
+ context.onTestFailed = (handler, timeout) => {
1012
+ test$1.onFailed || (test$1.onFailed = []);
1013
+ test$1.onFailed.push(withTimeout(handler, timeout ?? runner$1.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1014
+ };
1015
+ context.onTestFinished = (handler, timeout) => {
1016
+ test$1.onFinished || (test$1.onFinished = []);
1017
+ test$1.onFinished.push(withTimeout(handler, timeout ?? runner$1.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1018
+ };
1019
+ return ((_runner$extendTaskCon = runner$1.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner$1, context)) || context;
1020
+ }
1021
+ function makeTimeoutError(isHook, timeout, stackTraceError) {
1022
+ const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
1023
+ const error = new Error(message);
1024
+ if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
1025
+ return error;
1026
+ }
1027
+ const fileContexts = /* @__PURE__ */ new WeakMap();
1028
+ function getFileContext(file) {
1029
+ const context = fileContexts.get(file);
1030
+ if (!context) throw new Error(`Cannot find file context for ${file.name}`);
1031
+ return context;
1032
+ }
1033
+ const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1034
+ const now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1035
+ const unixNow = Date.now;
1036
+ const { clearTimeout, setTimeout } = getSafeTimers();
1037
+ const packs = /* @__PURE__ */ new Map();
1038
+ const eventsPacks = [];
1039
+ const pendingTasksUpdates = [];
1040
+ function sendTasksUpdate(runner$1) {
1041
+ if (packs.size) {
1042
+ var _runner$onTaskUpdate;
1043
+ const taskPacks = Array.from(packs).map(([id, task]) => {
1044
+ return [
1045
+ id,
1046
+ task[0],
1047
+ task[1]
1048
+ ];
1049
+ });
1050
+ const p = (_runner$onTaskUpdate = runner$1.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner$1, taskPacks, eventsPacks);
1051
+ if (p) {
1052
+ pendingTasksUpdates.push(p);
1053
+ p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
1054
+ }
1055
+ eventsPacks.length = 0;
1056
+ packs.clear();
1057
+ }
1058
+ }
1059
+ async function finishSendTasksUpdate(runner$1) {
1060
+ sendTasksUpdate(runner$1);
1061
+ await Promise.all(pendingTasksUpdates);
1062
+ }
1063
+ function throttle(fn, ms) {
1064
+ let last = 0;
1065
+ let pendingCall;
1066
+ return function call(...args) {
1067
+ const now$3 = unixNow();
1068
+ if (now$3 - last > ms) {
1069
+ last = now$3;
1070
+ clearTimeout(pendingCall);
1071
+ pendingCall = void 0;
1072
+ return fn.apply(this, args);
1073
+ }
1074
+ pendingCall ?? (pendingCall = setTimeout(() => call.bind(this)(...args), ms));
1075
+ };
1076
+ }
1077
+ const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
1078
+ /**
1079
+ * @experimental
1080
+ * @advanced
1081
+ *
1082
+ * Records a custom test artifact during test execution.
1083
+ *
1084
+ * This function allows you to attach structured data, files, or metadata to a test.
1085
+ *
1086
+ * Vitest automatically injects the source location where the artifact was created and manages any attachments you include.
1087
+ *
1088
+ * @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests
1089
+ * @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase}
1090
+ *
1091
+ * @returns A promise that resolves to the recorded artifact with location injected
1092
+ *
1093
+ * @throws {Error} If called after the test has finished running
1094
+ * @throws {Error} If the test runner doesn't support artifacts
1095
+ *
1096
+ * @example
1097
+ * ```ts
1098
+ * // In a custom assertion
1099
+ * async function toHaveValidSchema(this: MatcherState, actual: unknown) {
1100
+ * const validation = validateSchema(actual)
1101
+ *
1102
+ * await recordArtifact(this.task, {
1103
+ * type: 'my-plugin:schema-validation',
1104
+ * passed: validation.valid,
1105
+ * errors: validation.errors,
1106
+ * })
1107
+ *
1108
+ * return { pass: validation.valid, message: () => '...' }
1109
+ * }
1110
+ * ```
1111
+ */
1112
+ async function recordArtifact(task, artifact) {
1113
+ const runner$1 = getRunner();
1114
+ if (task.result && task.result.state !== "run") throw new Error(`Cannot record a test artifact outside of the test run. The test "${task.name}" finished running with the "${task.result.state}" state already.`);
1115
+ const stack = findTestFileStackTrace(task.file.filepath, (/* @__PURE__ */ new Error("STACK_TRACE")).stack);
1116
+ if (stack) {
1117
+ artifact.location = {
1118
+ file: stack.file,
1119
+ line: stack.line,
1120
+ column: stack.column
1121
+ };
1122
+ if (artifact.type === "internal:annotation") artifact.annotation.location = artifact.location;
1123
+ }
1124
+ if (Array.isArray(artifact.attachments)) for (const attachment of artifact.attachments) manageArtifactAttachment(attachment);
1125
+ if (artifact.type === "internal:annotation") return artifact;
1126
+ if (!runner$1.onTestArtifactRecord) throw new Error(`Test runner doesn't support test artifacts.`);
1127
+ await finishSendTasksUpdate(runner$1);
1128
+ const resolvedArtifact = await runner$1.onTestArtifactRecord(task, artifact);
1129
+ task.artifacts.push(resolvedArtifact);
1130
+ return resolvedArtifact;
1131
+ }
1132
+ const table = [];
1133
+ for (let i = 65; i < 91; i++) table.push(String.fromCharCode(i));
1134
+ for (let i = 97; i < 123; i++) table.push(String.fromCharCode(i));
1135
+ for (let i = 0; i < 10; i++) table.push(i.toString(10));
1136
+ table.push("+", "/");
1137
+ function encodeUint8Array(bytes) {
1138
+ let base64 = "";
1139
+ const len = bytes.byteLength;
1140
+ for (let i = 0; i < len; i += 3) if (len === i + 1) {
1141
+ const a = (bytes[i] & 252) >> 2;
1142
+ const b = (bytes[i] & 3) << 4;
1143
+ base64 += table[a];
1144
+ base64 += table[b];
1145
+ base64 += "==";
1146
+ } else if (len === i + 2) {
1147
+ const a = (bytes[i] & 252) >> 2;
1148
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1149
+ const c = (bytes[i + 1] & 15) << 2;
1150
+ base64 += table[a];
1151
+ base64 += table[b];
1152
+ base64 += table[c];
1153
+ base64 += "=";
1154
+ } else {
1155
+ const a = (bytes[i] & 252) >> 2;
1156
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1157
+ const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
1158
+ const d = bytes[i + 2] & 63;
1159
+ base64 += table[a];
1160
+ base64 += table[b];
1161
+ base64 += table[c];
1162
+ base64 += table[d];
1163
+ }
1164
+ return base64;
1165
+ }
1166
+ /**
1167
+ * Records an async operation associated with a test task.
1168
+ *
1169
+ * This function tracks promises that should be awaited before a test completes.
1170
+ * The promise is automatically removed from the test's promise list once it settles.
1171
+ */
1172
+ function recordAsyncOperation(test$1, promise) {
1173
+ promise = promise.finally(() => {
1174
+ if (!test$1.promises) return;
1175
+ const index = test$1.promises.indexOf(promise);
1176
+ if (index !== -1) test$1.promises.splice(index, 1);
1177
+ });
1178
+ if (!test$1.promises) test$1.promises = [];
1179
+ test$1.promises.push(promise);
1180
+ return promise;
1181
+ }
1182
+ /**
1183
+ * Validates and prepares a test attachment for serialization.
1184
+ *
1185
+ * This function ensures attachments have either `body` or `path` set (but not both), and converts `Uint8Array` bodies to base64-encoded strings for easier serialization.
1186
+ *
1187
+ * @param attachment - The attachment to validate and prepare
1188
+ *
1189
+ * @throws {TypeError} If neither `body` nor `path` is provided
1190
+ * @throws {TypeError} If both `body` and `path` are provided
1191
+ */
1192
+ function manageArtifactAttachment(attachment) {
1193
+ if (attachment.body == null && !attachment.path) throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`);
1194
+ if (attachment.body && attachment.path) throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
1195
+ if (attachment.body instanceof Uint8Array) attachment.body = encodeUint8Array(attachment.body);
1196
+ }
1197
+
1198
+ //#endregion
1199
+ export { afterAll, beforeAll, describe, getCurrentTest, it };