@manifest-network/manifest-mcp-core 0.1.0

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