@antdv-next/x-sdk 0.0.1 → 0.0.3

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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/dist/_util/resolveMaybeRef.d.ts +2 -0
  3. package/dist/_util/resolveMaybeRef.js +7 -0
  4. package/dist/_util/types.js +0 -0
  5. package/dist/chat-providers/AbstractChatProvider.d.ts +2 -2
  6. package/dist/chat-providers/AbstractChatProvider.js +42 -0
  7. package/dist/chat-providers/DeepSeekChatProvider.d.ts +2 -2
  8. package/dist/chat-providers/DeepSeekChatProvider.js +59 -0
  9. package/dist/chat-providers/DefaultChatProvider.d.ts +2 -2
  10. package/dist/chat-providers/DefaultChatProvider.js +26 -0
  11. package/dist/chat-providers/OpenAIChatProvider.d.ts +2 -2
  12. package/dist/chat-providers/OpenAIChatProvider.js +49 -0
  13. package/dist/chat-providers/index.js +4 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +7 -3
  16. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/expect/index.js +1467 -0
  17. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/pretty-format/index.js +884 -0
  18. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/runner/chunk-artifact.js +1513 -0
  19. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/snapshot/index.js +661 -0
  20. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/spy/index.js +384 -0
  21. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/chunk-pathe.M-eThtNZ.js +80 -0
  22. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/diff.js +1304 -0
  23. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/display.js +556 -0
  24. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/error.js +27 -0
  25. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/helpers.js +179 -0
  26. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/offset.js +25 -0
  27. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/serialize.js +75 -0
  28. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/source-map.js +371 -0
  29. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/utils/timers.js +35 -0
  30. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/chunks/_commonjsHelpers.D26ty3Ew.js +4 -0
  31. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/chunks/rpc.MzXet3jl.js +50 -0
  32. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/chunks/test.CBQUpOM3.js +2645 -0
  33. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/chunks/utils.BX5Fg8C4.js +42 -0
  34. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/vendor/chai.js +2872 -0
  35. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/vendor/magic-string.js +1009 -0
  36. package/dist/node_modules/.pnpm/@voidzero-dev_vite-plus-test@0.1.14_@types_node@24.12.0_@voidzero-dev_vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/vendor/tinyrainbow.js +84 -0
  37. package/dist/x-chat/__tests__/index.test.d.ts +1 -0
  38. package/dist/x-chat/__tests__/index.test.js +258 -0
  39. package/dist/x-chat/index.d.ts +14 -23
  40. package/dist/x-chat/index.js +85 -67
  41. package/dist/x-chat/store.d.ts +2 -0
  42. package/dist/{store-C1diHqNH.js → x-chat/store.js} +15 -9
  43. package/dist/x-conversations/__tests__/index.test.d.ts +1 -0
  44. package/dist/x-conversations/__tests__/index.test.js +36 -0
  45. package/dist/x-conversations/index.d.ts +4 -4
  46. package/dist/x-conversations/index.js +37 -1
  47. package/dist/{x-conversations-BrKWhj5r.js → x-conversations/store.js} +2 -31
  48. package/dist/x-request/__tests__/index.test.d.ts +1 -0
  49. package/dist/x-request/__tests__/index.test.js +90 -0
  50. package/dist/x-request/index.d.ts +36 -11
  51. package/dist/x-request/index.js +246 -1
  52. package/dist/x-request/x-fetch.js +18 -0
  53. package/dist/x-stream/__tests__/index.test.d.ts +1 -0
  54. package/dist/x-stream/__tests__/index.test.js +62 -0
  55. package/dist/x-stream/index.js +16 -5
  56. package/package.json +2 -1
  57. package/dist/chat-providers-5x9Va7p5.js +0 -167
  58. package/dist/x-request-BSFGaKND.js +0 -234
