hypotes 0.0.0-stage → 0.0.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.
@@ -0,0 +1,16 @@
1
+ import type { Rule } from './types.ts';
2
+ export declare const expectExpect: Rule;
3
+ export declare const noStandaloneExpect: Rule;
4
+ export declare const validExpect: Rule;
5
+ export declare const preferToBe: Rule;
6
+ export declare const preferToHaveLength: Rule;
7
+ export declare const noFocusedTests: Rule;
8
+ export declare const noDisabledTests: Rule;
9
+ export declare const warnTodo: Rule;
10
+ export declare const validTitle: Rule;
11
+ export declare const validDescribeCallback: Rule;
12
+ export declare const noConditionalTests: Rule;
13
+ export declare const validExpectInPromise: Rule;
14
+ export declare const requireToThrowMessage: Rule;
15
+ export declare const requireMockTypeParameters: Rule;
16
+ export declare const hoistedApisOnTop: Rule;
@@ -0,0 +1,8 @@
1
+ import type { RuleTester } from 'oxlint/plugins-dev';
2
+ export type Rule = Parameters<RuleTester['run']>[1];
3
+ export type Context = Parameters<NonNullable<Rule['create']>>[0];
4
+ export type Visitor = ReturnType<NonNullable<Rule['create']>>;
5
+ export type Report = Parameters<Context['report']>[0];
6
+ export type Fix = NonNullable<Report['fix']>;
7
+ /** The node that a visitor of `Type` nodes takes */
8
+ export type NodeOf<Type extends keyof Visitor> = Parameters<NonNullable<Visitor[Type]>>[0];
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,309 @@
1
+ import { n as ModuleMocks, t as MOCKS_KEY } from "./mocks-ciQvBYVw.js";
2
+ import { createRequire, getSourceMapsSupport, registerHooks, setSourceMapsSupport } from "node:module";
3
+ import { fileURLToPath } from "node:url";
4
+ // source/hoist.ts
5
+ /**
6
+ * A call that the transform looks for, before it parses the module, with
7
+ * type arguments or without, as in `vi.importActual<typeof import('./a.ts')>()`
8
+ */
9
+ const MOCK_CALL = /\bvi\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock|importActual)\s*[(<]/u;
10
+ /** The methods of `vi` whose calls move above the module's code */
11
+ const HOISTED = /* @__PURE__ */ new Set([
12
+ "hoisted",
13
+ "mock",
14
+ "unmock"
15
+ ]);
16
+ /** The methods of `vi` whose paths resolve from the module */
17
+ const RESOLVED = /* @__PURE__ */ new Set([
18
+ "doMock",
19
+ "doUnmock",
20
+ "importActual",
21
+ "mock",
22
+ "unmock"
23
+ ]);
24
+ /** Where `vi` comes from, whose imports stay static, above the mocks */
25
+ const HYPOTES = "hypotes";
26
+ /** The registry, from the code of a transformed module */
27
+ const MOCKS = `globalThis[Symbol.for(${JSON.stringify(MOCKS_KEY)})]`;
28
+ /** The start of a call that resolves the path of a mock from the module */
29
+ const RESOLVE = `${MOCKS}.resolvePath(import.meta, `;
30
+ const decoder = new TextDecoder();
31
+ const require = createRequire(import.meta.url);
32
+ let dependencies;
33
+ /**
34
+ * The module, with its mocks hoisted, if it's an ES module outside
35
+ * node_modules that calls `vi` to mock modules
36
+ */
37
+ function hoistModule(url, loaded) {
38
+ const { format, source } = loaded;
39
+ if (source === void 0 || format !== "module" && format !== "module-typescript" || !url.startsWith("file:") || url.includes("/node_modules/")) return loaded;
40
+ const code = typeof source === "string" ? source : decoder.decode(source);
41
+ if (!MOCK_CALL.test(code)) return loaded;
42
+ const hoisted = hoistMocks(code, url);
43
+ if (hoisted === void 0) return loaded;
44
+ if (!getSourceMapsSupport().enabled) setSourceMapsSupport(true);
45
+ return {
46
+ ...loaded,
47
+ source: hoisted
48
+ };
49
+ }
50
+ /** oxc-parser and magic-string, which load once a module needs them */
51
+ function loadDependencies() {
52
+ if (dependencies === void 0) try {
53
+ const { parseSync, Visitor } = require("oxc-parser");
54
+ const { MagicString } = require("magic-string");
55
+ dependencies = {
56
+ MagicString,
57
+ parseSync,
58
+ Visitor
59
+ };
60
+ } catch (error) {
61
+ if (error.code !== "MODULE_NOT_FOUND") throw error;
62
+ throw new Error("hypotes/register hoists vi.mock() with oxc-parser and magic-string, its optional peer dependencies, which are missing", { cause: error });
63
+ }
64
+ return dependencies;
65
+ }
66
+ /**
67
+ * The module's code, with its mocks hoisted, and its source map, unless it
68
+ * doesn't parse, which Node reports as it compiles it, or doesn't call `vi`
69
+ */
70
+ function hoistMocks(code, url) {
71
+ const { MagicString, parseSync, Visitor } = loadDependencies();
72
+ const path = fileURLToPath(url);
73
+ const { errors, module, program } = parseSync(path, code, { sourceType: "module" });
74
+ if (errors.length > 0) return;
75
+ const calls = callsOf(program, Visitor);
76
+ if (calls.length === 0) return;
77
+ const hoisted = hoistedStatements(program);
78
+ checkTopLevel(calls, hoisted, code, path);
79
+ const s = new MagicString(code);
80
+ const paths = resolvePaths(s, calls, code);
81
+ wrapDynamicImports(s, module.dynamicImports, paths);
82
+ if (hoisted.length > 0) hoist(s, program, hoisted, code, path);
83
+ const map = s.generateMap({
84
+ source: url,
85
+ hires: "boundary"
86
+ });
87
+ return `${s.toString()}\n//# sourceMappingURL=${map.toUrl()}\n`;
88
+ }
89
+ /** The module's calls of the methods of `vi` that mock, in order */
90
+ function callsOf(program, Visitor) {
91
+ const calls = [];
92
+ new Visitor({ CallExpression(node) {
93
+ const method = methodOf(node);
94
+ if (method !== void 0) calls.push({
95
+ method,
96
+ node
97
+ });
98
+ } }).visit(program);
99
+ return calls;
100
+ }
101
+ /** The method of `vi` that the call calls, if it's one that mocks */
102
+ function methodOf(node) {
103
+ const { callee } = node;
104
+ if (callee.type !== "MemberExpression" || callee.computed || callee.object.type !== "Identifier" || callee.object.name !== "vi" || callee.property.type !== "Identifier") return;
105
+ const { name } = callee.property;
106
+ return HOISTED.has(name) || RESOLVED.has(name) ? name : void 0;
107
+ }
108
+ /**
109
+ * The statements at the module's top level that call `vi.mock()` or
110
+ * `vi.unmock()`, or `vi.hoisted()`, which can be awaited, and declare what
111
+ * it returns, if the statement declares nothing else: it moves whole
112
+ */
113
+ function hoistedStatements(program) {
114
+ const hoisted = [];
115
+ for (const statement of program.body) {
116
+ let expression;
117
+ if (statement.type === "ExpressionStatement") expression = statement.expression;
118
+ else if (statement.type === "VariableDeclaration" && statement.declarations.length === 1) expression = statement.declarations[0].init;
119
+ const call = expression?.type === "AwaitExpression" ? expression.argument : expression;
120
+ if (call?.type !== "CallExpression") continue;
121
+ const method = methodOf(call);
122
+ if (method === "hoisted" || (method === "mock" || method === "unmock") && call === expression) hoisted.push({
123
+ statement,
124
+ call
125
+ });
126
+ }
127
+ return hoisted;
128
+ }
129
+ /**
130
+ * Throws for a call that would be hoisted from outside the top level, where
131
+ * it would run before the code around it, as Vitest's transform does, or
132
+ * from a statement that would take more with it: an export, or other
133
+ * variables
134
+ */
135
+ function checkTopLevel(calls, hoisted, code, path) {
136
+ const topLevel = new Set(hoisted.map(({ call }) => call));
137
+ const nested = calls.filter(({ method, node }) => HOISTED.has(method) && !topLevel.has(node));
138
+ if (nested.length === 0) return;
139
+ const lines = nested.map(({ method, node }) => {
140
+ const [first] = node.arguments;
141
+ return `- vi.${method}(${first?.type === "Literal" ? code.slice(first.start, first.end) : ""}) at ${path}:${locationOf(code, node.start)}`;
142
+ });
143
+ throw new SyntaxError([
144
+ `${path} calls vi.mock(), vi.unmock() or vi.hoisted() where they can't be hoisted from:`,
145
+ "",
146
+ ...lines,
147
+ "",
148
+ "They're hoisted above the module's code, so call each in a statement of its own at the module's top level, where it shows when it runs. The statement can declare what vi.hoisted() returns, if it declares nothing else and isn't an export."
149
+ ].join("\n"));
150
+ }
151
+ /** The line and column, from 1, of the offset in the code */
152
+ function locationOf(code, offset) {
153
+ const before = code.slice(0, offset);
154
+ return `${before.split("\n").length}:${offset - before.lastIndexOf("\n")}`;
155
+ }
156
+ /**
157
+ * Wraps the path of each mock in the registry's `resolvePath()`, which
158
+ * resolves it from the module, and returns where they are.
159
+ * `import('./a.ts')`, which types a mock's factory, is `'./a.ts'`.
160
+ */
161
+ function resolvePaths(s, calls, code) {
162
+ const paths = [];
163
+ for (const { method, node } of calls) {
164
+ const [path] = node.arguments;
165
+ if (!RESOLVED.has(method) || path === void 0 || path.type === "SpreadElement") continue;
166
+ const awaited = path.type === "AwaitExpression" ? path.argument : path;
167
+ if (awaited.type === "ImportExpression") {
168
+ const { source } = awaited;
169
+ const specifier = code.slice(source.start, source.end);
170
+ s.overwrite(path.start, path.end, `${RESOLVE}${specifier})`);
171
+ } else {
172
+ s.prependRight(path.start, RESOLVE);
173
+ s.appendLeft(path.end, ")");
174
+ }
175
+ paths.push(path);
176
+ }
177
+ return paths;
178
+ }
179
+ /**
180
+ * Makes each dynamic import wait for the factories of the mocks before it,
181
+ * but those in the paths of mocks, which no longer import
182
+ */
183
+ function wrapDynamicImports(s, imports, paths) {
184
+ for (const { start, end } of imports) {
185
+ if (paths.some((path) => start >= path.start && end <= path.end)) continue;
186
+ s.prependRight(start, `${MOCKS}.wrapDynamicImport(() => `);
187
+ s.appendLeft(end, ")");
188
+ }
189
+ }
190
+ /**
191
+ * Moves the hoisted statements above the module's code, in order, and its
192
+ * imports and exports of other modules after them, as dynamic imports, which
193
+ * wait for the factories of the mocks before them
194
+ */
195
+ function hoist(s, program, hoisted, code, path) {
196
+ const loads = program.body.filter(isConverted);
197
+ checkVi(loads, path);
198
+ checkExportAll(loads, code, path);
199
+ let index = /^#!.*\r?\n/u.exec(code)?.[0].length ?? 0;
200
+ for (const { statement } of hoisted) {
201
+ const end = lineEnd(code, statement.end);
202
+ if (end === statement.end) s.appendLeft(end, "\n");
203
+ index = moveTo(s, statement.start, end, index);
204
+ }
205
+ for (const [position, node] of loads.entries()) {
206
+ const settle = position === 0 ? `await ${MOCKS}.settle();\n` : "";
207
+ s.overwrite(node.start, node.end, `${settle}${dynamicLoad(node, position, code)}\n`);
208
+ index = moveTo(s, node.start, node.end, index);
209
+ }
210
+ }
211
+ /**
212
+ * Whether the statement loads a module that becomes a dynamic import: an
213
+ * import, or an export of another module's exports, unless it's of types,
214
+ * which Node strips, from hypotes, or of a phase, which a dynamic import
215
+ * can't be
216
+ */
217
+ function isConverted(statement) {
218
+ switch (statement.type) {
219
+ case "ImportDeclaration": return statement.importKind !== "type" && statement.phase === null && statement.source.value !== HYPOTES;
220
+ case "ExportNamedDeclaration": return statement.source !== null && statement.exportKind !== "type" && statement.source.value !== HYPOTES;
221
+ case "ExportAllDeclaration": return statement.exportKind !== "type" && statement.source.value !== HYPOTES;
222
+ default: return false;
223
+ }
224
+ }
225
+ /** Throws if `vi` comes from an import that would follow the mocks */
226
+ function checkVi(loads, path) {
227
+ for (const node of loads) {
228
+ if (node.type !== "ImportDeclaration") continue;
229
+ if (node.specifiers.some((specifier) => specifier.local.name === "vi" && !(specifier.type === "ImportSpecifier" && specifier.importKind === "type"))) throw new SyntaxError(`${path} imports vi from "${node.source.value}", where vi.mock(), vi.unmock() and vi.hoisted() are hoisted above its imports, but those from "${HYPOTES}", which vi has to come from`);
230
+ }
231
+ }
232
+ /**
233
+ * Throws for `export * from`, which names its exports only by loading the
234
+ * module, so it can't follow the mocks, as a dynamic import does
235
+ */
236
+ function checkExportAll(loads, code, path) {
237
+ for (const node of loads) if (node.type === "ExportAllDeclaration" && node.exported === null) throw new SyntaxError(`${path} exports every export of ${code.slice(node.source.start, node.source.end)} at ${path}:${locationOf(code, node.start)}, which would load before the mocks that are hoisted above the module's imports. Export its exports by name, or as a namespace, with "export * as", which load after them.`);
238
+ }
239
+ /** The end of the line on which the offset is, if the line ends there */
240
+ function lineEnd(code, offset) {
241
+ if (code.startsWith("\r\n", offset)) return offset + 2;
242
+ return code[offset] === "\n" ? offset + 1 : offset;
243
+ }
244
+ /**
245
+ * Moves the code from start to end to the index, after what moved there
246
+ * before, unless it's there, and returns where the next moves to
247
+ */
248
+ function moveTo(s, start, end, index) {
249
+ if (index === start || index === end) return end;
250
+ s.move(start, end, index);
251
+ return index;
252
+ }
253
+ /**
254
+ * The statement, as a dynamic import that declares its bindings as
255
+ * constants, and exports those that it exports. `position` tells its
256
+ * constants from those of the module's other statements.
257
+ */
258
+ function dynamicLoad(node, position, code) {
259
+ const sliceOf = ({ start, end }) => code.slice(start, end);
260
+ const attributes = node.attributes.map(({ key, value }) => `${sliceOf(key)}: ${sliceOf(value)}`);
261
+ const options = attributes.length > 0 ? `, { with: { ${attributes.join(", ")} } }` : "";
262
+ const load = `await import(${sliceOf(node.source)}${options})`;
263
+ switch (node.type) {
264
+ case "ImportDeclaration": return importOf(node, load, sliceOf);
265
+ case "ExportNamedDeclaration": return exportOf(node, load, position, sliceOf);
266
+ default: {
267
+ const local = `__hypotes_export_${position}__`;
268
+ return `const ${local} = ${load}; export { ${local} as ${sliceOf(node.exported)} };`;
269
+ }
270
+ }
271
+ }
272
+ /** The import's bindings, declared from what `load` imports */
273
+ function importOf(node, load, sliceOf) {
274
+ let namespace;
275
+ const properties = [];
276
+ for (const specifier of node.specifiers) {
277
+ const local = specifier.local.name;
278
+ if (specifier.type === "ImportNamespaceSpecifier") namespace = local;
279
+ else if (specifier.type === "ImportDefaultSpecifier") properties.push(`default: ${local}`);
280
+ else if (specifier.importKind !== "type") {
281
+ const imported = sliceOf(specifier.imported);
282
+ properties.push(imported === local ? local : `${imported}: ${local}`);
283
+ }
284
+ }
285
+ const pattern = `{ ${properties.join(", ")} }`;
286
+ if (namespace !== void 0) return properties.length > 0 ? `const ${namespace} = ${load}, ${pattern} = ${namespace};` : `const ${namespace} = ${load};`;
287
+ return properties.length > 0 ? `const ${pattern} = ${load};` : `${load};`;
288
+ }
289
+ /**
290
+ * The exports of `export { a as b } from`, from constants of what `load`
291
+ * imports, on one line, as the statement was
292
+ */
293
+ function exportOf(node, load, position, sliceOf) {
294
+ const properties = [];
295
+ const exports = [];
296
+ for (const [index, specifier] of node.specifiers.entries()) if (specifier.exportKind !== "type") {
297
+ const local = `__hypotes_export_${position}_${index}__`;
298
+ properties.push(`${sliceOf(specifier.local)}: ${local}`);
299
+ exports.push(`${local} as ${sliceOf(specifier.exported)}`);
300
+ }
301
+ return properties.length > 0 ? `const { ${properties.join(", ")} } = ${load}; export { ${exports.join(", ")} };` : `${load};`;
302
+ }
303
+ // source/register.ts
304
+ const mocks = ModuleMocks.install();
305
+ if (mocks !== void 0) registerHooks({
306
+ resolve: (specifier, context, nextResolve) => mocks.resolve(specifier, context, nextResolve),
307
+ load: (url, context, nextLoad) => hoistModule(url, mocks.load(url, context, nextLoad))
308
+ });
309
+ export {};
package/dist/site.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /** Where a test or a suite was declared */
2
+ export interface Site {
3
+ readonly scriptName: string;
4
+ readonly lineNumber: number;
5
+ readonly columnNumber: number;
6
+ }
7
+ /** node:test's `it` or `describe` */
8
+ type Register<Options, Fn> = (name: string, options: Options, fn: Fn) => unknown;
9
+ /**
10
+ * The position of the code that called the function that calls this: the
11
+ * test file's, when that function is one that a test file calls. It's the
12
+ * position that node:test takes for the one where a test is written: the one
13
+ * that a source map maps it to, as in a module that `hypotes/register`
14
+ * transforms, unless node:test maps it itself, as it does with
15
+ * `--enable-source-maps`.
16
+ */
17
+ export declare function callerSite(): Site | undefined;
18
+ /** Calls `register` from code at the site, if there is one */
19
+ export declare function callFrom<Options, Fn>(site: Site | undefined, register: Register<Options, Fn>, name: string, options: Options, fn: Fn): unknown;
20
+ export {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The rows of a table, each an object of its columns' values, from a
3
+ * template's strings and values
4
+ */
5
+ export declare function parseTable(strings: readonly string[], values: readonly unknown[]): Array<Record<string, unknown>>;
@@ -0,0 +1,266 @@
1
+ import { getCallSites } from "node:util";
2
+ import * as nodeTest from "node:test";
3
+ import { isNegativeNaN, isObject, objectAttr, toArray } from "@vitest/utils/helpers";
4
+ import { compileFunction } from "node:vm";
5
+ import { format, formatRegExp, inspect as inspect$1, truncateString } from "@vitest/utils/display";
6
+ // source/site.ts
7
+ /** The functions compiled at each site, which each row of `.each` shares */
8
+ const callers = /* @__PURE__ */ new Map();
9
+ /**
10
+ * The position of the code that called the function that calls this: the
11
+ * test file's, when that function is one that a test file calls. It's the
12
+ * position that node:test takes for the one where a test is written: the one
13
+ * that a source map maps it to, as in a module that `hypotes/register`
14
+ * transforms, unless node:test maps it itself, as it does with
15
+ * `--enable-source-maps`.
16
+ */
17
+ function callerSite() {
18
+ const compiled = getCallSites(3, { sourceMap: false })[2];
19
+ if (!compiled?.scriptName) return;
20
+ const written = getCallSites(3, { sourceMap: true })[2];
21
+ if (isSamePosition(compiled, written)) return compiled;
22
+ return isSamePosition(getCallSites(3)[2], written) ? compiled : written;
23
+ }
24
+ function isSamePosition(a, b) {
25
+ return a.lineNumber === b.lineNumber && a.columnNumber === b.columnNumber && a.scriptName === b.scriptName;
26
+ }
27
+ /** Calls `register` from code at the site, if there is one */
28
+ function callFrom(site, register, name, options, fn) {
29
+ if (site === void 0) return register(name, options, fn);
30
+ const key = `${site.scriptName}:${site.lineNumber}:${site.columnNumber}`;
31
+ let caller = callers.get(key);
32
+ if (caller === void 0) {
33
+ caller = compileCaller(site);
34
+ callers.set(key, caller);
35
+ }
36
+ return caller(register, name, options, fn);
37
+ }
38
+ /** A function whose call to `register` lies at the site */
39
+ function compileCaller(site) {
40
+ const body = `return (\n${" ".repeat(site.columnNumber - 1)}register(name, options, fn));`;
41
+ return compileFunction(body, [
42
+ "register",
43
+ "name",
44
+ "options",
45
+ "fn"
46
+ ], {
47
+ filename: site.scriptName,
48
+ lineOffset: site.lineNumber - 2
49
+ });
50
+ }
51
+ // source/table.ts
52
+ /**
53
+ * The rows of a table, each an object of its columns' values, from a
54
+ * template's strings and values
55
+ */
56
+ function parseTable(strings, values) {
57
+ const columns = headerOf(strings).split("|");
58
+ const count = Math.floor(values.length / columns.length);
59
+ const rows = [];
60
+ for (let index = 0; index < count; index++) rows.push(rowAt(columns, values, index));
61
+ return rows;
62
+ }
63
+ /** The first line of the template's text, without spaces */
64
+ function headerOf(strings) {
65
+ const text = strings.join("").trim();
66
+ const end = text.indexOf("\n");
67
+ return (end === -1 ? text : text.slice(0, end)).replaceAll(" ", "");
68
+ }
69
+ /**
70
+ * The row of the index, which assigns each value to its column's name, as
71
+ * Vitest does: a later column of the same name replaces an earlier one
72
+ */
73
+ function rowAt(columns, values, index) {
74
+ const row = {};
75
+ for (const [column, name] of columns.entries()) row[name] = values[index * columns.length + column];
76
+ return row;
77
+ }
78
+ // source/title.ts
79
+ /** The characters that a value prints in, Vitest's default */
80
+ const TRUNCATE = 40;
81
+ const INSPECT_OPTIONS = { truncate: TRUNCATE };
82
+ /** `$name` and `$0.name`, the paths of values in a row */
83
+ const ATTRIBUTE = /\$([$\p{ID_Continue}.]+)/gu;
84
+ /**
85
+ * Formats a title of `.each` or `.for` with the row's values: `%s`, `%d`,
86
+ * `%i`, `%f`, `%j`, `%o` and `%O` print them in order, as `util.format`
87
+ * does, `%#` and `%$` print the row's index from 0 and from 1, and `$name`
88
+ * prints a property of the row, if it's an object, or of an array's element,
89
+ * as `$0.name`.
90
+ */
91
+ function formatTitle(template, items, index) {
92
+ const signed = signZeroes(formatIndex(template, index), items);
93
+ const count = signed.split("%").length - 1;
94
+ let title = "";
95
+ let position = 0;
96
+ let used = 0;
97
+ for (const match of signed.matchAll(formatRegExp)) {
98
+ title += formatAttributes(signed.slice(position, match.index), items);
99
+ title += used < count ? format([match[0], items[used++]], INSPECT_OPTIONS) : match[0];
100
+ position = match.index + match[0].length;
101
+ }
102
+ return title + formatAttributes(signed.slice(position), items);
103
+ }
104
+ /** Replaces `%#` with the row's index, and `%$` with it from 1 */
105
+ function formatIndex(template, index) {
106
+ if (!(template.includes("%#") || template.includes("%$"))) return template;
107
+ return template.replaceAll("%%", "__vitest_escaped_%__").replaceAll("%#", String(index)).replaceAll("%$", String(index + 1)).replaceAll("__vitest_escaped_%__", "%%");
108
+ }
109
+ /**
110
+ * Puts a minus before each `%f` whose value is -0 or a negative NaN, which
111
+ * `%f` prints without its sign
112
+ */
113
+ function signZeroes(template, items) {
114
+ let signed = template;
115
+ for (const [index] of (template.match(/%f/gu) ?? []).entries()) {
116
+ const value = items[index];
117
+ if (isNegativeNaN(value) || Object.is(value, -0)) {
118
+ let occurrence = 0;
119
+ signed = signed.replaceAll("%f", (match) => ++occurrence === index + 1 ? "-%f" : match);
120
+ }
121
+ }
122
+ return signed;
123
+ }
124
+ /** Replaces `$name` with the property of the row, or of its element */
125
+ function formatAttributes(text, items) {
126
+ const isObjectItem = isObject(items[0]);
127
+ return text.replaceAll(ATTRIBUTE, (_, key) => {
128
+ const isArrayKey = /^\d+$/u.test(key);
129
+ if (!isObjectItem && !isArrayKey) return `$${key}`;
130
+ const element = isArrayKey ? objectAttr(items, key) : void 0;
131
+ const value = isObjectItem ? objectAttr(items[0], key, element) : element;
132
+ return typeof value === "string" ? truncateString(value, TRUNCATE) : inspect$1(value, INSPECT_OPTIONS);
133
+ });
134
+ }
135
+ // source/tests.ts
136
+ /**
137
+ * The function and options of a declaration, as Vitest 4 reads them: its
138
+ * options before its function, or a timeout after it. It throws a TypeError,
139
+ * with Vitest's message, for options after the function, which Vitest took
140
+ * until 4, and for two functions.
141
+ */
142
+ function parseArguments(first, second) {
143
+ if (second !== null && typeof second === "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.");
144
+ if (typeof first === "function" && typeof second === "function") throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
145
+ return {
146
+ fn: functionOf(first, second),
147
+ options: optionsOf(first, second)
148
+ };
149
+ }
150
+ /** The function of a declaration, before a timeout or after its options */
151
+ function functionOf(first, second) {
152
+ if (typeof first === "function") return first;
153
+ return typeof second === "function" ? second : void 0;
154
+ }
155
+ /**
156
+ * The options of a declaration: a timeout after its function, or else the
157
+ * options before it
158
+ */
159
+ function optionsOf(first, second) {
160
+ if (typeof second === "number") return { timeout: second };
161
+ return typeof first === "object" ? first : {};
162
+ }
163
+ /**
164
+ * The API of `it` or `describe`, of options that its modifiers set: each
165
+ * modifier builds another, when it's read. `extend` adds members, such as
166
+ * `prop`, which declare tests with the same options.
167
+ */
168
+ function createAPI(register, options, extend) {
169
+ const define = (name, ownOptions, fn, site) => {
170
+ const merged = {
171
+ ...options,
172
+ ...ownOptions
173
+ };
174
+ const todo = fn === void 0 ? { todo: true } : {};
175
+ register(name, {
176
+ ...merged,
177
+ ...todo
178
+ }, fn, site);
179
+ };
180
+ const build = (more) => createAPI(register, {
181
+ ...options,
182
+ ...more
183
+ }, extend);
184
+ const skipIf = (skip) => build(skip ? { skip: true } : {});
185
+ const declare = (name, first, second) => {
186
+ const parsed = parseArguments(first, second);
187
+ define(name, parsed.options, parsed.fn, callerSite());
188
+ };
189
+ return Object.defineProperties(Object.assign(declare, extend(define)), {
190
+ skip: { get: () => build({ skip: true }) },
191
+ only: { get: () => build({ only: true }) },
192
+ todo: { get: () => build({ todo: true }) },
193
+ skipIf: { value: (condition) => skipIf(Boolean(condition)) },
194
+ runIf: { value: (condition) => {
195
+ return skipIf(!Boolean(condition));
196
+ } },
197
+ each: { value: each(define) },
198
+ for: { value: forEach(define) }
199
+ });
200
+ }
201
+ /**
202
+ * The rows that `.each` or `.for` declares, from what it's called with: a
203
+ * table's, if values follow the cases, as a template literal's follow its
204
+ * strings, and otherwise the cases themselves. As in Vitest, the strings of a
205
+ * template literal without values are its rows.
206
+ */
207
+ function rowsOf(cases, values) {
208
+ return values.length > 0 ? parseTable(cases, values) : cases;
209
+ }
210
+ /** `.each`: spreads the rows if every row is an array */
211
+ function each(define) {
212
+ return (cases, ...values) => {
213
+ const rows = rowsOf(cases, values);
214
+ return (name, first, second) => {
215
+ const site = callerSite();
216
+ const { fn, options } = parseArguments(first, second);
217
+ const handler = fn;
218
+ const spread = rows.every((row) => Array.isArray(row));
219
+ for (const [index, row] of rows.entries()) {
220
+ const items = Array.isArray(row) ? row : [row];
221
+ const title = formatTitle(name, items, index);
222
+ const run = () => spread ? handler?.(...items) : handler?.(row);
223
+ define(title, options, handler && run, site);
224
+ }
225
+ };
226
+ };
227
+ }
228
+ /** `.for`: passes each row whole, and a test's context after it */
229
+ function forEach(define) {
230
+ return (cases, ...values) => {
231
+ const rows = rowsOf(cases, values);
232
+ return (name, first, second) => {
233
+ const site = callerSite();
234
+ const { fn, options } = parseArguments(first, second);
235
+ const handler = fn;
236
+ for (const [index, row] of rows.entries()) {
237
+ const title = formatTitle(name, toArray(row), index);
238
+ const run = (context) => handler?.(row, context);
239
+ define(title, options, handler && run, site);
240
+ }
241
+ };
242
+ };
243
+ }
244
+ /** Declares a test through node:test, which awaits it */
245
+ function registerTest(name, options, fn, site) {
246
+ const test = fn && ((context) => fn(context));
247
+ callFrom(site, nodeTest.it, name, options, test);
248
+ }
249
+ /** Declares a suite through node:test, which awaits it */
250
+ function registerSuite(name, options, fn, site) {
251
+ callFrom(site, nodeTest.describe, name, options, fn);
252
+ }
253
+ /**
254
+ * The API of `it` and `test`, with the members that `extend` adds at each
255
+ * modifier, such as fast-check's `prop`
256
+ */
257
+ function createTestAPI(extend) {
258
+ return createAPI(registerTest, {}, extend);
259
+ }
260
+ /** Declares a test, which passes unless its function throws or rejects */
261
+ const it = createTestAPI(() => ({}));
262
+ const test = it;
263
+ /** Declares a suite, whose function declares tests and other suites */
264
+ const describe = createAPI(registerSuite, {}, () => ({}));
265
+ const suite = describe;
266
+ export { suite as a, parseArguments as i, describe as n, test as o, it as r, callerSite as s, createTestAPI as t };