@@ -0,0 +1,1513 @@
1
+ import { format, formatRegExp, objDisplay } from "../utils/display.js";
2
+ import { assertTypes, createDefer, filterOutComments, isNegativeNaN, isObject, objectAttr, ordinal, toArray, unique } from "../utils/helpers.js";
3
+ import { getSafeTimers } from "../utils/timers.js";
4
+ import { parseSingleStack } from "../utils/source-map.js";
5
+ //#region ../../node_modules/.pnpm/@voidzero-dev+vite-plus-test@0.1.14_@types+node@24.12.0_@voidzero-dev+vite-plus-core@0._0c620f79340a656256b2ffe23b3e6dd1/node_modules/@voidzero-dev/vite-plus-test/dist/@vitest/runner/chunk-artifact.js
6
+ var PendingError = class extends Error {
7
+ code = "VITEST_PENDING";
8
+ taskId;
9
+ constructor(message, task, note) {
10
+ super(message);
11
+ this.message = message;
12
+ this.note = note;
13
+ this.taskId = task.id;
14
+ }
15
+ };
16
+ var FixtureDependencyError = class extends Error {
17
+ name = "FixtureDependencyError";
18
+ };
19
+ var FixtureAccessError = class extends Error {
20
+ name = "FixtureAccessError";
21
+ };
22
+ var FixtureParseError = class extends Error {
23
+ name = "FixtureParseError";
24
+ };
25
+ var fnMap = /* @__PURE__ */ new WeakMap();
26
+ var testFixtureMap = /* @__PURE__ */ new WeakMap();
27
+ var hooksMap = /* @__PURE__ */ new WeakMap();
28
+ function setFn(key, fn) {
29
+ fnMap.set(key, fn);
30
+ }
31
+ function setTestFixture(key, fixture) {
32
+ testFixtureMap.set(key, fixture);
33
+ }
34
+ function getTestFixtures(key) {
35
+ return testFixtureMap.get(key);
36
+ }
37
+ function setHooks(key, hooks) {
38
+ hooksMap.set(key, hooks);
39
+ }
40
+ function getHooks(key) {
41
+ return hooksMap.get(key);
42
+ }
43
+ var FIXTURE_STACK_TRACE_KEY = Symbol.for("VITEST_FIXTURE_STACK_TRACE");
44
+ var TestFixtures = class TestFixtures {
45
+ _suiteContexts;
46
+ _overrides = /* @__PURE__ */ new WeakMap();
47
+ _registrations;
48
+ static _definitions = [];
49
+ static _builtinFixtures = [
50
+ "task",
51
+ "signal",
52
+ "onTestFailed",
53
+ "onTestFinished",
54
+ "skip",
55
+ "annotate"
56
+ ];
57
+ static _fixtureOptionKeys = [
58
+ "auto",
59
+ "injected",
60
+ "scope"
61
+ ];
62
+ static _fixtureScopes = [
63
+ "test",
64
+ "file",
65
+ "worker"
66
+ ];
67
+ static _workerContextSuite = { type: "worker" };
68
+ static clearDefinitions() {
69
+ TestFixtures._definitions.length = 0;
70
+ }
71
+ static getWorkerContexts() {
72
+ return TestFixtures._definitions.map((f) => f.getWorkerContext());
73
+ }
74
+ static getFileContexts(file) {
75
+ return TestFixtures._definitions.map((f) => f.getFileContext(file));
76
+ }
77
+ static isFixtureOptions(obj) {
78
+ return isObject(obj) && Object.keys(obj).some((key) => TestFixtures._fixtureOptionKeys.includes(key));
79
+ }
80
+ constructor(registrations) {
81
+ this._registrations = registrations ?? /* @__PURE__ */ new Map();
82
+ this._suiteContexts = /* @__PURE__ */ new WeakMap();
83
+ TestFixtures._definitions.push(this);
84
+ }
85
+ extend(runner, userFixtures) {
86
+ const { suite } = getCurrentSuite();
87
+ const isTopLevel = !suite || suite.file === suite;
88
+ const registrations = this.parseUserFixtures(runner, userFixtures, isTopLevel);
89
+ return new TestFixtures(registrations);
90
+ }
91
+ get(suite) {
92
+ let currentSuite = suite;
93
+ while (currentSuite) {
94
+ const overrides = this._overrides.get(currentSuite);
95
+ if (overrides) return overrides;
96
+ if (currentSuite === currentSuite.file) break;
97
+ currentSuite = currentSuite.suite || currentSuite.file;
98
+ }
99
+ return this._registrations;
100
+ }
101
+ override(runner, userFixtures) {
102
+ const { suite: currentSuite, file } = getCurrentSuite();
103
+ const suite = currentSuite || file;
104
+ const isTopLevel = !currentSuite || currentSuite.file === currentSuite;
105
+ const suiteRegistrations = new Map(this.get(suite));
106
+ const registrations = this.parseUserFixtures(runner, userFixtures, isTopLevel, suiteRegistrations);
107
+ if (isTopLevel) this._registrations = registrations;
108
+ else this._overrides.set(suite, registrations);
109
+ }
110
+ getFileContext(file) {
111
+ if (!this._suiteContexts.has(file)) this._suiteContexts.set(file, Object.create(null));
112
+ return this._suiteContexts.get(file);
113
+ }
114
+ getWorkerContext() {
115
+ if (!this._suiteContexts.has(TestFixtures._workerContextSuite)) this._suiteContexts.set(TestFixtures._workerContextSuite, Object.create(null));
116
+ return this._suiteContexts.get(TestFixtures._workerContextSuite);
117
+ }
118
+ parseUserFixtures(runner, userFixtures, supportNonTest, registrations = new Map(this._registrations)) {
119
+ const errors = [];
120
+ Object.entries(userFixtures).forEach(([name, fn]) => {
121
+ let options;
122
+ let value;
123
+ let _options;
124
+ if (Array.isArray(fn) && fn.length >= 2 && TestFixtures.isFixtureOptions(fn[1])) {
125
+ _options = fn[1];
126
+ options = {
127
+ auto: _options.auto ?? false,
128
+ scope: _options.scope ?? "test",
129
+ injected: _options.injected ?? false
130
+ };
131
+ value = options.injected ? runner.injectValue?.(name) ?? fn[0] : fn[0];
132
+ } else value = fn;
133
+ const parent = registrations.get(name);
134
+ if (parent && options) {
135
+ if (parent.scope !== options.scope) errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered with a "${options.scope}" scope.`));
136
+ if (parent.auto !== options.auto) errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered as { auto: ${options.auto} }.`));
137
+ } else if (parent) options = {
138
+ auto: parent.auto,
139
+ scope: parent.scope,
140
+ injected: parent.injected
141
+ };
142
+ else if (!options) options = {
143
+ auto: false,
144
+ injected: false,
145
+ scope: "test"
146
+ };
147
+ if (options.scope && !TestFixtures._fixtureScopes.includes(options.scope)) errors.push(new FixtureDependencyError(`The "${name}" fixture has unknown scope "${options.scope}".`));
148
+ if (!supportNonTest && options.scope !== "test") errors.push(new FixtureDependencyError(`The "${name}" fixture cannot be defined with a ${options.scope} scope${!_options?.scope && parent?.scope ? " (inherited from the base fixture)" : ""} inside the describe block. Define it at the top level of the file instead.`));
149
+ const deps = isFixtureFunction(value) ? getUsedProps(value) : /* @__PURE__ */ new Set();
150
+ const item = {
151
+ name,
152
+ value,
153
+ auto: options.auto ?? false,
154
+ injected: options.injected ?? false,
155
+ scope: options.scope ?? "test",
156
+ deps,
157
+ parent
158
+ };
159
+ if (isFixtureFunction(value)) Object.assign(value, { [FIXTURE_STACK_TRACE_KEY]: /* @__PURE__ */ new Error("STACK_TRACE_ERROR") });
160
+ registrations.set(name, item);
161
+ if (item.scope === "worker" && (runner.pool === "vmThreads" || runner.pool === "vmForks")) item.scope = "file";
162
+ });
163
+ for (const fixture of registrations.values()) for (const depName of fixture.deps) {
164
+ if (TestFixtures._builtinFixtures.includes(depName)) continue;
165
+ const dep = registrations.get(depName);
166
+ if (!dep) {
167
+ errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on unknown fixture "${depName}".`));
168
+ continue;
169
+ }
170
+ if (depName === fixture.name && !fixture.parent) {
171
+ errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on itself, but does not have a base implementation.`));
172
+ continue;
173
+ }
174
+ if (TestFixtures._fixtureScopes.indexOf(fixture.scope) > TestFixtures._fixtureScopes.indexOf(dep.scope)) {
175
+ errors.push(new FixtureDependencyError(`The ${fixture.scope} "${fixture.name}" fixture cannot depend on a ${dep.scope} fixture "${dep.name}".`));
176
+ continue;
177
+ }
178
+ }
179
+ if (errors.length === 1) throw errors[0];
180
+ else if (errors.length > 1) throw new AggregateError(errors, "Cannot resolve user fixtures. See errors for more information.");
181
+ return registrations;
182
+ }
183
+ };
184
+ var cleanupFnArrayMap = /* @__PURE__ */ new WeakMap();
185
+ var contextHasFixturesCache = /* @__PURE__ */ new WeakMap();
186
+ function withFixtures(fn, options) {
187
+ const collector = getCurrentSuite();
188
+ const suite = options?.suite || collector.suite || collector.file;
189
+ return async (hookContext) => {
190
+ const context = hookContext || options?.context;
191
+ if (!context) {
192
+ if (options?.suiteHook) validateSuiteHook(fn, options.suiteHook, options.stackTraceError);
193
+ return fn({});
194
+ }
195
+ const fixtures = options?.fixtures || getTestFixtures(context);
196
+ if (!fixtures) return fn(context);
197
+ const registrations = fixtures.get(suite);
198
+ if (!registrations.size) return fn(context);
199
+ const usedFixtures = [];
200
+ const usedProps = getUsedProps(fn);
201
+ for (const fixture of registrations.values()) if (fixture.auto || usedProps.has(fixture.name)) usedFixtures.push(fixture);
202
+ if (!usedFixtures.length) return fn(context);
203
+ if (!cleanupFnArrayMap.has(context)) cleanupFnArrayMap.set(context, []);
204
+ const cleanupFnArray = cleanupFnArrayMap.get(context);
205
+ const pendingFixtures = resolveDeps(usedFixtures, registrations);
206
+ if (!pendingFixtures.length) return fn(context);
207
+ if (options?.suiteHook) {
208
+ const testScopedFixtures = pendingFixtures.filter((f) => f.scope === "test");
209
+ if (testScopedFixtures.length > 0) {
210
+ const fixtureNames = testScopedFixtures.map((f) => `"${f.name}"`).join(", ");
211
+ const error = new FixtureDependencyError(`Test-scoped fixtures cannot be used inside ${options.suiteHook} hook. The following fixtures are test-scoped: ${fixtureNames}. Use { scope: 'file' } or { scope: 'worker' } fixtures instead, or move the logic to ${{
212
+ aroundAll: "aroundEach",
213
+ beforeAll: "beforeEach",
214
+ afterAll: "afterEach"
215
+ }[options.suiteHook]} hook.`);
216
+ if (options.stackTraceError?.stack) error.stack = error.message + options.stackTraceError.stack.replace(options.stackTraceError.message, "");
217
+ throw error;
218
+ }
219
+ }
220
+ if (!contextHasFixturesCache.has(context)) contextHasFixturesCache.set(context, /* @__PURE__ */ new WeakSet());
221
+ const cachedFixtures = contextHasFixturesCache.get(context);
222
+ for (const fixture of pendingFixtures) if (fixture.scope === "test") {
223
+ if (cachedFixtures.has(fixture)) continue;
224
+ cachedFixtures.add(fixture);
225
+ const resolvedValue = await resolveTestFixtureValue(fixture, context, cleanupFnArray);
226
+ context[fixture.name] = resolvedValue;
227
+ cleanupFnArray.push(() => {
228
+ cachedFixtures.delete(fixture);
229
+ });
230
+ } else {
231
+ const resolvedValue = await resolveScopeFixtureValue(fixtures, suite, fixture);
232
+ context[fixture.name] = resolvedValue;
233
+ }
234
+ return fn(context);
235
+ };
236
+ }
237
+ function isFixtureFunction(value) {
238
+ return typeof value === "function";
239
+ }
240
+ function resolveTestFixtureValue(fixture, context, cleanupFnArray) {
241
+ if (!isFixtureFunction(fixture.value)) return fixture.value;
242
+ return resolveFixtureFunction(fixture.value, fixture.name, context, cleanupFnArray);
243
+ }
244
+ var scopedFixturePromiseCache = /* @__PURE__ */ new WeakMap();
245
+ async function resolveScopeFixtureValue(fixtures, suite, fixture) {
246
+ const workerContext = fixtures.getWorkerContext();
247
+ const fileContext = fixtures.getFileContext(suite.file);
248
+ const fixtureContext = fixture.scope === "worker" ? workerContext : fileContext;
249
+ if (!isFixtureFunction(fixture.value)) {
250
+ fixtureContext[fixture.name] = fixture.value;
251
+ return fixture.value;
252
+ }
253
+ if (fixture.name in fixtureContext) return fixtureContext[fixture.name];
254
+ if (scopedFixturePromiseCache.has(fixture)) return scopedFixturePromiseCache.get(fixture);
255
+ if (!cleanupFnArrayMap.has(fixtureContext)) cleanupFnArrayMap.set(fixtureContext, []);
256
+ const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
257
+ const promise = resolveFixtureFunction(fixture.value, fixture.name, fixture.scope === "file" ? {
258
+ ...workerContext,
259
+ ...fileContext
260
+ } : fixtureContext, cleanupFnFileArray).then((value) => {
261
+ fixtureContext[fixture.name] = value;
262
+ scopedFixturePromiseCache.delete(fixture);
263
+ return value;
264
+ });
265
+ scopedFixturePromiseCache.set(fixture, promise);
266
+ return promise;
267
+ }
268
+ async function resolveFixtureFunction(fixtureFn, fixtureName, context, cleanupFnArray) {
269
+ const useFnArgPromise = createDefer();
270
+ const stackTraceError = FIXTURE_STACK_TRACE_KEY in fixtureFn && fixtureFn[FIXTURE_STACK_TRACE_KEY] instanceof Error ? fixtureFn[FIXTURE_STACK_TRACE_KEY] : void 0;
271
+ let isUseFnArgResolved = false;
272
+ const fixtureReturn = fixtureFn(context, async (useFnArg) => {
273
+ isUseFnArgResolved = true;
274
+ useFnArgPromise.resolve(useFnArg);
275
+ const useReturnPromise = createDefer();
276
+ cleanupFnArray.push(async () => {
277
+ useReturnPromise.resolve();
278
+ await fixtureReturn;
279
+ });
280
+ await useReturnPromise;
281
+ }).then(() => {
282
+ if (!isUseFnArgResolved) {
283
+ const error = /* @__PURE__ */ new Error(`Fixture "${fixtureName}" returned without calling "use". Make sure to call "use" in every code path of the fixture function.`);
284
+ if (stackTraceError?.stack) error.stack = error.message + stackTraceError.stack.replace(stackTraceError.message, "");
285
+ useFnArgPromise.reject(error);
286
+ }
287
+ }).catch((e) => {
288
+ if (!isUseFnArgResolved) {
289
+ useFnArgPromise.reject(e);
290
+ return;
291
+ }
292
+ throw e;
293
+ });
294
+ return useFnArgPromise;
295
+ }
296
+ function resolveDeps(usedFixtures, registrations, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
297
+ usedFixtures.forEach((fixture) => {
298
+ if (pendingFixtures.includes(fixture)) return;
299
+ if (!isFixtureFunction(fixture.value) || !fixture.deps) {
300
+ pendingFixtures.push(fixture);
301
+ return;
302
+ }
303
+ if (depSet.has(fixture)) if (fixture.parent) fixture = fixture.parent;
304
+ else throw new Error(`Circular fixture dependency detected: ${fixture.name} <- ${[...depSet].reverse().map((d) => d.name).join(" <- ")}`);
305
+ depSet.add(fixture);
306
+ resolveDeps([...fixture.deps].map((n) => n === fixture.name ? fixture.parent : registrations.get(n)).filter((n) => !!n), registrations, depSet, pendingFixtures);
307
+ pendingFixtures.push(fixture);
308
+ depSet.clear();
309
+ });
310
+ return pendingFixtures;
311
+ }
312
+ function validateSuiteHook(fn, hook, suiteError) {
313
+ const usedProps = getUsedProps(fn, {
314
+ sourceError: suiteError,
315
+ suiteHook: hook
316
+ });
317
+ if (usedProps.size) {
318
+ const error = new FixtureAccessError(`The ${hook} hook uses fixtures "${[...usedProps].join("\", \"")}", but has no access to context. Did you forget to call it as "test.${hook}()" instead of "${hook}()"?\nIf you used internal "suite" task as the first argument previously, access it in the second argument instead. See https://vitest.dev/guide/test-context#suite-level-hooks`);
319
+ if (suiteError) error.stack = suiteError.stack?.replace(suiteError.message, error.message);
320
+ throw error;
321
+ }
322
+ }
323
+ var kPropsSymbol = Symbol("$vitest:fixture-props");
324
+ var kPropNamesSymbol = Symbol("$vitest:fixture-prop-names");
325
+ function configureProps(fn, options) {
326
+ Object.defineProperty(fn, kPropsSymbol, {
327
+ value: options,
328
+ enumerable: false
329
+ });
330
+ }
331
+ function memoProps(fn, props) {
332
+ fn[kPropNamesSymbol] = props;
333
+ return props;
334
+ }
335
+ function getUsedProps(fn, { sourceError, suiteHook } = {}) {
336
+ if (kPropNamesSymbol in fn) return fn[kPropNamesSymbol];
337
+ const { index: fixturesIndex = 0, original: implementation = fn } = kPropsSymbol in fn ? fn[kPropsSymbol] : {};
338
+ let fnString = filterOutComments(implementation.toString());
339
+ if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) fnString = fnString.split(/__async\((?:this|null),/)[1];
340
+ const match = fnString.match(/[^(]*\(([^)]*)/);
341
+ if (!match) return memoProps(fn, /* @__PURE__ */ new Set());
342
+ const args = splitByComma(match[1]);
343
+ if (!args.length) return memoProps(fn, /* @__PURE__ */ new Set());
344
+ const fixturesArgument = args[fixturesIndex];
345
+ if (!fixturesArgument) return memoProps(fn, /* @__PURE__ */ new Set());
346
+ if (!(fixturesArgument[0] === "{" && fixturesArgument.endsWith("}"))) {
347
+ const ordinalArgument = ordinal(fixturesIndex + 1);
348
+ const error = new FixtureParseError(`The ${ordinalArgument} argument inside a fixture must use object destructuring pattern, e.g. ({ task } => {}). Instead, received "${fixturesArgument}".${suiteHook ? ` If you used internal "suite" task as the ${ordinalArgument} argument previously, access it in the ${ordinal(fixturesIndex + 2)} argument instead.` : ""}`);
349
+ if (sourceError) error.stack = sourceError.stack?.replace(sourceError.message, error.message);
350
+ throw error;
351
+ }
352
+ const props = splitByComma(fixturesArgument.slice(1, -1).replace(/\s/g, "")).map((prop) => {
353
+ return prop.replace(/:.*|=.*/g, "");
354
+ });
355
+ const last = props.at(-1);
356
+ if (last && last.startsWith("...")) {
357
+ const error = new FixtureParseError(`Rest parameters are not supported in fixtures, received "${last}".`);
358
+ if (sourceError) error.stack = sourceError.stack?.replace(sourceError.message, error.message);
359
+ throw error;
360
+ }
361
+ return memoProps(fn, new Set(props));
362
+ }
363
+ function splitByComma(s) {
364
+ const result = [];
365
+ const stack = [];
366
+ let start = 0;
367
+ for (let i = 0; i < s.length; i++) if (s[i] === "{" || s[i] === "[") stack.push(s[i] === "{" ? "}" : "]");
368
+ else if (s[i] === stack.at(-1)) stack.pop();
369
+ else if (!stack.length && s[i] === ",") {
370
+ const token = s.substring(start, i).trim();
371
+ if (token) result.push(token);
372
+ start = i + 1;
373
+ }
374
+ const lastToken = s.substring(start).trim();
375
+ if (lastToken) result.push(lastToken);
376
+ return result;
377
+ }
378
+ var _test;
379
+ function getCurrentTest() {
380
+ return _test;
381
+ }
382
+ var kChainableContext = Symbol("kChainableContext");
383
+ function getChainableContext(chainable) {
384
+ return chainable?.[kChainableContext];
385
+ }
386
+ function createChainable(keys, fn, context) {
387
+ function create(context) {
388
+ const chain = function(...args) {
389
+ return fn.apply(context, args);
390
+ };
391
+ Object.assign(chain, fn);
392
+ Object.defineProperty(chain, kChainableContext, {
393
+ value: {
394
+ withContext: () => chain.bind(context),
395
+ getFixtures: () => context.fixtures,
396
+ setContext: (key, value) => {
397
+ context[key] = value;
398
+ },
399
+ mergeContext: (ctx) => {
400
+ Object.assign(context, ctx);
401
+ }
402
+ },
403
+ enumerable: false
404
+ });
405
+ for (const key of keys) Object.defineProperty(chain, key, { get() {
406
+ return create({
407
+ ...context,
408
+ [key]: true
409
+ });
410
+ } });
411
+ return chain;
412
+ }
413
+ const chain = create(context ?? {});
414
+ Object.defineProperty(chain, "fn", {
415
+ value: fn,
416
+ enumerable: false
417
+ });
418
+ return chain;
419
+ }
420
+ function getDefaultHookTimeout() {
421
+ return getRunner().config.hookTimeout;
422
+ }
423
+ var CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
424
+ var CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
425
+ var AROUND_TIMEOUT_KEY = Symbol.for("VITEST_AROUND_TIMEOUT");
426
+ var AROUND_STACK_TRACE_KEY = Symbol.for("VITEST_AROUND_STACK_TRACE");
427
+ /**
428
+ * Registers a callback function to be executed once before all tests within the current suite.
429
+ * 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.
430
+ *
431
+ * **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.
432
+ *
433
+ * @param {Function} fn - The callback function to be executed before all tests.
434
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
435
+ * @returns {void}
436
+ * @example
437
+ * ```ts
438
+ * // Example of using beforeAll to set up a database connection
439
+ * beforeAll(async () => {
440
+ * await database.connect();
441
+ * });
442
+ * ```
443
+ */
444
+ function beforeAll(fn, timeout = getDefaultHookTimeout()) {
445
+ assertTypes(fn, "\"beforeAll\" callback", ["function"]);
446
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
447
+ const context = getChainableContext(this);
448
+ return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(withSuiteFixtures("beforeAll", fn, context, stackTraceError), timeout, true, stackTraceError), {
449
+ [CLEANUP_TIMEOUT_KEY]: timeout,
450
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
451
+ }));
452
+ }
453
+ /**
454
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
455
+ * 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.
456
+ *
457
+ * **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.
458
+ *
459
+ * @param {Function} fn - The callback function to be executed after all tests.
460
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
461
+ * @returns {void}
462
+ * @example
463
+ * ```ts
464
+ * // Example of using afterAll to close a database connection
465
+ * afterAll(async () => {
466
+ * await database.disconnect();
467
+ * });
468
+ * ```
469
+ */
470
+ function afterAll(fn, timeout) {
471
+ assertTypes(fn, "\"afterAll\" callback", ["function"]);
472
+ const context = getChainableContext(this);
473
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
474
+ return getCurrentSuite().on("afterAll", withTimeout(withSuiteFixtures("afterAll", fn, context, stackTraceError), timeout ?? getDefaultHookTimeout(), true, stackTraceError));
475
+ }
476
+ /**
477
+ * Registers a callback function to be executed before each test within the current suite.
478
+ * 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.
479
+ *
480
+ * **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.
481
+ *
482
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
483
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
484
+ * @returns {void}
485
+ * @example
486
+ * ```ts
487
+ * // Example of using beforeEach to reset a database state
488
+ * beforeEach(async () => {
489
+ * await database.reset();
490
+ * });
491
+ * ```
492
+ */
493
+ function beforeEach(fn, timeout = getDefaultHookTimeout()) {
494
+ assertTypes(fn, "\"beforeEach\" callback", ["function"]);
495
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
496
+ const wrapper = (context, suite) => {
497
+ return withFixtures(fn, { suite })(context);
498
+ };
499
+ return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
500
+ [CLEANUP_TIMEOUT_KEY]: timeout,
501
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
502
+ }));
503
+ }
504
+ /**
505
+ * Registers a callback function to be executed after each test within the current suite has completed.
506
+ * 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.
507
+ *
508
+ * **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.
509
+ *
510
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
511
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
512
+ * @returns {void}
513
+ * @example
514
+ * ```ts
515
+ * // Example of using afterEach to delete temporary files created during a test
516
+ * afterEach(async () => {
517
+ * await fileSystem.deleteTempFiles();
518
+ * });
519
+ * ```
520
+ */
521
+ function afterEach(fn, timeout) {
522
+ assertTypes(fn, "\"afterEach\" callback", ["function"]);
523
+ const wrapper = (context, suite) => {
524
+ return withFixtures(fn, { suite })(context);
525
+ };
526
+ return getCurrentSuite().on("afterEach", withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), abortIfTimeout));
527
+ }
528
+ /**
529
+ * Registers a callback function that wraps around all tests within the current suite.
530
+ * The callback receives a `runSuite` function that must be called to run the suite's tests.
531
+ * This hook is useful for scenarios where you need to wrap an entire suite in a context
532
+ * (e.g., starting a server, opening a database connection that all tests share).
533
+ *
534
+ * **Note:** When multiple `aroundAll` hooks are registered, they are nested inside each other.
535
+ * The first registered hook is the outermost wrapper.
536
+ *
537
+ * @param {Function} fn - The callback function that wraps the suite. Must call `runSuite()` to run the tests.
538
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
539
+ * @returns {void}
540
+ * @example
541
+ * ```ts
542
+ * // Example of using aroundAll to wrap suite in a tracing span
543
+ * aroundAll(async (runSuite) => {
544
+ * await tracer.trace('test-suite', runSuite);
545
+ * });
546
+ * ```
547
+ * @example
548
+ * ```ts
549
+ * // Example of using aroundAll with fixtures
550
+ * aroundAll(async (runSuite, { db }) => {
551
+ * await db.transaction(() => runSuite());
552
+ * });
553
+ * ```
554
+ */
555
+ function aroundAll(fn, timeout) {
556
+ assertTypes(fn, "\"aroundAll\" callback", ["function"]);
557
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
558
+ const resolvedTimeout = timeout ?? getDefaultHookTimeout();
559
+ const context = getChainableContext(this);
560
+ return getCurrentSuite().on("aroundAll", Object.assign(withSuiteFixtures("aroundAll", fn, context, stackTraceError, 1), {
561
+ [AROUND_TIMEOUT_KEY]: resolvedTimeout,
562
+ [AROUND_STACK_TRACE_KEY]: stackTraceError
563
+ }));
564
+ }
565
+ /**
566
+ * Registers a callback function that wraps around each test within the current suite.
567
+ * The callback receives a `runTest` function that must be called to run the test.
568
+ * This hook is useful for scenarios where you need to wrap tests in a context (e.g., database transactions).
569
+ *
570
+ * **Note:** When multiple `aroundEach` hooks are registered, they are nested inside each other.
571
+ * The first registered hook is the outermost wrapper.
572
+ *
573
+ * @param {Function} fn - The callback function that wraps the test. Must call `runTest()` to run the test.
574
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
575
+ * @returns {void}
576
+ * @example
577
+ * ```ts
578
+ * // Example of using aroundEach to wrap tests in a database transaction
579
+ * aroundEach(async (runTest) => {
580
+ * await database.transaction(() => runTest());
581
+ * });
582
+ * ```
583
+ * @example
584
+ * ```ts
585
+ * // Example of using aroundEach with fixtures
586
+ * aroundEach(async (runTest, { db }) => {
587
+ * await db.transaction(() => runTest());
588
+ * });
589
+ * ```
590
+ */
591
+ function aroundEach(fn, timeout) {
592
+ assertTypes(fn, "\"aroundEach\" callback", ["function"]);
593
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
594
+ const resolvedTimeout = timeout ?? getDefaultHookTimeout();
595
+ const wrapper = (runTest, context, suite) => {
596
+ const innerFn = (ctx) => fn(runTest, ctx, suite);
597
+ configureProps(innerFn, {
598
+ index: 1,
599
+ original: fn
600
+ });
601
+ return withFixtures(innerFn, { suite })(context);
602
+ };
603
+ return getCurrentSuite().on("aroundEach", Object.assign(wrapper, {
604
+ [AROUND_TIMEOUT_KEY]: resolvedTimeout,
605
+ [AROUND_STACK_TRACE_KEY]: stackTraceError
606
+ }));
607
+ }
608
+ function withSuiteFixtures(suiteHook, fn, context, stackTraceError, contextIndex = 0) {
609
+ return (...args) => {
610
+ const suite = args.at(-1);
611
+ const prefix = args.slice(0, -1);
612
+ const wrapper = (ctx) => fn(...prefix, ctx, suite);
613
+ configureProps(wrapper, {
614
+ index: contextIndex,
615
+ original: fn
616
+ });
617
+ const fixtures = context?.getFixtures();
618
+ const fileContext = fixtures?.getFileContext(suite.file);
619
+ return withFixtures(wrapper, {
620
+ suiteHook,
621
+ fixtures,
622
+ context: fileContext,
623
+ stackTraceError
624
+ })();
625
+ };
626
+ }
627
+ function findTestFileStackTrace(testFilePath, error) {
628
+ const lines = error.split("\n").slice(1);
629
+ for (const line of lines) {
630
+ const stack = parseSingleStack(line);
631
+ if (stack && stack.file === testFilePath) return stack;
632
+ }
633
+ }
634
+ function validateTags(config, tags) {
635
+ if (!config.strictTags) return;
636
+ const availableTags = new Set(config.tags.map((tag) => tag.name));
637
+ for (const tag of tags) if (!availableTags.has(tag)) throw createNoTagsError(config.tags, tag);
638
+ }
639
+ function createNoTagsError(availableTags, tag, prefix = "tag") {
640
+ if (!availableTags.length) throw new Error(`The Vitest config does't define any "tags", cannot apply "${tag}" ${prefix} for this test. See: https://vitest.dev/guide/test-tags`);
641
+ throw new Error(`The ${prefix} "${tag}" is not defined in the configuration. Available tags are:\n${availableTags.map((t) => `- ${t.name}${t.description ? `: ${t.description}` : ""}`).join("\n")}`);
642
+ }
643
+ function getNames(task) {
644
+ const names = [task.name];
645
+ let current = task;
646
+ while (current?.suite) {
647
+ current = current.suite;
648
+ if (current?.name) names.unshift(current.name);
649
+ }
650
+ if (current !== task.file) names.unshift(task.file.name);
651
+ return names;
652
+ }
653
+ function createTaskName(names, separator = " > ") {
654
+ return names.filter((name) => name !== void 0).join(separator);
655
+ }
656
+ /**
657
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
658
+ * Suites can contain both tests and other suites, enabling complex test structures.
659
+ *
660
+ * @param {string} name - The name of the suite, used for identification and reporting.
661
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
662
+ * @example
663
+ * ```ts
664
+ * // Define a suite with two tests
665
+ * suite('Math operations', () => {
666
+ * test('should add two numbers', () => {
667
+ * expect(add(1, 2)).toBe(3);
668
+ * });
669
+ *
670
+ * test('should subtract two numbers', () => {
671
+ * expect(subtract(5, 2)).toBe(3);
672
+ * });
673
+ * });
674
+ * ```
675
+ * @example
676
+ * ```ts
677
+ * // Define nested suites
678
+ * suite('String operations', () => {
679
+ * suite('Trimming', () => {
680
+ * test('should trim whitespace from start and end', () => {
681
+ * expect(' hello '.trim()).toBe('hello');
682
+ * });
683
+ * });
684
+ *
685
+ * suite('Concatenation', () => {
686
+ * test('should concatenate two strings', () => {
687
+ * expect('hello' + ' ' + 'world').toBe('hello world');
688
+ * });
689
+ * });
690
+ * });
691
+ * ```
692
+ */
693
+ var suite = createSuite();
694
+ /**
695
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
696
+ *
697
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
698
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
699
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
700
+ * @throws {Error} If called inside another test function.
701
+ * @example
702
+ * ```ts
703
+ * // Define a simple test
704
+ * test('should add two numbers', () => {
705
+ * expect(add(1, 2)).toBe(3);
706
+ * });
707
+ * ```
708
+ * @example
709
+ * ```ts
710
+ * // Define a test with options
711
+ * test('should subtract two numbers', { retry: 3 }, () => {
712
+ * expect(subtract(5, 2)).toBe(3);
713
+ * });
714
+ * ```
715
+ */
716
+ var test = createTest(function(name, optionsOrFn, optionsOrTest) {
717
+ 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.");
718
+ getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
719
+ });
720
+ /**
721
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
722
+ * Suites can contain both tests and other suites, enabling complex test structures.
723
+ *
724
+ * @param {string} name - The name of the suite, used for identification and reporting.
725
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
726
+ * @example
727
+ * ```ts
728
+ * // Define a suite with two tests
729
+ * describe('Math operations', () => {
730
+ * test('should add two numbers', () => {
731
+ * expect(add(1, 2)).toBe(3);
732
+ * });
733
+ *
734
+ * test('should subtract two numbers', () => {
735
+ * expect(subtract(5, 2)).toBe(3);
736
+ * });
737
+ * });
738
+ * ```
739
+ * @example
740
+ * ```ts
741
+ * // Define nested suites
742
+ * describe('String operations', () => {
743
+ * describe('Trimming', () => {
744
+ * test('should trim whitespace from start and end', () => {
745
+ * expect(' hello '.trim()).toBe('hello');
746
+ * });
747
+ * });
748
+ *
749
+ * describe('Concatenation', () => {
750
+ * test('should concatenate two strings', () => {
751
+ * expect('hello' + ' ' + 'world').toBe('hello world');
752
+ * });
753
+ * });
754
+ * });
755
+ * ```
756
+ */
757
+ var describe = suite;
758
+ /**
759
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
760
+ *
761
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
762
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
763
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
764
+ * @throws {Error} If called inside another test function.
765
+ * @example
766
+ * ```ts
767
+ * // Define a simple test
768
+ * it('adds two numbers', () => {
769
+ * expect(add(1, 2)).toBe(3);
770
+ * });
771
+ * ```
772
+ * @example
773
+ * ```ts
774
+ * // Define a test with options
775
+ * it('subtracts two numbers', { retry: 3 }, () => {
776
+ * expect(subtract(5, 2)).toBe(3);
777
+ * });
778
+ * ```
779
+ */
780
+ var it = test;
781
+ var runner;
782
+ var defaultSuite;
783
+ var currentTestFilepath;
784
+ function assert(condition, message) {
785
+ if (!condition) throw new Error(`Vitest failed to find ${message}. One of the following is possible:
786
+ - "vitest" is imported directly without running "vitest" command
787
+ - "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)
788
+ - "vitest" is imported inside Vite / Vitest config file
789
+ - Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues
790
+ `);
791
+ }
792
+ function getRunner() {
793
+ assert(runner, "the runner");
794
+ return runner;
795
+ }
796
+ function getCurrentSuite() {
797
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
798
+ assert(currentSuite, "the current suite");
799
+ return currentSuite;
800
+ }
801
+ function createSuiteHooks() {
802
+ return {
803
+ beforeAll: [],
804
+ afterAll: [],
805
+ beforeEach: [],
806
+ afterEach: [],
807
+ aroundEach: [],
808
+ aroundAll: []
809
+ };
810
+ }
811
+ var POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
812
+ function parseArguments(optionsOrFn, timeoutOrTest) {
813
+ 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.`);
814
+ let options = {};
815
+ let fn;
816
+ if (typeof timeoutOrTest === "number") options = { timeout: timeoutOrTest };
817
+ else if (typeof optionsOrFn === "object") options = optionsOrFn;
818
+ if (typeof optionsOrFn === "function") {
819
+ if (typeof timeoutOrTest === "function") throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
820
+ fn = optionsOrFn;
821
+ } else if (typeof timeoutOrTest === "function") fn = timeoutOrTest;
822
+ return {
823
+ options,
824
+ handler: fn
825
+ };
826
+ }
827
+ function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions) {
828
+ const tasks = [];
829
+ let suite;
830
+ initSuite(true);
831
+ const task = function(name = "", options = {}) {
832
+ const currentSuite = collectorContext.currentSuite?.suite;
833
+ const testTags = unique([...(currentSuite ?? collectorContext.currentSuite?.file)?.tags || [], ...toArray(options.tags)]);
834
+ const tagsOptions = testTags.map((tag) => {
835
+ const tagDefinition = runner.config.tags?.find((t) => t.name === tag);
836
+ if (!tagDefinition && runner.config.strictTags) throw createNoTagsError(runner.config.tags, tag);
837
+ return tagDefinition;
838
+ }).filter((r) => r != null).sort((tag1, tag2) => (tag2.priority ?? POSITIVE_INFINITY) - (tag1.priority ?? POSITIVE_INFINITY)).reduce((acc, tag) => {
839
+ const { name, description, priority, meta, ...options } = tag;
840
+ Object.assign(acc, options);
841
+ if (meta) acc.meta = Object.assign(acc.meta ?? Object.create(null), meta);
842
+ return acc;
843
+ }, {});
844
+ const testOwnMeta = options.meta;
845
+ options = {
846
+ ...tagsOptions,
847
+ ...options
848
+ };
849
+ const timeout = options.timeout ?? runner.config.testTimeout;
850
+ const parentMeta = currentSuite?.meta;
851
+ const tagMeta = tagsOptions.meta;
852
+ const testMeta = Object.create(null);
853
+ if (tagMeta) Object.assign(testMeta, tagMeta);
854
+ if (parentMeta) Object.assign(testMeta, parentMeta);
855
+ if (testOwnMeta) Object.assign(testMeta, testOwnMeta);
856
+ const task = {
857
+ id: "",
858
+ name,
859
+ fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name]),
860
+ fullTestName: createTaskName([currentSuite?.fullTestName, name]),
861
+ suite: currentSuite,
862
+ each: options.each,
863
+ fails: options.fails,
864
+ context: void 0,
865
+ type: "test",
866
+ file: currentSuite?.file ?? collectorContext.currentSuite?.file,
867
+ timeout,
868
+ retry: options.retry ?? runner.config.retry,
869
+ repeats: options.repeats,
870
+ mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
871
+ meta: testMeta,
872
+ annotations: [],
873
+ artifacts: [],
874
+ tags: testTags
875
+ };
876
+ const handler = options.handler;
877
+ if (task.mode === "run" && !handler) task.mode = "todo";
878
+ if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) task.concurrent = true;
879
+ task.shuffle = suiteOptions?.shuffle;
880
+ const context = createTestContext(task, runner);
881
+ Object.defineProperty(task, "context", {
882
+ value: context,
883
+ enumerable: false
884
+ });
885
+ setTestFixture(context, options.fixtures ?? new TestFixtures());
886
+ const limit = Error.stackTraceLimit;
887
+ Error.stackTraceLimit = 10;
888
+ const stackTraceError = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
889
+ Error.stackTraceLimit = limit;
890
+ if (handler) setFn(task, withTimeout(withCancel(withAwaitAsyncAssertions(withFixtures(handler, { context }), task), task.context.signal), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
891
+ if (runner.config.includeTaskLocation) {
892
+ const error = stackTraceError.stack;
893
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
894
+ if (stack) task.location = {
895
+ line: stack.line,
896
+ column: stack.column
897
+ };
898
+ }
899
+ tasks.push(task);
900
+ return task;
901
+ };
902
+ const test = createTest(function(name, optionsOrFn, timeoutOrTest) {
903
+ let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
904
+ if (typeof suiteOptions === "object") options = Object.assign({}, suiteOptions, options);
905
+ const concurrent = this.concurrent ?? (!this.sequential && options?.concurrent);
906
+ if (options.concurrent != null && concurrent != null) options.concurrent = concurrent;
907
+ const sequential = this.sequential ?? (!this.concurrent && options?.sequential);
908
+ if (options.sequential != null && sequential != null) options.sequential = sequential;
909
+ const test = task(formatName(name), {
910
+ ...this,
911
+ ...options,
912
+ handler
913
+ });
914
+ test.type = "test";
915
+ });
916
+ const collector = {
917
+ type: "collector",
918
+ name,
919
+ mode,
920
+ suite,
921
+ options: suiteOptions,
922
+ test,
923
+ file: suite.file,
924
+ tasks,
925
+ collect,
926
+ task,
927
+ clear,
928
+ on: addHook
929
+ };
930
+ function addHook(name, ...fn) {
931
+ getHooks(suite)[name].push(...fn);
932
+ }
933
+ function initSuite(includeLocation) {
934
+ if (typeof suiteOptions === "number") suiteOptions = { timeout: suiteOptions };
935
+ const currentSuite = collectorContext.currentSuite?.suite;
936
+ const parentTask = currentSuite ?? collectorContext.currentSuite?.file;
937
+ const suiteTags = toArray(suiteOptions?.tags);
938
+ validateTags(runner.config, suiteTags);
939
+ suite = {
940
+ id: "",
941
+ type: "suite",
942
+ name,
943
+ fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name]),
944
+ fullTestName: createTaskName([currentSuite?.fullTestName, name]),
945
+ suite: currentSuite,
946
+ mode,
947
+ each,
948
+ file: currentSuite?.file ?? collectorContext.currentSuite?.file,
949
+ shuffle: suiteOptions?.shuffle,
950
+ tasks: [],
951
+ meta: suiteOptions?.meta ?? Object.create(null),
952
+ concurrent: suiteOptions?.concurrent,
953
+ tags: unique([...parentTask?.tags || [], ...suiteTags])
954
+ };
955
+ if (runner && includeLocation && runner.config.includeTaskLocation) {
956
+ const limit = Error.stackTraceLimit;
957
+ Error.stackTraceLimit = 15;
958
+ const error = (/* @__PURE__ */ new Error("stacktrace")).stack;
959
+ Error.stackTraceLimit = limit;
960
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
961
+ if (stack) suite.location = {
962
+ line: stack.line,
963
+ column: stack.column
964
+ };
965
+ }
966
+ setHooks(suite, createSuiteHooks());
967
+ }
968
+ function clear() {
969
+ tasks.length = 0;
970
+ initSuite(false);
971
+ }
972
+ async function collect(file) {
973
+ if (!file) throw new TypeError("File is required to collect tasks.");
974
+ if (factory) await runWithSuite(collector, () => factory(test));
975
+ const allChildren = [];
976
+ for (const i of tasks) allChildren.push(i.type === "collector" ? await i.collect(file) : i);
977
+ suite.tasks = allChildren;
978
+ return suite;
979
+ }
980
+ collectTask(collector);
981
+ return collector;
982
+ }
983
+ function withAwaitAsyncAssertions(fn, task) {
984
+ return (async (...args) => {
985
+ const fnResult = await fn(...args);
986
+ if (task.promises) {
987
+ const errors = (await Promise.allSettled(task.promises)).map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
988
+ if (errors.length) throw errors;
989
+ }
990
+ return fnResult;
991
+ });
992
+ }
993
+ function createSuite() {
994
+ function suiteFn(name, factoryOrOptions, optionsOrFactory) {
995
+ 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.");
996
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
997
+ let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
998
+ const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
999
+ const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
1000
+ const { meta: parentMeta, ...parentOptions } = currentSuite?.options || {};
1001
+ options = {
1002
+ ...parentOptions,
1003
+ ...options
1004
+ };
1005
+ const shuffle = this.shuffle ?? options.shuffle ?? currentSuite?.options?.shuffle ?? runner?.config.sequence.shuffle;
1006
+ if (shuffle != null) options.shuffle = shuffle;
1007
+ let mode = this.only ?? options.only ? "only" : this.skip ?? options.skip ? "skip" : this.todo ?? options.todo ? "todo" : "run";
1008
+ if (mode === "run" && !factory) mode = "todo";
1009
+ const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
1010
+ const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
1011
+ if (isConcurrent != null) options.concurrent = isConcurrent && !isSequential;
1012
+ if (isSequential != null) options.sequential = isSequential && !isConcurrent;
1013
+ if (parentMeta) options.meta = Object.assign(Object.create(null), parentMeta, options.meta);
1014
+ return createSuiteCollector(formatName(name), factory, mode, this.each, options);
1015
+ }
1016
+ suiteFn.each = function(cases, ...args) {
1017
+ const context = getChainableContext(this);
1018
+ const suite = context.withContext();
1019
+ context.setContext("each", true);
1020
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
1021
+ return (name, optionsOrFn, fnOrOptions) => {
1022
+ const _name = formatName(name);
1023
+ const arrayOnlyCases = cases.every(Array.isArray);
1024
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
1025
+ const fnFirst = typeof optionsOrFn === "function";
1026
+ cases.forEach((i, idx) => {
1027
+ const items = Array.isArray(i) ? i : [i];
1028
+ if (fnFirst) if (arrayOnlyCases) suite(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout);
1029
+ else suite(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options.timeout);
1030
+ else if (arrayOnlyCases) suite(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
1031
+ else suite(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
1032
+ });
1033
+ context.setContext("each", void 0);
1034
+ };
1035
+ };
1036
+ suiteFn.for = function(cases, ...args) {
1037
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
1038
+ return (name, optionsOrFn, fnOrOptions) => {
1039
+ const name_ = formatName(name);
1040
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
1041
+ cases.forEach((item, idx) => {
1042
+ suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
1043
+ });
1044
+ };
1045
+ };
1046
+ suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
1047
+ suiteFn.runIf = (condition) => condition ? suite : suite.skip;
1048
+ return createChainable([
1049
+ "concurrent",
1050
+ "sequential",
1051
+ "shuffle",
1052
+ "skip",
1053
+ "only",
1054
+ "todo"
1055
+ ], suiteFn);
1056
+ }
1057
+ function createTaskCollector(fn) {
1058
+ const taskFn = fn;
1059
+ taskFn.each = function(cases, ...args) {
1060
+ const context = getChainableContext(this);
1061
+ const test = context.withContext();
1062
+ context.setContext("each", true);
1063
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
1064
+ return (name, optionsOrFn, fnOrOptions) => {
1065
+ const _name = formatName(name);
1066
+ const arrayOnlyCases = cases.every(Array.isArray);
1067
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
1068
+ const fnFirst = typeof optionsOrFn === "function";
1069
+ cases.forEach((i, idx) => {
1070
+ const items = Array.isArray(i) ? i : [i];
1071
+ if (fnFirst) if (arrayOnlyCases) test(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout);
1072
+ else test(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options.timeout);
1073
+ else if (arrayOnlyCases) test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
1074
+ else test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
1075
+ });
1076
+ context.setContext("each", void 0);
1077
+ };
1078
+ };
1079
+ taskFn.for = function(cases, ...args) {
1080
+ const test = getChainableContext(this).withContext();
1081
+ if (Array.isArray(cases) && args.length) cases = formatTemplateString(cases, args);
1082
+ return (name, optionsOrFn, fnOrOptions) => {
1083
+ const _name = formatName(name);
1084
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
1085
+ cases.forEach((item, idx) => {
1086
+ const handlerWrapper = handler ? (ctx) => handler(item, ctx) : void 0;
1087
+ if (handlerWrapper) configureProps(handlerWrapper, {
1088
+ index: 1,
1089
+ original: handler
1090
+ });
1091
+ test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
1092
+ });
1093
+ };
1094
+ };
1095
+ taskFn.skipIf = function(condition) {
1096
+ return condition ? this.skip : this;
1097
+ };
1098
+ taskFn.runIf = function(condition) {
1099
+ return condition ? this : this.skip;
1100
+ };
1101
+ /**
1102
+ * Parse builder pattern arguments into a fixtures object.
1103
+ * Handles both builder pattern (name, options?, value) and object syntax.
1104
+ */
1105
+ function parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn) {
1106
+ if (typeof fixturesOrName !== "string") return fixturesOrName;
1107
+ const fixtureName = fixturesOrName;
1108
+ let fixtureOptions;
1109
+ let fixtureValue;
1110
+ if (maybeFn !== void 0) {
1111
+ fixtureOptions = optionsOrFn;
1112
+ fixtureValue = maybeFn;
1113
+ } else if (optionsOrFn !== null && typeof optionsOrFn === "object" && !Array.isArray(optionsOrFn) && TestFixtures.isFixtureOptions(optionsOrFn)) {
1114
+ fixtureOptions = optionsOrFn;
1115
+ fixtureValue = {};
1116
+ } else {
1117
+ fixtureOptions = void 0;
1118
+ fixtureValue = optionsOrFn;
1119
+ }
1120
+ if (typeof fixtureValue === "function") {
1121
+ const builderFn = fixtureValue;
1122
+ const fixture = async (ctx, use) => {
1123
+ let cleanup;
1124
+ const onCleanup = (fn) => {
1125
+ if (cleanup !== void 0) throw new Error("onCleanup can only be called once per fixture. Define separate fixtures if you need multiple cleanup functions.");
1126
+ cleanup = fn;
1127
+ };
1128
+ await use(await builderFn(ctx, { onCleanup }));
1129
+ if (cleanup) await cleanup();
1130
+ };
1131
+ configureProps(fixture, { original: builderFn });
1132
+ if (fixtureOptions) return { [fixtureName]: [fixture, fixtureOptions] };
1133
+ return { [fixtureName]: fixture };
1134
+ }
1135
+ if (fixtureOptions) return { [fixtureName]: [fixtureValue, fixtureOptions] };
1136
+ return { [fixtureName]: fixtureValue };
1137
+ }
1138
+ taskFn.override = function(fixturesOrName, optionsOrFn, maybeFn) {
1139
+ const userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn);
1140
+ getChainableContext(this).getFixtures().override(runner, userFixtures);
1141
+ return this;
1142
+ };
1143
+ taskFn.scoped = function(fixtures) {
1144
+ console.warn(`test.scoped() is deprecated and will be removed in future versions. Please use test.override() instead.`);
1145
+ return this.override(fixtures);
1146
+ };
1147
+ taskFn.extend = function(fixturesOrName, optionsOrFn, maybeFn) {
1148
+ const userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn);
1149
+ const fixtures = getChainableContext(this).getFixtures().extend(runner, userFixtures);
1150
+ const _test = createTest(function(name, optionsOrFn, optionsOrTest) {
1151
+ fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
1152
+ });
1153
+ getChainableContext(_test).mergeContext({ fixtures });
1154
+ return _test;
1155
+ };
1156
+ taskFn.describe = suite;
1157
+ taskFn.suite = suite;
1158
+ taskFn.beforeEach = beforeEach;
1159
+ taskFn.afterEach = afterEach;
1160
+ taskFn.beforeAll = beforeAll;
1161
+ taskFn.afterAll = afterAll;
1162
+ taskFn.aroundEach = aroundEach;
1163
+ taskFn.aroundAll = aroundAll;
1164
+ return createChainable([
1165
+ "concurrent",
1166
+ "sequential",
1167
+ "skip",
1168
+ "only",
1169
+ "todo",
1170
+ "fails"
1171
+ ], taskFn, { fixtures: new TestFixtures() });
1172
+ }
1173
+ function createTest(fn) {
1174
+ return createTaskCollector(fn);
1175
+ }
1176
+ function formatName(name) {
1177
+ return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
1178
+ }
1179
+ function formatTitle(template, items, idx) {
1180
+ if (template.includes("%#") || template.includes("%$")) template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
1181
+ const count = template.split("%").length - 1;
1182
+ if (template.includes("%f")) (template.match(/%f/g) || []).forEach((_, i) => {
1183
+ if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
1184
+ let occurrence = 0;
1185
+ template = template.replace(/%f/g, (match) => {
1186
+ occurrence++;
1187
+ return occurrence === i + 1 ? "-%f" : match;
1188
+ });
1189
+ }
1190
+ });
1191
+ const isObjectItem = isObject(items[0]);
1192
+ function formatAttribute(s) {
1193
+ return s.replace(/\$([$\w.]+)/g, (_, key) => {
1194
+ const isArrayKey = /^\d+$/.test(key);
1195
+ if (!isObjectItem && !isArrayKey) return `$${key}`;
1196
+ const arrayElement = isArrayKey ? objectAttr(items, key) : void 0;
1197
+ return objDisplay(isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement, { truncate: runner?.config?.chaiConfig?.truncateThreshold });
1198
+ });
1199
+ }
1200
+ let output = "";
1201
+ let i = 0;
1202
+ handleRegexMatch(template, formatRegExp, (match) => {
1203
+ if (i < count) output += format(match[0], items[i++]);
1204
+ else output += match[0];
1205
+ }, (nonMatch) => {
1206
+ output += formatAttribute(nonMatch);
1207
+ });
1208
+ return output;
1209
+ }
1210
+ function handleRegexMatch(input, regex, onMatch, onNonMatch) {
1211
+ let lastIndex = 0;
1212
+ for (const m of input.matchAll(regex)) {
1213
+ if (lastIndex < m.index) onNonMatch(input.slice(lastIndex, m.index));
1214
+ onMatch(m);
1215
+ lastIndex = m.index + m[0].length;
1216
+ }
1217
+ if (lastIndex < input.length) onNonMatch(input.slice(lastIndex));
1218
+ }
1219
+ function formatTemplateString(cases, args) {
1220
+ const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
1221
+ const res = [];
1222
+ for (let i = 0; i < Math.floor(args.length / header.length); i++) {
1223
+ const oneCase = {};
1224
+ for (let j = 0; j < header.length; j++) oneCase[header[j]] = args[i * header.length + j];
1225
+ res.push(oneCase);
1226
+ }
1227
+ return res;
1228
+ }
1229
+ var now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1230
+ var collectorContext = {
1231
+ tasks: [],
1232
+ currentSuite: null
1233
+ };
1234
+ function collectTask(task) {
1235
+ collectorContext.currentSuite?.tasks.push(task);
1236
+ }
1237
+ async function runWithSuite(suite, fn) {
1238
+ const prev = collectorContext.currentSuite;
1239
+ collectorContext.currentSuite = suite;
1240
+ await fn();
1241
+ collectorContext.currentSuite = prev;
1242
+ }
1243
+ function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
1244
+ if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) return fn;
1245
+ const { setTimeout, clearTimeout } = getSafeTimers();
1246
+ return (function runWithTimeout(...args) {
1247
+ const startTime = now$2();
1248
+ const runner = getRunner();
1249
+ runner._currentTaskStartTime = startTime;
1250
+ runner._currentTaskTimeout = timeout;
1251
+ return new Promise((resolve_, reject_) => {
1252
+ const timer = setTimeout(() => {
1253
+ clearTimeout(timer);
1254
+ rejectTimeoutError();
1255
+ }, timeout);
1256
+ timer.unref?.();
1257
+ function rejectTimeoutError() {
1258
+ const error = makeTimeoutError(isHook, timeout, stackTraceError);
1259
+ onTimeout?.(args, error);
1260
+ reject_(error);
1261
+ }
1262
+ function resolve(result) {
1263
+ runner._currentTaskStartTime = void 0;
1264
+ runner._currentTaskTimeout = void 0;
1265
+ clearTimeout(timer);
1266
+ if (now$2() - startTime >= timeout) {
1267
+ rejectTimeoutError();
1268
+ return;
1269
+ }
1270
+ resolve_(result);
1271
+ }
1272
+ function reject(error) {
1273
+ runner._currentTaskStartTime = void 0;
1274
+ runner._currentTaskTimeout = void 0;
1275
+ clearTimeout(timer);
1276
+ reject_(error);
1277
+ }
1278
+ try {
1279
+ const result = fn(...args);
1280
+ if (typeof result === "object" && result != null && typeof result.then === "function") result.then(resolve, reject);
1281
+ else resolve(result);
1282
+ } catch (error) {
1283
+ reject(error);
1284
+ }
1285
+ });
1286
+ });
1287
+ }
1288
+ function withCancel(fn, signal) {
1289
+ return (function runWithCancel(...args) {
1290
+ return new Promise((resolve, reject) => {
1291
+ signal.addEventListener("abort", () => reject(signal.reason));
1292
+ try {
1293
+ const result = fn(...args);
1294
+ if (typeof result === "object" && result != null && typeof result.then === "function") result.then(resolve, reject);
1295
+ else resolve(result);
1296
+ } catch (error) {
1297
+ reject(error);
1298
+ }
1299
+ });
1300
+ });
1301
+ }
1302
+ var abortControllers = /* @__PURE__ */ new WeakMap();
1303
+ function abortIfTimeout([context], error) {
1304
+ if (context) abortContextSignal(context, error);
1305
+ }
1306
+ function abortContextSignal(context, error) {
1307
+ abortControllers.get(context)?.abort(error);
1308
+ }
1309
+ function createTestContext(test, runner) {
1310
+ const context = function() {
1311
+ throw new Error("done() callback is deprecated, use promise instead");
1312
+ };
1313
+ let abortController = abortControllers.get(context);
1314
+ if (!abortController) {
1315
+ abortController = new AbortController();
1316
+ abortControllers.set(context, abortController);
1317
+ }
1318
+ context.signal = abortController.signal;
1319
+ context.task = test;
1320
+ context.skip = (condition, note) => {
1321
+ if (condition === false) return;
1322
+ test.result ??= { state: "skip" };
1323
+ test.result.pending = true;
1324
+ throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
1325
+ };
1326
+ context.annotate = ((message, type, attachment) => {
1327
+ if (test.result && test.result.state !== "run") throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`);
1328
+ const annotation = {
1329
+ message,
1330
+ type: typeof type === "object" || type === void 0 ? "notice" : type
1331
+ };
1332
+ const annotationAttachment = typeof type === "object" ? type : attachment;
1333
+ if (annotationAttachment) {
1334
+ annotation.attachment = annotationAttachment;
1335
+ manageArtifactAttachment(annotation.attachment);
1336
+ }
1337
+ return recordAsyncOperation(test, recordArtifact(test, {
1338
+ type: "internal:annotation",
1339
+ annotation
1340
+ }).then(async ({ annotation }) => {
1341
+ if (!runner.onTestAnnotate) throw new Error(`Test runner doesn't support test annotations.`);
1342
+ await finishSendTasksUpdate(runner);
1343
+ const resolvedAnnotation = await runner.onTestAnnotate(test, annotation);
1344
+ test.annotations.push(resolvedAnnotation);
1345
+ return resolvedAnnotation;
1346
+ }));
1347
+ });
1348
+ context.onTestFailed = (handler, timeout) => {
1349
+ test.onFailed ||= [];
1350
+ test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1351
+ };
1352
+ context.onTestFinished = (handler, timeout) => {
1353
+ test.onFinished ||= [];
1354
+ test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1355
+ };
1356
+ return runner.extendTaskContext?.(context) || context;
1357
+ }
1358
+ function makeTimeoutError(isHook, timeout, stackTraceError) {
1359
+ 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"}".`;
1360
+ const error = new Error(message);
1361
+ if (stackTraceError?.stack) error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
1362
+ return error;
1363
+ }
1364
+ globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1365
+ globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1366
+ Date.now;
1367
+ var { clearTimeout, setTimeout } = getSafeTimers();
1368
+ var packs = /* @__PURE__ */ new Map();
1369
+ var eventsPacks = [];
1370
+ var pendingTasksUpdates = [];
1371
+ function sendTasksUpdate(runner) {
1372
+ if (packs.size) {
1373
+ const taskPacks = Array.from(packs).map(([id, task]) => {
1374
+ return [
1375
+ id,
1376
+ task[0],
1377
+ task[1]
1378
+ ];
1379
+ });
1380
+ const p = runner.onTaskUpdate?.(taskPacks, eventsPacks);
1381
+ if (p) {
1382
+ pendingTasksUpdates.push(p);
1383
+ p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
1384
+ }
1385
+ eventsPacks.length = 0;
1386
+ packs.clear();
1387
+ }
1388
+ }
1389
+ async function finishSendTasksUpdate(runner) {
1390
+ sendTasksUpdate(runner);
1391
+ await Promise.all(pendingTasksUpdates);
1392
+ }
1393
+ /**
1394
+ * @experimental
1395
+ * @advanced
1396
+ *
1397
+ * Records a custom test artifact during test execution.
1398
+ *
1399
+ * This function allows you to attach structured data, files, or metadata to a test.
1400
+ *
1401
+ * Vitest automatically injects the source location where the artifact was created and manages any attachments you include.
1402
+ *
1403
+ * **Note:** artifacts must be recorded before the task is reported. Any artifacts recorded after that will not be included in the task.
1404
+ *
1405
+ * @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests
1406
+ * @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase}
1407
+ *
1408
+ * @returns A promise that resolves to the recorded artifact with location injected
1409
+ *
1410
+ * @throws {Error} If the test runner doesn't support artifacts
1411
+ *
1412
+ * @example
1413
+ * ```ts
1414
+ * // In a custom assertion
1415
+ * async function toHaveValidSchema(this: MatcherState, actual: unknown) {
1416
+ * const validation = validateSchema(actual)
1417
+ *
1418
+ * await recordArtifact(this.task, {
1419
+ * type: 'my-plugin:schema-validation',
1420
+ * passed: validation.valid,
1421
+ * errors: validation.errors,
1422
+ * })
1423
+ *
1424
+ * return { pass: validation.valid, message: () => '...' }
1425
+ * }
1426
+ * ```
1427
+ */
1428
+ async function recordArtifact(task, artifact) {
1429
+ const runner = getRunner();
1430
+ const stack = findTestFileStackTrace(task.file.filepath, (/* @__PURE__ */ new Error("STACK_TRACE")).stack);
1431
+ if (stack) {
1432
+ artifact.location = {
1433
+ file: stack.file,
1434
+ line: stack.line,
1435
+ column: stack.column
1436
+ };
1437
+ if (artifact.type === "internal:annotation") artifact.annotation.location = artifact.location;
1438
+ }
1439
+ if (Array.isArray(artifact.attachments)) for (const attachment of artifact.attachments) manageArtifactAttachment(attachment);
1440
+ if (artifact.type === "internal:annotation") return artifact;
1441
+ if (!runner.onTestArtifactRecord) throw new Error(`Test runner doesn't support test artifacts.`);
1442
+ await finishSendTasksUpdate(runner);
1443
+ const resolvedArtifact = await runner.onTestArtifactRecord(task, artifact);
1444
+ task.artifacts.push(resolvedArtifact);
1445
+ return resolvedArtifact;
1446
+ }
1447
+ var table = [];
1448
+ for (let i = 65; i < 91; i++) table.push(String.fromCharCode(i));
1449
+ for (let i = 97; i < 123; i++) table.push(String.fromCharCode(i));
1450
+ for (let i = 0; i < 10; i++) table.push(i.toString(10));
1451
+ table.push("+", "/");
1452
+ function encodeUint8Array(bytes) {
1453
+ let base64 = "";
1454
+ const len = bytes.byteLength;
1455
+ for (let i = 0; i < len; i += 3) if (len === i + 1) {
1456
+ const a = (bytes[i] & 252) >> 2;
1457
+ const b = (bytes[i] & 3) << 4;
1458
+ base64 += table[a];
1459
+ base64 += table[b];
1460
+ base64 += "==";
1461
+ } else if (len === i + 2) {
1462
+ const a = (bytes[i] & 252) >> 2;
1463
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1464
+ const c = (bytes[i + 1] & 15) << 2;
1465
+ base64 += table[a];
1466
+ base64 += table[b];
1467
+ base64 += table[c];
1468
+ base64 += "=";
1469
+ } else {
1470
+ const a = (bytes[i] & 252) >> 2;
1471
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1472
+ const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
1473
+ const d = bytes[i + 2] & 63;
1474
+ base64 += table[a];
1475
+ base64 += table[b];
1476
+ base64 += table[c];
1477
+ base64 += table[d];
1478
+ }
1479
+ return base64;
1480
+ }
1481
+ /**
1482
+ * Records an async operation associated with a test task.
1483
+ *
1484
+ * This function tracks promises that should be awaited before a test completes.
1485
+ * The promise is automatically removed from the test's promise list once it settles.
1486
+ */
1487
+ function recordAsyncOperation(test, promise) {
1488
+ promise = promise.finally(() => {
1489
+ if (!test.promises) return;
1490
+ const index = test.promises.indexOf(promise);
1491
+ if (index !== -1) test.promises.splice(index, 1);
1492
+ });
1493
+ if (!test.promises) test.promises = [];
1494
+ test.promises.push(promise);
1495
+ return promise;
1496
+ }
1497
+ /**
1498
+ * Validates and prepares a test attachment for serialization.
1499
+ *
1500
+ * This function ensures attachments have either `body` or `path` set (but not both), and converts `Uint8Array` bodies to base64-encoded strings for easier serialization.
1501
+ *
1502
+ * @param attachment - The attachment to validate and prepare
1503
+ *
1504
+ * @throws {TypeError} If neither `body` nor `path` is provided
1505
+ * @throws {TypeError} If both `body` and `path` are provided
1506
+ */
1507
+ function manageArtifactAttachment(attachment) {
1508
+ if (attachment.body == null && !attachment.path) throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`);
1509
+ if (attachment.body && attachment.path) throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
1510
+ if (attachment.body instanceof Uint8Array) attachment.body = encodeUint8Array(attachment.body);
1511
+ }
1512
+ //#endregion
1513
+ export { createTaskName as B, findTestFileStackTrace as C, getNames as G, validateTags as T, afterAll as a, afterEach as b, aroundAll as c, aroundEach as d, beforeAll as e, beforeEach as f, createTaskCollector as g, describe as h, getCurrentSuite as i, getCurrentTest as j, getHooks as l, it as m, setHooks as q, recordArtifact as r, setFn as s, suite as u, test as v, createChainable as y };