@jterrazz/test 15.1.1 → 15.3.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,2796 @@
1
+ import { TestRunner, expect, inject, onTestFinished, vi } from "vitest";
2
+ import { commands, page, userEvent } from "vitest/browser";
3
+ import { mock, mockDeep } from "vitest-mock-extended";
4
+ import MockDatePackage from "mockdate";
5
+ //#region src/specification/contracts/contract.ts
6
+ /**
7
+ * Declare one contract. Identity function — its value is the enforced shape
8
+ * and the naming convention:
9
+ *
10
+ * @example
11
+ * // specs/api/reports/contracts/openai/classify-article.ts
12
+ * import { defineContract, openai } from '@jterrazz/test';
13
+ *
14
+ * export default defineContract({
15
+ * request: openai.responses({ user: PROMPT, tools: ['classify'] }),
16
+ * response: openai.reply({ categories: ['TECH'] }),
17
+ * });
18
+ *
19
+ * // Dynamic — the response is computed from the observed request:
20
+ * export default defineContract({
21
+ * request: http.post('https://api.example.com/echo'),
22
+ * response: (request) => http.json({ received: request.body }),
23
+ * });
24
+ */
25
+ function defineContract(contract) {
26
+ return contract;
27
+ }
28
+ /** Is this a {@link Contracts} composite (rather than a contract or a list)? */
29
+ function isContracts(value) {
30
+ return typeof value === "object" && value !== null && Array.isArray(value.contracts) && typeof value.with === "function";
31
+ }
32
+ /** Is this a single {@link Contract} (rather than a bare request half)? */
33
+ function isContract(value) {
34
+ return typeof value === "object" && value !== null && "request" in value && "response" in value;
35
+ }
36
+ /**
37
+ * The route a contract claims — method + the DECLARED url source. Two
38
+ * contracts share a route when they would be written on the same line of a
39
+ * declaration: same method, same url pattern (`.source` for a RegExp).
40
+ */
41
+ function routeKeyOf(contract) {
42
+ const { method, url } = contract.request;
43
+ return url instanceof RegExp ? `${method} re:${url.source}` : `${method} str:${url}`;
44
+ }
45
+ /** Human-readable route of a contract — used in every failure message. */
46
+ function describeRoute(contract) {
47
+ const { method, url } = contract.request;
48
+ return `${method === "*" ? "ANY" : method} ${url instanceof RegExp ? String(url) : url}`;
49
+ }
50
+ /** Flatten contracts, lists, and composites into one ordered list. */
51
+ function flatten(items) {
52
+ const flat = [];
53
+ for (const item of items) if (Array.isArray(item)) flat.push(...flatten(item));
54
+ else if (isContracts(item)) flat.push(...item.contracts);
55
+ else flat.push(item);
56
+ return flat;
57
+ }
58
+ /**
59
+ * Compose contracts into the artifact a test imports — it's contracts all the
60
+ * way down: a composite may extend contracts, lists, and other composites,
61
+ * recursively, order preserved.
62
+ *
63
+ * `.with(...)` derives a scenario: contracts whose route the overrides claim
64
+ * are removed from the base, and the overrides are prepended. Under
65
+ * first-match selection a more specific override (`/articles/gone-1`) also
66
+ * wins over a generic base route (`/articles/{{uuid}}`) it does not replace.
67
+ *
68
+ * @example
69
+ * // contracts/newsroom.contracts.ts
70
+ * export default defineContracts(events, articleById);
71
+ * export const withArticleGone = (id: string) =>
72
+ * newsroom.with(articleGone(id));
73
+ */
74
+ function defineContracts(...items) {
75
+ const contracts = Object.freeze(flatten(items));
76
+ return {
77
+ contracts,
78
+ with(...overrides) {
79
+ const added = flatten(overrides);
80
+ const claimed = new Set(added.map(routeKeyOf));
81
+ const kept = contracts.filter((contract) => !claimed.has(routeKeyOf(contract)));
82
+ return defineContracts([...added, ...kept]);
83
+ }
84
+ };
85
+ }
86
+ /** Normalize any accepted input into a flat contract list. */
87
+ function contractsOf(input) {
88
+ return flatten([input]);
89
+ }
90
+ //#endregion
91
+ //#region src/integrations/msw/scope.ts
92
+ /**
93
+ * The network double in MODULE scope — the same contracts, the same queue and
94
+ * the same strictness as a chain's `.intercept()`, for the one kind of test
95
+ * that has no chain to hang them on.
96
+ *
97
+ * A module test whose subject reaches the network had exactly two ways out
98
+ * before this: `vi.stubGlobal('fetch')`, which replaces the platform with a
99
+ * hand-written stand-in, or `msw/node` imported directly, which F6 refuses a
100
+ * test and F8 refuses a consumer to declare. Both answer "what did the outside
101
+ * world reply" in a dialect nothing else in the repository speaks.
102
+ *
103
+ * The scope is an `AsyncDisposable`, so the handlers come off at the end of
104
+ * the block however the block ends — and the strict violation (an outgoing
105
+ * request no contract accepted) is raised THERE, which is what makes the
106
+ * double a guard rather than a convenience.
107
+ */
108
+ /**
109
+ * The contracts a call declared, whichever of the two forms it used. Exported
110
+ * for its own module test: the bare-request refusal is a runtime guard the
111
+ * compiler already states, so no typed call site can reach it.
112
+ *
113
+ * @internal
114
+ */
115
+ function declared(requestOrContracts, maybeResponse) {
116
+ if (Array.isArray(requestOrContracts) || isContracts(requestOrContracts) || isContract(requestOrContracts)) return contractsOf(requestOrContracts);
117
+ if (maybeResponse === void 0) throw new Error("intercept(): a bare request needs its response — pass a contract (defineContract({ request, response })) or the inline pair intercept(request, response).");
118
+ return [{
119
+ request: requestOrContracts,
120
+ response: maybeResponse
121
+ }];
122
+ }
123
+ /**
124
+ * Build the module-scope double on one engine. The node entry hands it msw's
125
+ * server, the page's entry hands it msw's worker: one shape, two transports,
126
+ * exactly as a chain's `.intercept()` already has it.
127
+ *
128
+ * @internal
129
+ */
130
+ function interceptThrough(register) {
131
+ async function intercept(requestOrContracts, maybeResponse) {
132
+ const contracts = declared(requestOrContracts, maybeResponse);
133
+ if (contracts.length === 0) throw new Error("intercept(): declare at least one contract — an empty list guards nothing, and a subject with no network needs no intercept at all.");
134
+ const registration = await register(contracts);
135
+ return { [Symbol.asyncDispose]: async () => {
136
+ const violation = registration.violation();
137
+ registration.cleanup();
138
+ await Promise.resolve();
139
+ if (violation) throw violation;
140
+ } };
141
+ }
142
+ return intercept;
143
+ }
144
+ //#endregion
145
+ //#region src/specification/matching/match.ts
146
+ /** Every kind usable as a `{{token}}` in fixture files (all but ref/regex/includes). */
147
+ const TOKEN_KINDS = [
148
+ "any",
149
+ "base64",
150
+ "date",
151
+ "duration",
152
+ "email",
153
+ "float",
154
+ "hex",
155
+ "int",
156
+ "ip",
157
+ "iso8601",
158
+ "number",
159
+ "path",
160
+ "port",
161
+ "semver",
162
+ "sha",
163
+ "string",
164
+ "time",
165
+ "ulid",
166
+ "url",
167
+ "uuid",
168
+ "workdir"
169
+ ];
170
+ /**
171
+ * A dynamic-value matcher. Created via the {@link match} factories — never
172
+ * constructed directly by user code.
173
+ */
174
+ var Matcher = class {
175
+ /** For kind 'includes': the substring the actual value must contain. */
176
+ includes;
177
+ kind;
178
+ /** For kind 'ref': the capture to assert inequality against. */
179
+ notRef;
180
+ /** For kind 'ref': the capture name. */
181
+ refName;
182
+ /** For kind 'regex': the pattern the actual value must match. */
183
+ regex;
184
+ constructor(kind, options = {}) {
185
+ this.includes = options.includes;
186
+ this.kind = kind;
187
+ this.notRef = options.notRef;
188
+ this.refName = options.refName;
189
+ this.regex = options.regex;
190
+ }
191
+ /** Placeholder-style rendering used in failure diffs and serialization. */
192
+ toString() {
193
+ switch (this.kind) {
194
+ case "includes": return `{{includes:${this.includes}}}`;
195
+ case "ref": return this.notRef ? `{{ref#${this.refName}!${this.notRef}}}` : `{{ref#${this.refName}}}`;
196
+ case "regex": return `{{regex:${this.regex?.source}}}`;
197
+ default: return this.refName ? `{{${this.kind}#${this.refName}}}` : `{{${this.kind}}}`;
198
+ }
199
+ }
200
+ toJSON() {
201
+ return this.toString();
202
+ }
203
+ };
204
+ const typed = (kind) => () => new Matcher(kind);
205
+ const match = {
206
+ /** Matches anything. */
207
+ any: typed("any"),
208
+ /** Matches a base64 string. */
209
+ base64: typed("base64"),
210
+ /** Matches a calendar date (`YYYY-MM-DD`). */
211
+ date: typed("date"),
212
+ /** Matches a human duration (`12ms`, `1.5s`, `2m`, `3h`). */
213
+ duration: typed("duration"),
214
+ /** Matches an email address. */
215
+ email: typed("email"),
216
+ /**
217
+ * Matches a float. In JSON contexts any finite number passes (JSON does
218
+ * not distinguish `42` from `42.0`); in text contexts the decimal part
219
+ * is required (`4.2`, never `42`).
220
+ */
221
+ float: typed("float"),
222
+ /** Matches a hexadecimal string. */
223
+ hex: typed("hex"),
224
+ /**
225
+ * Matches a string CONTAINING the given substring. Code-only, like
226
+ * {@link match.regex} — the `{{token}}` fixture vocabulary does not grow.
227
+ * The explicit escape hatch now that contract string filters
228
+ * (`openai.chat({ user })`) mean exact equality.
229
+ */
230
+ includes: (substring) => new Matcher("includes", { includes: substring }),
231
+ /** Matches an integer (or an integer string in text contexts). */
232
+ int: typed("int"),
233
+ /** Matches an IPv4 address. */
234
+ ip: typed("ip"),
235
+ /** Matches an ISO-8601 timestamp string. */
236
+ iso8601: typed("iso8601"),
237
+ /** Matches a number (or a numeric string in text contexts). */
238
+ number: typed("number"),
239
+ /** Matches a filesystem path (`/...` or `./...`). */
240
+ path: typed("path"),
241
+ /** Matches a TCP/UDP port number (0-65535). */
242
+ port: typed("port"),
243
+ /**
244
+ * Capture-and-compare. The first occurrence of `ref(name)` captures the
245
+ * actual value; every later occurrence must strictly equal the capture.
246
+ * `{ not: other }` additionally asserts inequality with the capture named
247
+ * `other`. Scope: the current spec execution (reset per chain).
248
+ */
249
+ ref: (name, options) => new Matcher("ref", {
250
+ notRef: options?.not,
251
+ refName: name
252
+ }),
253
+ /** Matches a string against the given regular expression. */
254
+ regex: (regex) => new Matcher("regex", { regex }),
255
+ /** Matches a semantic version (`1.2.3`, `2.0.0-rc.1`). */
256
+ semver: typed("semver"),
257
+ /** Matches a git SHA (7-64 hex chars). */
258
+ sha: typed("sha"),
259
+ /** Matches any string. */
260
+ string: typed("string"),
261
+ /** Matches a wall-clock time (`HH:MM` or `HH:MM:SS`). */
262
+ time: typed("time"),
263
+ /** Matches a ULID. */
264
+ ulid: typed("ulid"),
265
+ /** Matches an http(s) URL. */
266
+ url: typed("url"),
267
+ /** Matches a UUID string. */
268
+ uuid: typed("uuid"),
269
+ /** Matches the exact working directory of the current spec. */
270
+ workdir: typed("workdir")
271
+ };
272
+ /**
273
+ * Named captures recorded by `match.ref()` / `{{type#ref}}` placeholders.
274
+ * One scope lives on each spec result — every assertion chained off the same
275
+ * result shares it, and a new chain starts fresh.
276
+ */
277
+ var CaptureScope = class {
278
+ values = /* @__PURE__ */ new Map();
279
+ /**
280
+ * The exact working directory of the current spec, when the framework
281
+ * knows it (cli mode). Drives the `{{workdir}}` token / `match.workdir()`.
282
+ */
283
+ workdir;
284
+ constructor(workdir) {
285
+ this.workdir = workdir;
286
+ }
287
+ get(name) {
288
+ return this.values.get(name);
289
+ }
290
+ has(name) {
291
+ return this.values.has(name);
292
+ }
293
+ set(name, value) {
294
+ this.values.set(name, value);
295
+ }
296
+ };
297
+ //#endregion
298
+ //#region src/specification/matching/structural.ts
299
+ /**
300
+ * Structural comparison engine shared by every fixture matcher.
301
+ *
302
+ * Handles three kinds of "expected" values:
303
+ * - plain JSON values → strict deep equality
304
+ * - {@link Matcher} instances (code-side `match.*`)
305
+ * - strings containing `{{placeholder}}` forms (file-side fixtures)
306
+ *
307
+ * One unified `{{token}}` grammar (CONVENTIONS D4) — the same vocabulary
308
+ * works in `_expected/*.http` (body and headers), `_expected/*.json`, and
309
+ * text snapshots (`_expected/*.txt`).
310
+ *
311
+ * Ref captures (`match.ref(name)` / `{{type#name}}`) are recorded in the
312
+ * {@link CaptureScope} supplied by the caller.
313
+ */
314
+ const UUID_SOURCE = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
315
+ const ULID_SOURCE = "[0-9A-HJKMNP-TV-Z]{26}";
316
+ const ISO8601_SOURCE = String.raw`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})`;
317
+ const DATE_SOURCE = String.raw`\d{4}-\d{2}-\d{2}`;
318
+ const TIME_SOURCE = String.raw`\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?`;
319
+ const DURATION_SOURCE = String.raw`\d+(?:\.\d+)?(?:ms|s|m|h)`;
320
+ const NUMBER_SOURCE = String.raw`-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?`;
321
+ const INT_SOURCE = String.raw`-?\d+`;
322
+ const FLOAT_SOURCE = String.raw`-?\d+\.\d+`;
323
+ const SEMVER_SOURCE = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?`;
324
+ const SHA_SOURCE = "[0-9a-f]{7,64}";
325
+ const HEX_SOURCE = "[0-9a-fA-F]+";
326
+ const BASE64_SOURCE = "[A-Za-z0-9+/]+={0,2}";
327
+ const PORT_SOURCE = String.raw`(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|\d{1,4})`;
328
+ const IP_OCTET = String.raw`(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)`;
329
+ const IP_SOURCE = String.raw`(?:${IP_OCTET}\.){3}${IP_OCTET}`;
330
+ const URL_SOURCE = String.raw`https?:\/\/[^\s"'<>]+`;
331
+ const EMBEDDED_SOURCES = {
332
+ base64: BASE64_SOURCE,
333
+ date: DATE_SOURCE,
334
+ duration: DURATION_SOURCE,
335
+ email: String.raw`[^\s@"'<>]+@[^\s@"'<>]+\.[^\s@"'<>]+`,
336
+ float: FLOAT_SOURCE,
337
+ hex: HEX_SOURCE,
338
+ int: INT_SOURCE,
339
+ ip: IP_SOURCE,
340
+ iso8601: ISO8601_SOURCE,
341
+ number: NUMBER_SOURCE,
342
+ path: String.raw`\.{0,2}\/[^\s"'<>]*`,
343
+ port: PORT_SOURCE,
344
+ semver: SEMVER_SOURCE,
345
+ sha: SHA_SOURCE,
346
+ time: TIME_SOURCE,
347
+ ulid: ULID_SOURCE,
348
+ url: URL_SOURCE,
349
+ uuid: UUID_SOURCE
350
+ };
351
+ const wholeRe = (source) => new RegExp(`^(?:${source})$`, "u");
352
+ const WHOLE_RES = Object.fromEntries(Object.entries(EMBEDDED_SOURCES).map(([kind, source]) => [kind, wholeRe(source)]));
353
+ const PLACEHOLDER_RE = new RegExp(String.raw`\{\{(?<kind>${[...TOKEN_KINDS].sort((a, b) => b.length - a.length).join("|")})(?:#(?<ref>[\w.-]+))?\}\}`, "gu");
354
+ /** Whether a fixture string contains at least one `{{placeholder}}`. */
355
+ function hasPlaceholders(value) {
356
+ PLACEHOLDER_RE.lastIndex = 0;
357
+ return PLACEHOLDER_RE.test(value);
358
+ }
359
+ /** Key-order-independent stringification for captured-object comparison. */
360
+ function stableStringify(value) {
361
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
362
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1).map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
363
+ return JSON.stringify(value) ?? "undefined";
364
+ }
365
+ function capturedEquals(a, b) {
366
+ if (Object.is(a, b)) return true;
367
+ if (typeof a === "number" && typeof b === "string" || typeof a === "string" && typeof b === "number") return String(a) === String(b);
368
+ if (a !== null && b !== null && typeof a === "object" && typeof b === "object") return stableStringify(a) === stableStringify(b);
369
+ return false;
370
+ }
371
+ function recordRef(name, actual, scope) {
372
+ if (scope.has(name)) return capturedEquals(scope.get(name), actual);
373
+ scope.set(name, actual);
374
+ return true;
375
+ }
376
+ function isPortValue(value) {
377
+ return Number.isInteger(value) && value >= 0 && value <= 65535;
378
+ }
379
+ function kindMatches(kind, actual, scope) {
380
+ switch (kind) {
381
+ case "any": return true;
382
+ case "float":
383
+ if (typeof actual === "number") return Number.isFinite(actual);
384
+ return typeof actual === "string" && WHOLE_RES.float.test(actual);
385
+ case "int":
386
+ if (typeof actual === "number") return Number.isInteger(actual);
387
+ return typeof actual === "string" && WHOLE_RES.int.test(actual);
388
+ case "number":
389
+ if (typeof actual === "number") return Number.isFinite(actual);
390
+ return typeof actual === "string" && WHOLE_RES.number.test(actual);
391
+ case "port":
392
+ if (typeof actual === "number") return isPortValue(actual);
393
+ return typeof actual === "string" && WHOLE_RES.port.test(actual) && isPortValue(Number(actual));
394
+ case "string": return typeof actual === "string";
395
+ case "workdir": return typeof actual === "string" && scope.workdir !== void 0 ? actual === scope.workdir : false;
396
+ default: {
397
+ const re = WHOLE_RES[kind];
398
+ return re !== void 0 && typeof actual === "string" && re.test(actual);
399
+ }
400
+ }
401
+ }
402
+ function matcherMatches(matcher, actual, scope) {
403
+ if (matcher.kind === "includes") return typeof actual === "string" && actual.includes(matcher.includes);
404
+ if (matcher.kind === "regex") return typeof actual === "string" && matcher.regex.test(actual);
405
+ if (matcher.kind === "ref") {
406
+ if (matcher.notRef && scope.has(matcher.notRef) && capturedEquals(scope.get(matcher.notRef), actual)) return false;
407
+ return recordRef(matcher.refName, actual, scope);
408
+ }
409
+ return kindMatches(matcher.kind, actual, scope);
410
+ }
411
+ function placeholderSource(kind, scope) {
412
+ if (kind === "workdir") return scope.workdir === void 0 ? "(?!)" : escapeRegExp(scope.workdir);
413
+ const source = EMBEDDED_SOURCES[kind];
414
+ if (source) return source;
415
+ return kind === "any" ? String.raw`[\s\S]*?` : String.raw`[^\n]*?`;
416
+ }
417
+ function escapeRegExp(text) {
418
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
419
+ }
420
+ function parsePlaceholderString(expected, scope) {
421
+ PLACEHOLDER_RE.lastIndex = 0;
422
+ const refs = [];
423
+ let source = "";
424
+ let lastIndex = 0;
425
+ let single = null;
426
+ let count = 0;
427
+ for (const found of expected.matchAll(PLACEHOLDER_RE)) {
428
+ const kind = found.groups.kind;
429
+ const { ref } = found.groups;
430
+ source += escapeRegExp(expected.slice(lastIndex, found.index));
431
+ source += `(${placeholderSource(kind, scope)})`;
432
+ refs.push({
433
+ index: count,
434
+ kind,
435
+ ref
436
+ });
437
+ count++;
438
+ lastIndex = found.index + found[0].length;
439
+ if (found.index === 0 && found[0].length === expected.length) single = {
440
+ kind,
441
+ ref
442
+ };
443
+ }
444
+ source += escapeRegExp(expected.slice(lastIndex));
445
+ return {
446
+ pattern: new RegExp(`^${source}$`, "u"),
447
+ refs,
448
+ single,
449
+ source
450
+ };
451
+ }
452
+ /**
453
+ * Unanchored regex source matching a fixture string — plain text escaped
454
+ * verbatim, each `{{token}}` expanded to its embedded grammar. Used to route
455
+ * declared `.http` intercept paths (`/articles/{{uuid}}`) as URL patterns.
456
+ */
457
+ function placeholderPatternSource(expected) {
458
+ return parsePlaceholderString(expected, new CaptureScope()).source;
459
+ }
460
+ function placeholderStringMatches(expected, actual, scope) {
461
+ const parsed = parsePlaceholderString(expected, scope);
462
+ if (parsed.single) {
463
+ if (!kindMatches(parsed.single.kind, actual, scope)) return false;
464
+ if (parsed.single.ref) return recordRef(parsed.single.ref, actual, scope);
465
+ return true;
466
+ }
467
+ if (typeof actual !== "string" && typeof actual !== "number") return false;
468
+ const text = String(actual);
469
+ const found = parsed.pattern.exec(text);
470
+ if (!found) return false;
471
+ for (const entry of parsed.refs) {
472
+ if (!entry.ref) continue;
473
+ if (!recordRef(entry.ref, found[entry.index + 1], scope)) return false;
474
+ }
475
+ return true;
476
+ }
477
+ function isPlainObject(value) {
478
+ return value !== null && typeof value === "object" && !Array.isArray(value);
479
+ }
480
+ /**
481
+ * Deep structural equality with matcher / placeholder support. Ref captures
482
+ * are recorded in `scope` in traversal order (arrays left-to-right, object
483
+ * keys in expected-key order).
484
+ */
485
+ function structuralEquals(expected, actual, scope) {
486
+ if (expected instanceof Matcher) return matcherMatches(expected, actual, scope);
487
+ if (typeof expected === "string" && hasPlaceholders(expected)) return placeholderStringMatches(expected, actual, scope);
488
+ if (Array.isArray(expected)) {
489
+ if (!Array.isArray(actual) || actual.length !== expected.length) return false;
490
+ return expected.every((item, i) => structuralEquals(item, actual[i], scope));
491
+ }
492
+ if (isPlainObject(expected)) {
493
+ if (!isPlainObject(actual)) return false;
494
+ const expectedKeys = Object.keys(expected);
495
+ const actualKeys = Object.keys(actual);
496
+ if (expectedKeys.length !== actualKeys.length) return false;
497
+ return expectedKeys.every((key) => key in actual && structuralEquals(expected[key], actual[key], scope));
498
+ }
499
+ return Object.is(expected, actual);
500
+ }
501
+ /**
502
+ * Deep structural SUBSET match (toMatchObject-style) with matcher /
503
+ * placeholder support. Plain objects match when every expected key is present
504
+ * and recursively subset-matches — the actual value may carry extra keys.
505
+ * Arrays require equal length with each element subset-matched. Leaves fall
506
+ * back to {@link structuralEquals} semantics (matchers, placeholders, strict
507
+ * equality). Used by request-body filters on intercept triggers.
508
+ */
509
+ function structuralSubset(expected, actual, scope) {
510
+ if (expected instanceof Matcher) return matcherMatches(expected, actual, scope);
511
+ if (typeof expected === "string" && hasPlaceholders(expected)) return placeholderStringMatches(expected, actual, scope);
512
+ if (Array.isArray(expected)) {
513
+ if (!Array.isArray(actual) || actual.length !== expected.length) return false;
514
+ return expected.every((item, i) => structuralSubset(item, actual[i], scope));
515
+ }
516
+ if (isPlainObject(expected)) {
517
+ if (!isPlainObject(actual)) return false;
518
+ return Object.keys(expected).every((key) => key in actual && structuralSubset(expected[key], actual[key], scope));
519
+ }
520
+ return Object.is(expected, actual);
521
+ }
522
+ /**
523
+ * Multi-line text comparison with `{{token}}` support — used by text
524
+ * snapshots (`_expected/*.txt`). Without placeholders this is strict equality.
525
+ */
526
+ function textEquals(expected, actual, scope) {
527
+ if (!hasPlaceholders(expected)) return expected === actual;
528
+ return placeholderStringMatches(expected, actual, scope);
529
+ }
530
+ //#endregion
531
+ //#region src/specification/contracts/queue.ts
532
+ /**
533
+ * The ONE contract queue — pure, engine-agnostic (no MSW, no node:http).
534
+ * Both engines consume it: the MSW integration on api/jobs chains, and the
535
+ * declared stub backend on website/mobile chains.
536
+ *
537
+ * Selection: the FIRST contract in declaration order that matches the observed
538
+ * request and is not exhausted. A contract with no `times` is unlimited (a
539
+ * re-render or a retry replays it); `times: n` is spent after n serves, so an
540
+ * ordered sequence is written as finite contracts before an unlimited tail:
541
+ * `[error500 ×3, ok]`.
542
+ *
543
+ * Strictness (CONVENTIONS D7): when nothing matches — including "everything
544
+ * that matches is exhausted" — the engine answers 501, records the request,
545
+ * and the chain fails with {@link ContractQueue.unmatchedError}. A chain that
546
+ * declared zero contracts is not guarded at all (unchanged boundary).
547
+ */
548
+ /** Base used to parse origin-relative observed URLs (`/events?x=1`). */
549
+ const RELATIVE_BASE = "http://contract.invalid";
550
+ /** Split a declared url into its base (origin+path, or path) and query halves.
551
+ * Never through `new URL()`, which would percent-encode `{{token}}` braces. */
552
+ function splitDeclared(url) {
553
+ const separator = url.indexOf("?");
554
+ if (separator === -1) return {
555
+ base: url,
556
+ query: new URLSearchParams()
557
+ };
558
+ return {
559
+ base: url.slice(0, separator),
560
+ query: new URLSearchParams(url.slice(separator + 1))
561
+ };
562
+ }
563
+ /** Decode percent-escapes, falling back to the raw text on malformed input. */
564
+ function safeDecode(text) {
565
+ try {
566
+ return decodeURIComponent(text);
567
+ } catch {
568
+ return text;
569
+ }
570
+ }
571
+ /** Token-aware comparison of one declared value against an observed one. */
572
+ function valueMatches(declared, observed) {
573
+ return textEquals(declared, observed, new CaptureScope());
574
+ }
575
+ /**
576
+ * Does an observed URL satisfy a declared one? A RegExp tests the full URL; a
577
+ * PATH FORM (`/articles/{{uuid}}`) ignores the origin; an absolute string
578
+ * compares origin+pathname. In both string forms `{{token}}` segments compare
579
+ * structurally and declared query params are a SUBSET of the observed ones.
580
+ */
581
+ function urlMatches(declared, observed) {
582
+ if (declared instanceof RegExp) return declared.test(observed);
583
+ let url;
584
+ try {
585
+ url = new URL(observed, RELATIVE_BASE);
586
+ } catch {
587
+ return false;
588
+ }
589
+ const { base, query } = splitDeclared(declared);
590
+ const observedBase = base.startsWith("/") ? url.pathname : `${url.origin}${url.pathname}`;
591
+ const decodedBase = base.startsWith("/") ? safeDecode(url.pathname) : `${url.origin}${safeDecode(url.pathname)}`;
592
+ if (!valueMatches(base, observedBase) && !valueMatches(base, decodedBase)) return false;
593
+ for (const key of new Set(query.keys())) {
594
+ const observedValues = url.searchParams.getAll(key);
595
+ if (!query.getAll(key).every((value) => observedValues.some((actual) => valueMatches(value, actual)))) return false;
596
+ }
597
+ return true;
598
+ }
599
+ /**
600
+ * Does an observed request satisfy a contract? Method (`*` matches any), URL,
601
+ * then the contract's own `match` predicate (headers/query/body filters).
602
+ */
603
+ function contractMatches(contract, request) {
604
+ const { match, method, url } = contract.request;
605
+ if (method !== "*" && method.toUpperCase() !== request.method.toUpperCase()) return false;
606
+ if (!urlMatches(url, request.url)) return false;
607
+ return match ? match(request) : true;
608
+ }
609
+ /**
610
+ * The URL pattern an out-of-process router (MSW) must register so the request
611
+ * REACHES the queue. Deliberately no narrower than {@link contractMatches} —
612
+ * the predicate above stays the authority on what actually matches.
613
+ */
614
+ function routePatternOf(declared) {
615
+ if (declared instanceof RegExp) return declared;
616
+ const { base } = splitDeclared(declared);
617
+ if (base.startsWith("/")) return new RegExp(String.raw`^https?:\/\/[^/?#]+${placeholderPatternSource(base)}(?:\?[^#]*)?(?:#.*)?$`, "u");
618
+ if (hasPlaceholders(base)) return new RegExp(String.raw`^${placeholderPatternSource(base)}(?:\?[^#]*)?(?:#.*)?$`, "u");
619
+ return base;
620
+ }
621
+ /** How a declared contract reads in a failure message: spent, served, or silent. */
622
+ function stateOf({ contract, served }) {
623
+ const { times } = contract;
624
+ if (times !== void 0 && served >= times) return ` (exhausted after ${times})`;
625
+ return served === 0 ? "" : ` (served ${served} time(s))`;
626
+ }
627
+ var ContractQueue = class {
628
+ entries;
629
+ constructor(contracts) {
630
+ this.entries = contracts.map((contract) => ({
631
+ contract,
632
+ served: 0
633
+ }));
634
+ }
635
+ /** How many contracts the chain declared. */
636
+ get size() {
637
+ return this.entries.length;
638
+ }
639
+ /**
640
+ * Routes to register with an out-of-process router, deduped by pattern —
641
+ * two contracts on the same URL share one handler and one queue.
642
+ */
643
+ get routes() {
644
+ const routes = /* @__PURE__ */ new Map();
645
+ for (const { contract } of this.entries) {
646
+ const url = routePatternOf(contract.request.url);
647
+ const key = String(url);
648
+ const route = routes.get(key) ?? {
649
+ methods: [],
650
+ url
651
+ };
652
+ if (!route.methods.includes(contract.request.method)) route.methods.push(contract.request.method);
653
+ routes.set(key, route);
654
+ }
655
+ return [...routes.values()];
656
+ }
657
+ /** The declared routes, in order — the enumeration a 501 body carries. */
658
+ declaredRoutes() {
659
+ return this.entries.map(({ contract }) => describeRoute(contract));
660
+ }
661
+ /**
662
+ * Serve the first contract in declaration order that matches and is not
663
+ * exhausted, or null when nothing matches (including "everything that
664
+ * matches is spent") — the strict-violation signal.
665
+ */
666
+ take(request) {
667
+ for (const entry of this.entries) {
668
+ const { times } = entry.contract;
669
+ if (times !== void 0 && entry.served >= times) continue;
670
+ if (!contractMatches(entry.contract, request)) continue;
671
+ entry.served += 1;
672
+ return entry.contract;
673
+ }
674
+ return null;
675
+ }
676
+ /**
677
+ * The chain-end failure for contracts declared `required: true` that were
678
+ * never requested (or not exactly `times` times), or null when every
679
+ * requirement held.
680
+ */
681
+ requiredError() {
682
+ const unmet = [];
683
+ for (const { contract, served } of this.entries) {
684
+ if (!contract.required) continue;
685
+ const { times } = contract;
686
+ if (times === void 0) {
687
+ if (served === 0) unmet.push(` - ${describeRoute(contract)} — declared and required but never requested`);
688
+ } else if (served !== times) unmet.push(` - ${describeRoute(contract)} — declared required with times: ${times} but was requested ${served} time(s)`);
689
+ }
690
+ if (unmet.length === 0) return null;
691
+ return /* @__PURE__ */ new Error(`Required contract(s) never satisfied during the chain:\n${unmet.join("\n")}\nA required contract states the call MUST happen — either the code no longer makes it, or the contract no longer describes it.`);
692
+ }
693
+ /**
694
+ * The strict failure for a request that matched no contract (CONVENTIONS
695
+ * D7): method + URL of the offending request, plus every declared contract
696
+ * and how often it was served.
697
+ */
698
+ unmatchedError(method, url) {
699
+ const declared = this.entries.length === 0 ? " (no contracts declared)" : this.entries.map((entry) => ` - ${describeRoute(entry.contract)}${stateOf(entry)}`).join("\n");
700
+ return /* @__PURE__ */ new Error(`Unmatched outgoing HTTP request during spec: ${method} ${url}\nDeclared contracts:\n${declared}\nEvery outgoing request of a chain that declares contracts must match one — add a contract for it (or raise its \`times\` when it is exhausted).`);
701
+ }
702
+ };
703
+ //#endregion
704
+ //#region src/specification/timing/pause.ts
705
+ /**
706
+ * One answer to "wait" — the only `setTimeout` the model owns.
707
+ *
708
+ * Two things in the framework genuinely have to wait: the spacing between the
709
+ * pieces of a declared stream, and the poll behind `waitUntil`. Everything
710
+ * else that waits is a spec doing it by hand, which is what J2 refuses. Stated
711
+ * once so there is one place to look when time stops behaving.
712
+ */
713
+ async function pause(ms) {
714
+ await new Promise((resolve) => {
715
+ setTimeout(resolve, ms);
716
+ });
717
+ }
718
+ //#endregion
719
+ //#region src/specification/contracts/stream.ts
720
+ /**
721
+ * A declared stream, made real — ONE serialisation for all three engines.
722
+ *
723
+ * msw's server and msw's worker take a `ReadableStream` body verbatim
724
+ * (https://mswjs.io/docs/http/mocking-responses/streaming) and the `node:http`
725
+ * stub pipes one into its response, so what "arriving in pieces" MEANS —
726
+ * the order, the spacing, the close after the last chunk — is stated here and
727
+ * nowhere else. A second copy of it would be a second answer to "what does the
728
+ * subject read", and the facets would drift.
729
+ */
730
+ /**
731
+ * The pieces of `body`, in order, `delayBetweenChunks` milliseconds apart,
732
+ * closing after the last one.
733
+ */
734
+ function toReadableStream(body) {
735
+ const encoder = new TextEncoder();
736
+ let index = 0;
737
+ return new ReadableStream({ async pull(controller) {
738
+ const chunk = body.chunks[index];
739
+ if (chunk === void 0) {
740
+ controller.close();
741
+ return;
742
+ }
743
+ if (body.delayBetweenChunks > 0 && index > 0) await pause(body.delayBetweenChunks);
744
+ index += 1;
745
+ controller.enqueue(encoder.encode(chunk));
746
+ } });
747
+ }
748
+ //#endregion
749
+ //#region src/specification/contracts/types.ts
750
+ /**
751
+ * The marker that tells a STREAMED body from a value that happens to be an
752
+ * object. A body reaches three different engines (msw's server, msw's worker,
753
+ * the `node:http` stub) and each of them serialises "an object" as JSON, so a
754
+ * stream declared as a plain value arrives as `{}`. The tag is what each
755
+ * engine recognises before it reaches for `JSON.stringify`.
756
+ */
757
+ const STREAM_BODY = "@jterrazz/test:stream";
758
+ /** Is this body a declared stream rather than a value to serialise? */
759
+ function isStreamBody(body) {
760
+ return typeof body === "object" && body !== null && "kind" in body && body.kind === "@jterrazz/test:stream";
761
+ }
762
+ //#endregion
763
+ //#region src/integrations/msw/handlers.ts
764
+ /**
765
+ * A contract answers the request that was made, never a copy of an earlier one.
766
+ *
767
+ * In a page the reply travels through a real service worker and a real HTTP
768
+ * cache, so a second render of the same component can be served the FIRST
769
+ * test's answer and never reach the queue at all — a contract that was
770
+ * exhausted, or replaced, silently keeps answering. Stated as a default, so a
771
+ * spec whose subject IS caching can still say otherwise.
772
+ */
773
+ const NEVER_CACHED = { "cache-control": "no-store" };
774
+ /** Turn a contract response into the msw reply, body kind by body kind. */
775
+ function toMswResponse(msw, response) {
776
+ const { body, headers, status = 200 } = response;
777
+ if (response.transport === "network-error") return msw.HttpResponse.error();
778
+ if (body === null || body === void 0) return new msw.HttpResponse(null, {
779
+ headers: {
780
+ ...NEVER_CACHED,
781
+ ...headers
782
+ },
783
+ status
784
+ });
785
+ if (isStreamBody(body)) return new msw.HttpResponse(toReadableStream(body), {
786
+ headers: {
787
+ ...NEVER_CACHED,
788
+ "content-type": body.contentType,
789
+ ...headers
790
+ },
791
+ status
792
+ });
793
+ if (typeof body === "string") return new msw.HttpResponse(body, {
794
+ headers: {
795
+ ...NEVER_CACHED,
796
+ "content-type": "text/plain; charset=utf-8",
797
+ ...headers
798
+ },
799
+ status
800
+ });
801
+ return msw.HttpResponse.json(body, {
802
+ headers: {
803
+ ...NEVER_CACHED,
804
+ ...headers
805
+ },
806
+ status
807
+ });
808
+ }
809
+ /**
810
+ * The handlers one chain's contracts become, plus the trailing catch-all that
811
+ * records any request no contract accepted (CONVENTIONS D7). The caller decides
812
+ * what to do with the recorded violation — the api chain rethrows it, the
813
+ * component chain fails the render. An EMPTY contract list is still a guard:
814
+ * the catch-all alone says "this subject has no network".
815
+ *
816
+ * `bypass` names the traffic that is not the subject's: under node there is
817
+ * none, in a page it is everything the runner fetches to BE a page.
818
+ */
819
+ function buildContractHandlers(msw, contracts, bypass) {
820
+ const queue = new ContractQueue(contracts);
821
+ let violation = null;
822
+ const recordViolation = (method, url) => {
823
+ violation ??= queue.unmatchedError(method, url);
824
+ return msw.HttpResponse.json({ error: `@jterrazz/test strict contracts: unmatched request ${method} ${url}` }, {
825
+ headers: NEVER_CACHED,
826
+ status: 501
827
+ });
828
+ };
829
+ const handlers = [];
830
+ for (const route of queue.routes) for (const method of route.methods) {
831
+ const handlerFn = method === "*" ? msw.http.all : msw.http[method.toLowerCase()];
832
+ if (!handlerFn) continue;
833
+ handlers.push(handlerFn(route.url, async ({ request }) => {
834
+ const observed = await observe(request);
835
+ const contract = queue.take(observed);
836
+ if (!contract) return recordViolation(request.method, request.url);
837
+ const response = typeof contract.response === "function" ? contract.response(observed) : contract.response;
838
+ if (response.delay) await new Promise((resolve) => setTimeout(resolve, response.delay));
839
+ return toMswResponse(msw, response);
840
+ }));
841
+ }
842
+ handlers.push(msw.http.all("*", ({ request }) => bypass?.(request.url) === true ? msw.passthrough() : recordViolation(request.method, request.url)));
843
+ return {
844
+ handlers,
845
+ violation: () => violation ?? queue.requiredError()
846
+ };
847
+ }
848
+ /** The request as the queue matches it — body parsed when it is JSON. */
849
+ async function observe(request) {
850
+ let body = null;
851
+ const rawText = await request.clone().text();
852
+ if (rawText) try {
853
+ body = JSON.parse(rawText);
854
+ } catch {
855
+ body = rawText;
856
+ }
857
+ const headers = {};
858
+ request.headers.forEach((value, key) => {
859
+ headers[key.toLowerCase()] = value;
860
+ });
861
+ return {
862
+ body,
863
+ headers,
864
+ method: request.method.toUpperCase(),
865
+ url: request.url
866
+ };
867
+ }
868
+ //#endregion
869
+ //#region src/integrations/msw/worker.ts
870
+ /**
871
+ * What the runner itself fetches. Everything else a page asks for is the
872
+ * subject's own traffic and answers to its contracts (D7).
873
+ */
874
+ const RUNNER_PREFIXES = [
875
+ "/.artifacts/",
876
+ "/@fs/",
877
+ "/@id/",
878
+ "/@vite",
879
+ "/node_modules/",
880
+ "/__vitest"
881
+ ];
882
+ let workerInstance = null;
883
+ /**
884
+ * Is this the runner's own traffic rather than the subject's?
885
+ *
886
+ * In a page EVERY module is an HTTP request: the test file, the seam, the
887
+ * dependency cache Vite optimised, the runner's own channel. None of them is
888
+ * the component's network, and none of them can be declared by a contract, so
889
+ * they are recognised by PREFIX — never by extension, because msw bypasses a
890
+ * "common asset" path before `onUnhandledRequest` ever runs and an extension
891
+ * test would let a real `/api/posts.json` through on the same ground.
892
+ */
893
+ function isRunnerRequest(url) {
894
+ const { pathname } = new URL(url);
895
+ return RUNNER_PREFIXES.some((prefix) => pathname.startsWith(prefix));
896
+ }
897
+ /**
898
+ * Start the worker once per page. The script is served at `/mockServiceWorker.js`
899
+ * by the plugin `component()` registers, out of the package's OWN `msw`
900
+ * install — so no consumer ever runs `msw init` and no consumer declares `msw`.
901
+ */
902
+ async function ensureContractWorker() {
903
+ if (workerInstance !== null) return;
904
+ const { setupWorker } = await import("msw/browser");
905
+ workerInstance = setupWorker();
906
+ await workerInstance.start({
907
+ onUnhandledRequest: (request, print) => {
908
+ if (!isRunnerRequest(request.url)) print.error();
909
+ },
910
+ quiet: true,
911
+ serviceWorker: { url: "/mockServiceWorker.js" }
912
+ });
913
+ }
914
+ /**
915
+ * Register one render's contracts on the page's worker.
916
+ *
917
+ * The worker starts even when the list is empty: on this facet D7 is TOTAL —
918
+ * a component that was given no contract has no network, and a fetch it makes
919
+ * anyway is named by {@link ContractRegistration.violation} rather than
920
+ * answered by whatever the dev server happens to have at that path.
921
+ */
922
+ async function registerWorkerContracts(contracts) {
923
+ await ensureContractWorker();
924
+ const { handlers, violation } = buildContractHandlers(await import("msw"), contracts, isRunnerRequest);
925
+ workerInstance.use(...handlers);
926
+ return {
927
+ cleanup: () => {
928
+ workerInstance.resetHandlers();
929
+ },
930
+ violation
931
+ };
932
+ }
933
+ /** Drop every handler the page still carries — the per-test reset. */
934
+ function resetWorkerContracts() {
935
+ if (workerInstance !== null) workerInstance.resetHandlers();
936
+ }
937
+ //#endregion
938
+ //#region src/specification/facets/_common/ground.ts
939
+ /**
940
+ * The GROUND a row of specs stands on — the naming law of a spec tree.
941
+ *
942
+ * In a row of specs, a MEMBER is a spec: `<aspect>.test.ts`, `<case>.spec.yaml`,
943
+ * `<name>.specification.ts`, and the facet/domain folders that hold them.
944
+ * Everything else in that row is what the members STAND ON — inert material the
945
+ * framework resolves BY PATH, never imported, never executed — and it carries a
946
+ * LEADING UNDERSCORE. A spec's own folder never does.
947
+ *
948
+ * Four names, and only four: `_fixtures/` (file state), `_expected/` (goldens),
949
+ * `_requests/` (inputs), `_seeds/` (database state). `contracts/` is NOT ground —
950
+ * a contract is TypeScript a spec imports, behaviour composed with the spec's own,
951
+ * so it stays a member. `docker/` is not ground either: it sits at the PROJECT
952
+ * root beside `package.json`, outside any row of specs.
953
+ *
954
+ * This module is the single home of those names. Every resolver, matcher, lint
955
+ * rule and checker pass reads them from here, so the runtime and the static
956
+ * channels cannot disagree about where a spec's ground lives.
957
+ */
958
+ /** Goldens: every expected fixture, flat, extension included. */
959
+ const GROUND_EXPECTED = "_expected";
960
+ //#endregion
961
+ //#region src/specification/facets/_common/reporter.ts
962
+ const GREEN = "\x1B[32m";
963
+ const RED = "\x1B[31m";
964
+ const RESET = "\x1B[0m";
965
+ const strictEquals = (expected, actual) => expected === actual;
966
+ function renderLines(expectedLines, actualLines, equals) {
967
+ const rendered = [];
968
+ let marked = 0;
969
+ const maxLines = Math.max(expectedLines.length, actualLines.length);
970
+ for (let i = 0; i < maxLines; i++) {
971
+ const exp = expectedLines[i];
972
+ const act = actualLines[i];
973
+ if (exp !== void 0 && act !== void 0 && equals(exp, act)) {
974
+ rendered.push(` ${exp}`);
975
+ continue;
976
+ }
977
+ marked++;
978
+ if (exp !== void 0) rendered.push(`${GREEN}- ${exp}${RESET}`);
979
+ if (act !== void 0) rendered.push(`${RED}+ ${act}${RESET}`);
980
+ }
981
+ return {
982
+ marked,
983
+ rendered
984
+ };
985
+ }
986
+ /**
987
+ * Render an expected/received diff over two texts.
988
+ *
989
+ * `equals` is how a line is judged EQUAL. Callers that compare through the
990
+ * `{{token}}` grammar pass a token-aware predicate, so a `{{url}}` line that
991
+ * matched is shown as equal — with its token, not as a `-`/`+` pair against
992
+ * the concrete URL. Marking a line the comparison ACCEPTED buries the one it
993
+ * rejected: the reader then has to work out which of the differences is the
994
+ * actual cause.
995
+ *
996
+ * Safety net: if the token-aware pass marks nothing at all, the whole diff
997
+ * would render as a clean block against a failure that really happened (a
998
+ * `#ref` captured inconsistently across lines, say). The strict rendering is
999
+ * used instead, so a diff always shows the reader something.
1000
+ */
1001
+ function formatStdoutDiff(file, expected, actual, options) {
1002
+ const lines = [];
1003
+ lines.push(`Output mismatch (${file})`, "", `${GREEN}- Expected${RESET}`, `${RED}+ Received${RESET}`, "");
1004
+ const expectedLines = expected.split("\n");
1005
+ const actualLines = actual.split("\n");
1006
+ const equals = options?.equals ?? strictEquals;
1007
+ const first = renderLines(expectedLines, actualLines, equals);
1008
+ const rendered = first.marked === 0 && equals !== strictEquals ? renderLines(expectedLines, actualLines, strictEquals).rendered : first.rendered;
1009
+ return [...lines, ...rendered].join("\n");
1010
+ }
1011
+ //#endregion
1012
+ //#region src/specification/facets/_common/result/text-assertions.ts
1013
+ /** The fixture name carries its extension — the name IS the file. */
1014
+ function requireExtension(name, subject) {
1015
+ if (!/\.[A-Za-z0-9]+$/u.test(name)) throw new Error(`toMatch("${name}"): the extension is part of the name and is required for ${subject} subjects (e.g. "help.txt").`);
1016
+ }
1017
+ /**
1018
+ * Compare a captured stream against the CONTENT of its golden. Text snapshots
1019
+ * share the unified `{{token}}` grammar (CONVENTIONS D4), and the diff judges
1020
+ * each line through the SAME grammar the comparison used — so a token line
1021
+ * that matched is shown as equal instead of competing with the real mismatch
1022
+ * for the reader's attention.
1023
+ */
1024
+ function compareStreamText(accessor, name, expected) {
1025
+ const actual = accessor.comparableText;
1026
+ if (textEquals(expected, actual, accessor.captures)) return {
1027
+ message: () => `expected ${accessor.streamName} not to match _expected/${name}`,
1028
+ pass: true
1029
+ };
1030
+ return {
1031
+ message: () => formatStdoutDiff(name, expected, actual, { equals: (expectedLine, actualLine) => textEquals(expectedLine, actualLine, new CaptureScope(accessor.captures.workdir)) }),
1032
+ pass: false
1033
+ };
1034
+ }
1035
+ /** `expect(stream).toBeEmpty()` — the stream you usually want silent. */
1036
+ function textIsEmpty(accessor) {
1037
+ const content = accessor.comparableText;
1038
+ const pass = content === "";
1039
+ return {
1040
+ message: () => pass ? `expected ${accessor.streamName} not to be empty` : `Expected ${accessor.streamName} to be empty, but it contains:\n${content}`,
1041
+ pass
1042
+ };
1043
+ }
1044
+ /** `expect(stream).toContain('…')` — the scalpel, never the default (D11). */
1045
+ function textContains(accessor, expected) {
1046
+ const actual = accessor.comparableText;
1047
+ const pass = actual.includes(expected);
1048
+ return {
1049
+ message: () => pass ? `expected ${accessor.streamName} not to contain ${JSON.stringify(expected)}` : `${accessor.streamName} does not contain expected substring.\n expected to contain: ${JSON.stringify(expected)}\n actual: ${JSON.stringify(actual.length > 500 ? `${actual.slice(0, 500)}…` : actual)}`,
1050
+ pass
1051
+ };
1052
+ }
1053
+ /**
1054
+ * `toMatch` and `toContain` on a subject that is NOT an accessor.
1055
+ *
1056
+ * Both matchers are overridden globally, for every subject in the project, so
1057
+ * whatever the framework does not own has to keep meaning what vitest's own
1058
+ * matcher meant. Stated once here because the two builds register two different
1059
+ * `expect.extend` calls: a copy in the page is how `expect(['ab']).toContain('b')`
1060
+ * ends up passing on one side of the seam and failing on the other.
1061
+ */
1062
+ /** vitest's `toMatch` for a plain string: a substring, or a regular expression. */
1063
+ function nativeMatch(received, expected) {
1064
+ if (typeof received !== "string") throw new TypeError("toMatch: unsupported subject — expected a stream, json, response, filesystem, or directory accessor, or a string.");
1065
+ const pass = expected instanceof RegExp ? expected.test(received) : received.includes(String(expected));
1066
+ return {
1067
+ message: () => `expected ${JSON.stringify(received)} ${pass ? "not " : ""}to match ${String(expected)}`,
1068
+ pass
1069
+ };
1070
+ }
1071
+ /** vitest's `toContain` for a plain string (substring) or an iterable (membership). */
1072
+ function nativeContain(received, expected) {
1073
+ if (typeof received === "string") {
1074
+ const pass = received.includes(String(expected));
1075
+ return {
1076
+ message: () => `expected ${JSON.stringify(received)} ${pass ? "not " : ""}to contain ${JSON.stringify(expected)}`,
1077
+ pass
1078
+ };
1079
+ }
1080
+ if (isIterable(received)) {
1081
+ const pass = [...received].includes(expected);
1082
+ return {
1083
+ message: () => `expected iterable ${pass ? "not " : ""}to contain ${JSON.stringify(expected)}`,
1084
+ pass
1085
+ };
1086
+ }
1087
+ throw new TypeError(`toContain: unsupported subject of type ${typeof received} — expected a stream accessor, string, or iterable.`);
1088
+ }
1089
+ /** Does this value hand out its members? A Set and an array both do; a DOM node does not. */
1090
+ function isIterable(value) {
1091
+ return value !== null && value !== void 0 && typeof value[Symbol.iterator] === "function";
1092
+ }
1093
+ //#endregion
1094
+ //#region src/specification/facets/_common/result/grep.ts
1095
+ /**
1096
+ * Extract text blocks from output that contain a pattern.
1097
+ * Splits by blank lines (how linter/compiler output is structured),
1098
+ * returns only blocks matching the pattern.
1099
+ *
1100
+ * @example
1101
+ * expect(grep(result.stdout, "unused-var.ts")).toContain("no-unused-vars")
1102
+ * expect(grep(result.stdout, "valid/sorted.ts")).not.toContain("sort-imports")
1103
+ */
1104
+ function grep(output, pattern) {
1105
+ return output.replaceAll(/\u001B\[[0-9;]*m/gu, "").split(/\n\s*\n/u).filter((block) => block.includes(pattern)).join("\n\n");
1106
+ }
1107
+ //#endregion
1108
+ //#region src/specification/facets/_common/result/text.ts
1109
+ const ANSI_RE = /\u001B\[[0-9;]*m/gu;
1110
+ /** Strip ANSI escape sequences from a string. */
1111
+ function stripAnsiCodes(value) {
1112
+ return value.replace(ANSI_RE, "");
1113
+ }
1114
+ /**
1115
+ * Read-only accessor for a captured text handle — THE universal one: stdout,
1116
+ * stderr, container logs, and file text all surface as a `TextAccessor`.
1117
+ *
1118
+ * Backed by a primitive string, exposed via {@link text}, but also provides
1119
+ * `toString()` / `valueOf()` for string coercion, so common patterns like
1120
+ * `String(result.stdout)` and template-literal interpolation still work.
1121
+ *
1122
+ * ANSI escape sequences are stripped by default before every comparison
1123
+ * (CONVENTIONS D6) — `.text` stays raw. The runner `transform` option remains
1124
+ * an escape hatch for application noise not covered by the `{{token}}`
1125
+ * grammar.
1126
+ *
1127
+ * Text operations are **closed** over the type: `.grep(pattern)` returns a
1128
+ * `TextAccessor` (not a bare string), preserving the `_expected/`-resolution
1129
+ * context and the `transform`, so results are chainable
1130
+ * (`result.stdout.grep(a).grep(b)`) and snapshot-able
1131
+ * (`expect(result.stdout.grep('users.ts')).toMatch('block.txt')`).
1132
+ *
1133
+ * Assertions go through `expect()` matchers: `expect(result.stdout).toContain(...)`
1134
+ * and `expect(result.stdout).toMatch('name.txt')` (resolved against
1135
+ * `_expected/<name>`, flat — with `{{token}}` support, CONVENTIONS D4).
1136
+ */
1137
+ var TextAccessor = class TextAccessor {
1138
+ /** @internal Ref-capture scope shared by the current spec execution. */
1139
+ captures;
1140
+ /** @internal Stream label used in failure messages ("stdout" / "stderr"). */
1141
+ streamName;
1142
+ /** @internal Test-file directory — fixture resolution root for matchers. */
1143
+ testDir;
1144
+ /** The raw captured text (never transformed, ANSI preserved). */
1145
+ text;
1146
+ /** @internal Normaliser applied before comparisons, never to fixtures. */
1147
+ transform;
1148
+ constructor(value, streamName, testDir, options = {}) {
1149
+ this.text = value;
1150
+ this.streamName = streamName;
1151
+ this.testDir = testDir;
1152
+ this.transform = options.transform;
1153
+ this.captures = options.captures ?? new CaptureScope();
1154
+ }
1155
+ /** @internal The text as compared by matchers — ANSI stripped, transform applied. */
1156
+ get comparableText() {
1157
+ const stripped = stripAnsiCodes(this.text);
1158
+ return this.transform ? this.transform(stripped) : stripped;
1159
+ }
1160
+ /**
1161
+ * Keep only the blank-line-separated blocks of the text that contain
1162
+ * `pattern` (how linter/compiler output is structured), returned as a new
1163
+ * `TextAccessor` — the same subject type, so the result is chainable and
1164
+ * snapshot-able. The scalpel for probing large tool outputs; snapshot the
1165
+ * whole surface by default, reach for `.grep()` for targeted checks.
1166
+ */
1167
+ grep(pattern) {
1168
+ return new TextAccessor(grep(this.text, pattern), this.streamName, this.testDir, {
1169
+ captures: this.captures,
1170
+ transform: this.transform
1171
+ });
1172
+ }
1173
+ toString() {
1174
+ return this.text;
1175
+ }
1176
+ valueOf() {
1177
+ return this.text;
1178
+ }
1179
+ };
1180
+ //#endregion
1181
+ //#region src/specification/facets/website/ambiguity.ts
1182
+ /**
1183
+ * The ambiguity refusal — CONVENTIONS W3.
1184
+ *
1185
+ * A visit descriptor must designate exactly one element. Acting on "the
1186
+ * first match" is the failure mode this module exists to prevent: the spec
1187
+ * keeps passing while the visitor clicks something else, and nothing ever
1188
+ * reports it. So when a descriptor matches several elements the framework
1189
+ * refuses, and the refusal has to carry everything needed to fix it without
1190
+ * opening a browser — the descriptor in the caller's own vocabulary, every
1191
+ * candidate, and the concrete rewrites that would resolve it.
1192
+ *
1193
+ * Pure string building: it takes captured data and returns a message, so the
1194
+ * wording is unit-testable and the browser integration stays a thin adapter.
1195
+ */
1196
+ /** `kind` → the constructor that builds it, so errors echo the caller's source. */
1197
+ const CONSTRUCTORS = {
1198
+ banner: "banner",
1199
+ button: "button",
1200
+ complementary: "complementary",
1201
+ contentinfo: "contentinfo",
1202
+ dialog: "dialog",
1203
+ field: "field",
1204
+ form: "form",
1205
+ heading: "heading",
1206
+ link: "link",
1207
+ listitem: "listitem",
1208
+ main: "main",
1209
+ navigation: "navigation",
1210
+ option: "option",
1211
+ region: "region",
1212
+ row: "row",
1213
+ search: "search",
1214
+ status: "status",
1215
+ table: "table",
1216
+ testId: "testId",
1217
+ text: "content"
1218
+ };
1219
+ /** The landmark a context string maps back to, for a copy-pasteable suggestion. */
1220
+ const CONTEXT_LANDMARKS = {
1221
+ aside: "complementary()",
1222
+ banner: "banner()",
1223
+ complementary: "complementary()",
1224
+ contentinfo: "contentinfo()",
1225
+ footer: "contentinfo()",
1226
+ form: "form()",
1227
+ header: "banner()",
1228
+ main: "main()",
1229
+ nav: "navigation()",
1230
+ navigation: "navigation()",
1231
+ search: "search()"
1232
+ };
1233
+ /**
1234
+ * Render a descriptor as the source that would build it — `link('Articles')`,
1235
+ * `within(navigation(), link('Articles', { exact: true }))`. The error speaks
1236
+ * the vocabulary the author wrote, never playwright's.
1237
+ */
1238
+ function formatElement(element) {
1239
+ const bare = formatBare(element);
1240
+ return element.scope ? `within(${formatElement(element.scope)}, ${bare})` : bare;
1241
+ }
1242
+ function formatBare(element) {
1243
+ const args = [];
1244
+ if (element.name !== void 0) args.push(JSON.stringify(element.name));
1245
+ if (element.exact) args.push("{ exact: true }");
1246
+ return `${CONSTRUCTORS[element.kind]}(${args.join(", ")})`;
1247
+ }
1248
+ /** `1. <a href="/articles">Articles</a> in <nav>` — one evidence line per candidate. */
1249
+ function formatMatch(match, index) {
1250
+ const attribute = match.detail ? ` ${quoteDetail(match)}` : "";
1251
+ const named = match.accessibleName ? ` named ${JSON.stringify(match.accessibleName)}` : "";
1252
+ const context = match.context ? ` in <${match.context}>` : "";
1253
+ return ` ${index + 1}. <${match.tag}${attribute}>${match.text}</${match.tag}>${named}${context}`;
1254
+ }
1255
+ function quoteDetail(match) {
1256
+ return `${match.tag === "a" ? "href" : "name"}=${JSON.stringify(match.detail)}`;
1257
+ }
1258
+ /** Each landmark the candidates sit in, and how many of them it holds. */
1259
+ function landmarkCounts(matches) {
1260
+ const counts = /* @__PURE__ */ new Map();
1261
+ for (const match of matches) {
1262
+ const landmark = match.context === void 0 ? void 0 : CONTEXT_LANDMARKS[match.context];
1263
+ if (landmark !== void 0) counts.set(landmark, (counts.get(landmark) ?? 0) + 1);
1264
+ }
1265
+ return [...counts].toSorted(([, a], [, b]) => a - b);
1266
+ }
1267
+ /**
1268
+ * The rewrites worth offering, in the order they should be tried. Scoping is
1269
+ * always available; `exact` only when it would actually narrow the set, and
1270
+ * the count it would leave is stated so a still-ambiguous suggestion never
1271
+ * reads as a fix.
1272
+ */
1273
+ function formatFixes(element, matches) {
1274
+ const fixes = [];
1275
+ const narrowing = landmarkCounts(matches).filter(([, count]) => count < matches.length);
1276
+ if (!element.scope) {
1277
+ const [first, ...rest] = narrowing;
1278
+ const alsoHere = rest.length > 0 ? ` [also here: ${rest.map(([name]) => name).join(", ")}]` : "";
1279
+ fixes.push(first === void 0 ? `scope it within(<a container holding only this one>, ${formatBare(element)})` : `scope it within(${first[0]}, ${formatBare(element)}) [leaves ${first[1]} of ${matches.length}]${alsoHere}`);
1280
+ }
1281
+ if (!element.exact && element.name !== void 0) {
1282
+ const remaining = matches.filter((match) => match.text === element.name).length;
1283
+ if (remaining > 0 && remaining < matches.length) fixes.push(`exact name ${formatBare({
1284
+ ...element,
1285
+ exact: true
1286
+ })} [leaves ${remaining} of ${matches.length}]`);
1287
+ }
1288
+ fixes.push("other element a heading(), button() or field() may name one thing where this does not");
1289
+ return fixes;
1290
+ }
1291
+ /**
1292
+ * The W3 refusal. A distinct class so the visit wrapper can recognize an
1293
+ * already-complete message and let it through instead of nesting it inside
1294
+ * `visit scenario failed: …`, which would print the whole thing twice.
1295
+ */
1296
+ var AmbiguousElementError = class extends Error {
1297
+ name = "AmbiguousElementError";
1298
+ };
1299
+ /**
1300
+ * Build the refusal thrown when a descriptor matches more than one element.
1301
+ *
1302
+ * @param options.element The descriptor as the caller wrote it.
1303
+ * @param options.matches Every candidate, in DOM order (already truncated).
1304
+ * @param options.url The page the visitor was on when it happened.
1305
+ */
1306
+ function describeAmbiguity(options) {
1307
+ const { element, matches, url } = options;
1308
+ const fixes = formatFixes(element, matches).map((fix) => ` • ${fix}`);
1309
+ return [
1310
+ `Ambiguous element: ${formatElement(element)} matched ${matches.length} elements on ${url}.`,
1311
+ "",
1312
+ "A spec must designate exactly one element. Acting on the first match would let",
1313
+ "this test keep passing while the visitor interacts with something else.",
1314
+ "",
1315
+ "Matched:",
1316
+ ...matches.map((match, index) => formatMatch(match, index)),
1317
+ "",
1318
+ "Disambiguate with one of:",
1319
+ ...fixes,
1320
+ "",
1321
+ "Docs: docs/14-website.md#designating-exactly-one-element (CONVENTIONS W3)"
1322
+ ].join("\n");
1323
+ }
1324
+ //#endregion
1325
+ //#region src/integrations/vitest-browser/vitest-browser.adapter.ts
1326
+ /**
1327
+ * The browser-mode adapter — the component facet's half of the one element
1328
+ * vocabulary.
1329
+ *
1330
+ * Its translation table is the playwright adapter's, descriptor for
1331
+ * descriptor: a `button('Save')` means `getByRole('button', { name })` whether
1332
+ * the surface is a served page or a mounted component, and the W3 refusal
1333
+ * enumerates candidates in the same words. Two adapters, one dialect — which
1334
+ * is the whole reason a page spec and a component spec read alike.
1335
+ *
1336
+ * What differs is where the code runs. Playwright drives a page from the
1337
+ * outside and reads it through `evaluate`; here the test IS in the page, so a
1338
+ * candidate is described from the live element and the ARIA tree is the one
1339
+ * thing that has to go back out (`server.commands`, the provider's own frame).
1340
+ */
1341
+ /** How many candidates the ambiguity error enumerates before truncating. */
1342
+ const MAX_REPORTED_MATCHES = 10;
1343
+ /** The landmark ancestors the ambiguity evidence names. */
1344
+ const LANDMARKS = "nav, header, footer, main, aside, section, form, [role]";
1345
+ /**
1346
+ * Translate a user-facing descriptor into a Browser Mode locator, resolving
1347
+ * `scope` outside-in so `within(navigation(), link('X'))` searches the nav
1348
+ * subtree. No `.first()` anywhere: designating exactly one element is
1349
+ * CONVENTIONS W3, and taking the first match is the silent wrong-element bug
1350
+ * the rule exists to prevent.
1351
+ */
1352
+ function locate(root, element) {
1353
+ const scope = element.scope ? locate(root, element.scope) : root;
1354
+ const exact = element.exact ?? false;
1355
+ const name = element.name ?? "";
1356
+ if (element.kind === "field") return scope.getByLabelText(name, { exact });
1357
+ if (element.kind === "testId") return scope.getByTestId(name);
1358
+ if (element.kind === "text") return scope.getByText(name, { exact });
1359
+ return scope.getByRole(element.kind, element.name === void 0 ? { exact } : {
1360
+ exact,
1361
+ name: element.name
1362
+ });
1363
+ }
1364
+ /** Describe the live candidates — the evidence the W3 refusal enumerates. */
1365
+ function candidates(locator) {
1366
+ return locator.elements().slice(0, MAX_REPORTED_MATCHES).map((node) => {
1367
+ const landmark = node.parentElement?.closest(LANDMARKS);
1368
+ const context = landmark?.getAttribute("role") ?? landmark?.tagName.toLowerCase();
1369
+ const detail = node.getAttribute("href") ?? node.getAttribute("name");
1370
+ const text = (node.textContent ?? "").replaceAll(/\s+/gu, " ").trim().slice(0, 80);
1371
+ const label = node.getAttribute("aria-label")?.trim();
1372
+ return {
1373
+ accessibleName: label !== void 0 && label !== text ? label : void 0,
1374
+ context: context ?? void 0,
1375
+ detail: detail ?? void 0,
1376
+ tag: node.tagName.toLowerCase(),
1377
+ text
1378
+ };
1379
+ });
1380
+ }
1381
+ /** Walk the scope chain outside-in; the outermost ambiguous level is the fault. */
1382
+ function ambiguousLevel(element) {
1383
+ const chain = [];
1384
+ for (let current = element; current; current = current.scope) chain.unshift(current);
1385
+ for (const level of chain.slice(0, -1)) if (locate(page, level).elements().length > 1) return level;
1386
+ return element;
1387
+ }
1388
+ /**
1389
+ * Run one visitor action, turning "more than one match" into the W3 refusal.
1390
+ * The ambiguous LEVEL is identified first: a scope matching several landmarks
1391
+ * is the real fault, and naming the target would send the author to fix the
1392
+ * wrong descriptor.
1393
+ */
1394
+ async function act(element, action) {
1395
+ const locator = locate(page, element);
1396
+ try {
1397
+ return await action(locator);
1398
+ } catch (error) {
1399
+ if (locator.elements().length <= 1) throw error;
1400
+ const culprit = ambiguousLevel(element);
1401
+ const matches = candidates(locate(page, culprit));
1402
+ const url = globalThis.location.href;
1403
+ throw new AmbiguousElementError(describeAmbiguity({
1404
+ element: culprit,
1405
+ matches,
1406
+ url
1407
+ }));
1408
+ }
1409
+ }
1410
+ /**
1411
+ * Is this descriptor answered by PRESENCE rather than by visibility?
1412
+ *
1413
+ * The options of a collapsed `<select>` are in the document and in the
1414
+ * accessibility tree, and not one of them has a box on the screen — asking
1415
+ * whether an option is visible would answer "no" for every select a visitor
1416
+ * never opened.
1417
+ */
1418
+ function byPresence(element) {
1419
+ return element.kind === "option";
1420
+ }
1421
+ /** A control's live value — the property, never the attribute. */
1422
+ function valueOf(node) {
1423
+ return node instanceof HTMLInputElement || node instanceof HTMLSelectElement || node instanceof HTMLTextAreaElement ? node.value : void 0;
1424
+ }
1425
+ /**
1426
+ * Is the element gone — or, with a state modifier, no longer in that state? A
1427
+ * node that left the document and one that is still there but not rendered are
1428
+ * the same answer to a spec.
1429
+ */
1430
+ function isGone(locator, element) {
1431
+ const node = locator.query();
1432
+ if (element.focused === true) return node !== document.activeElement;
1433
+ if (element.disabled !== void 0) return node === null || node.matches(":disabled") !== element.disabled;
1434
+ if (element.selected !== void 0) return node === null || node.matches(":checked") !== element.selected;
1435
+ if (element.value !== void 0) return node === null || valueOf(node) !== element.value;
1436
+ return node === null || (byPresence(element) ? false : !node.checkVisibility());
1437
+ }
1438
+ /**
1439
+ * How long `gone()` waits — what is LEFT of the running test's budget.
1440
+ *
1441
+ * Every other verb already gets it: a locator action and `expect.element`
1442
+ * default their timeout to the remaining budget, and only a bare
1443
+ * `expect.poll` falls back to vitest's one second. That second made `gone()`
1444
+ * the one verb that could not outlast a slow answer — a button taken off the
1445
+ * screen when a two-second request returns was "still on the screen".
1446
+ *
1447
+ * The 100ms margin is vitest's own: the poll has to give up just BEFORE the
1448
+ * test does, or the failure is a bare timeout naming no element.
1449
+ */
1450
+ function remainingBudget() {
1451
+ const current = TestRunner.getCurrentTest();
1452
+ const started = current?.result?.startTime;
1453
+ if (current === void 0 || started === void 0) return;
1454
+ return Math.max(current.timeout - (Date.now() - started) - 100, 0);
1455
+ }
1456
+ /** `expect.poll` over that budget — the retry the matchers get for free. */
1457
+ function polling(probe, message) {
1458
+ const timeout = remainingBudget();
1459
+ return expect.poll(probe, {
1460
+ message,
1461
+ ...timeout === void 0 ? {} : { timeout }
1462
+ });
1463
+ }
1464
+ /** A key name is a key; a single character is typed as itself. */
1465
+ function keystroke(key) {
1466
+ return key.length > 1 ? `{${key}}` : key;
1467
+ }
1468
+ /** The verbs a rendered surface shares with a page, plus the two a parent owns. */
1469
+ function componentVerbs(surface) {
1470
+ return {
1471
+ check: async (element) => {
1472
+ await act(element, async (locator) => {
1473
+ const node = locator.element();
1474
+ if (!(node instanceof HTMLInputElement) || !node.checked) await locator.click();
1475
+ });
1476
+ },
1477
+ click: async (element) => {
1478
+ await act(element, async (locator) => {
1479
+ await locator.click();
1480
+ });
1481
+ },
1482
+ fill: async (element, value) => {
1483
+ await act(element, async (locator) => {
1484
+ await locator.fill(value);
1485
+ });
1486
+ },
1487
+ gone: async (element) => {
1488
+ await act(element, async (locator) => {
1489
+ await polling(() => isGone(locator, element), `${formatElement(element)} is still on the screen`).toBeTruthy();
1490
+ });
1491
+ },
1492
+ hover: async (element) => {
1493
+ await act(element, async (locator) => {
1494
+ await locator.hover();
1495
+ });
1496
+ },
1497
+ press: async (key) => {
1498
+ await userEvent.keyboard(keystroke(key));
1499
+ },
1500
+ rerender: surface.rerender,
1501
+ see: async (element) => {
1502
+ await act(element, async (locator) => {
1503
+ if (element.focused === true) {
1504
+ await expect.element(locator).toHaveFocus();
1505
+ return;
1506
+ }
1507
+ if (element.disabled === true) {
1508
+ await expect.element(locator).toBeDisabled();
1509
+ return;
1510
+ }
1511
+ if (element.disabled === false) {
1512
+ await expect.element(locator).toBeEnabled();
1513
+ return;
1514
+ }
1515
+ if (element.selected !== void 0) {
1516
+ await polling(() => locator.query()?.matches(":checked") === true, `${formatElement(element)} is not the selected one`).toBe(element.selected);
1517
+ return;
1518
+ }
1519
+ if (element.value !== void 0) {
1520
+ await expect.element(locator).toHaveValue(element.value);
1521
+ return;
1522
+ }
1523
+ if (byPresence(element)) {
1524
+ await expect.element(locator).toBeInTheDocument();
1525
+ return;
1526
+ }
1527
+ await expect.element(locator).toBeVisible();
1528
+ });
1529
+ },
1530
+ select: async (element, option) => {
1531
+ await act(element, async (locator) => {
1532
+ await locator.selectOptions(option);
1533
+ });
1534
+ },
1535
+ unmount: surface.unmount
1536
+ };
1537
+ }
1538
+ /** The ARIA snapshot of the rendered `<body>` — the golden a tree is asserted as. */
1539
+ async function ariaTree() {
1540
+ return await commands.ariaTree();
1541
+ }
1542
+ /** A golden's content, read server-side from `_expected/` beside the test. */
1543
+ async function readGolden(name) {
1544
+ return await commands.goldenRead(name);
1545
+ }
1546
+ /** Write a golden server-side, and say where — update mode's half. */
1547
+ async function writeGolden(name, content) {
1548
+ return await commands.goldenWrite(name, content);
1549
+ }
1550
+ /** Mount a React subject through the optional `vitest-browser-react` adapter. */
1551
+ async function mountReact(ui) {
1552
+ let render;
1553
+ try {
1554
+ ({render} = await import("vitest-browser-react"));
1555
+ } catch (error) {
1556
+ throw new Error(`component.render(<X />) needs vitest-browser-react and react (optional peers): npm install -D vitest-browser-react react react-dom (${String(error)})`, { cause: error });
1557
+ }
1558
+ const rendered = await render(ui);
1559
+ return {
1560
+ container: rendered.container,
1561
+ rerender: rendered.rerender,
1562
+ unmount: rendered.unmount
1563
+ };
1564
+ }
1565
+ /**
1566
+ * Mount a vanilla DOM subject: the function is handed a fresh container and
1567
+ * may return its own teardown — the shape a DOM library states one in. There
1568
+ * is no react here, and no react is loaded.
1569
+ */
1570
+ function mountDom(mount) {
1571
+ const container = document.createElement("div");
1572
+ document.body.append(container);
1573
+ const teardown = mount(container);
1574
+ return {
1575
+ container,
1576
+ rerender: () => {
1577
+ throw new Error("rerender() replaces a React tree; a DOM function is re-rendered by calling it again in a new render().");
1578
+ },
1579
+ unmount: async () => {
1580
+ teardown?.();
1581
+ container.remove();
1582
+ await Promise.resolve();
1583
+ }
1584
+ };
1585
+ }
1586
+ //#endregion
1587
+ //#region src/integrations/vitest-browser/golden.ts
1588
+ /** Update mode crosses the seam as a provided value, never as an env read. */
1589
+ function updating() {
1590
+ return inject("update") === true;
1591
+ }
1592
+ async function matchGolden(accessor, name, frozen) {
1593
+ requireExtension(name, "stream");
1594
+ const actual = accessor.comparableText;
1595
+ const stored = await readGolden(name);
1596
+ if (stored === null) {
1597
+ if (updating() && !frozen) {
1598
+ const path = await writeGolden(name, actual);
1599
+ return {
1600
+ message: () => `wrote ${path}`,
1601
+ pass: true
1602
+ };
1603
+ }
1604
+ return {
1605
+ message: () => `${accessor.streamName} fixture "${name}" does not exist under ${GROUND_EXPECTED}/ beside this test.\nRun with TEST_UPDATE=1 (or vitest -u) to create it.`,
1606
+ pass: false
1607
+ };
1608
+ }
1609
+ const comparison = compareStreamText(accessor, name, stored);
1610
+ if (!comparison.pass && updating() && !frozen) {
1611
+ await writeGolden(name, actual);
1612
+ return {
1613
+ message: () => `updated ${GROUND_EXPECTED}/${name}`,
1614
+ pass: true
1615
+ };
1616
+ }
1617
+ return comparison;
1618
+ }
1619
+ async function toMatch(received, expected, options) {
1620
+ if (received instanceof TextAccessor) {
1621
+ if (typeof expected !== "string") throw new TypeError("toMatch on accessors takes a fixture name (extension included) — for a regex, assert on the raw text instead: expect(x.text).toMatch(/re/).");
1622
+ return await matchGolden(received, expected, options?.frozen === true);
1623
+ }
1624
+ return nativeMatch(received, expected);
1625
+ }
1626
+ function toContain(received, expected) {
1627
+ if (received instanceof TextAccessor) return textContains(received, String(expected));
1628
+ return nativeContain(received, expected);
1629
+ }
1630
+ function toBeEmpty(received) {
1631
+ if (!(received instanceof TextAccessor)) throw new TypeError("toBeEmpty: unsupported subject — expected a text accessor.");
1632
+ return textIsEmpty(received);
1633
+ }
1634
+ let registered = false;
1635
+ /**
1636
+ * Register the page's matchers with vitest's `expect`. Idempotent, and called
1637
+ * from the browser entry itself: a component test imports `@jterrazz/test` to
1638
+ * get `component`, and that import IS the registration.
1639
+ */
1640
+ function registerBrowserMatchers() {
1641
+ if (registered) return;
1642
+ registered = true;
1643
+ expect.extend({
1644
+ toBeEmpty,
1645
+ toContain,
1646
+ toMatch
1647
+ });
1648
+ }
1649
+ //#endregion
1650
+ //#region src/browser/node-only.ts
1651
+ /**
1652
+ * The refusals the browser build ships in place of what only node can do.
1653
+ *
1654
+ * `@jterrazz/test` has ONE specifier and two runtimes, so the page gets the
1655
+ * same NAMES as the server: a component test that reaches for
1656
+ * `specification.api()` or `postgres()` fails on the line that reached, saying
1657
+ * where that name runs — not on an unresolved import three layers down, and
1658
+ * not silently on `undefined`.
1659
+ */
1660
+ /**
1661
+ * The refusal, in one line, whatever the name. Returns `never`, so a stub is
1662
+ * an ordinary arrow function the page's entry annotates with the node
1663
+ * signature — no cast, and no way for the two surfaces to disagree.
1664
+ */
1665
+ function refuse(name) {
1666
+ throw new Error(`${name} runs under node: a page has no filesystem, no child process and no socket. Specify it from a test collected by a node project (unit/api/jobs/cli/website/mobile); a rendered thing is a \`.test.tsx\` beside its component.`);
1667
+ }
1668
+ /**
1669
+ * A node-only CLASS, present under the same name. A class has a shape a stub
1670
+ * cannot honour — every instance member of the real one — so this is the one
1671
+ * place the page's entry states a type it does not structurally satisfy; what
1672
+ * the value can actually do is throw, which is the whole of the contract.
1673
+ *
1674
+ * The stub is a constructible FUNCTION, never an arrow: `new` on an arrow
1675
+ * throws "is not a constructor" before the refusal can run, so the page would
1676
+ * lose the one thing the stub exists to say — which name it reached for.
1677
+ */
1678
+ const nodeOnlyClass = (name) => function NodeOnly() {
1679
+ return refuse(name);
1680
+ };
1681
+ //#endregion
1682
+ //#region src/integrations/vitest-browser/page-runtime.ts
1683
+ /**
1684
+ * The runner, as the page reaches it.
1685
+ *
1686
+ * `vitest` is the framework's one sanctioned coupling and it lives in the
1687
+ * layers that own a runner — `src/vitest/` for the config side, this seam for
1688
+ * the page's. The component model asks for "after this test", "pin the clock"
1689
+ * and "what did the project provide" and never learns which runner answers.
1690
+ */
1691
+ /** Run `teardown` when the current test ends, however it ends. No hook in the spec. */
1692
+ function afterThisTest(teardown) {
1693
+ onTestFinished(teardown);
1694
+ }
1695
+ /**
1696
+ * Freeze the page's `Date` at `iso`. `Date` ONLY: faking the page's timers
1697
+ * would stop React's scheduler and nothing would ever render.
1698
+ */
1699
+ function pinClock(iso) {
1700
+ vi.useFakeTimers({
1701
+ now: new Date(iso),
1702
+ toFake: ["Date"]
1703
+ });
1704
+ }
1705
+ /** Give the page its real clock back. */
1706
+ function releaseClock() {
1707
+ vi.useRealTimers();
1708
+ }
1709
+ /** The instant `component({ clock })` pinned for every render, if it did. */
1710
+ function providedClock() {
1711
+ return inject("componentClock");
1712
+ }
1713
+ /** The page size the project states — what a per-test `.viewport()` is restored to. */
1714
+ function providedViewport() {
1715
+ return inject("componentViewport");
1716
+ }
1717
+ /** Resize the page the test renders into. */
1718
+ async function setViewport(size) {
1719
+ await page.viewport(size.width, size.height);
1720
+ }
1721
+ /**
1722
+ * The project's `wrap`, left on `globalThis` by the setup module the project
1723
+ * loads. A shared symbol rather than an import: the setup module and this
1724
+ * bundle are two graphs in one page and share no module instance.
1725
+ */
1726
+ function projectWrapper() {
1727
+ const wrap = globalThis[Symbol.for("@jterrazz/test:component-wrap")];
1728
+ return typeof wrap === "function" ? wrap : void 0;
1729
+ }
1730
+ //#endregion
1731
+ //#region src/specification/facets/component/rendered-text.ts
1732
+ /**
1733
+ * A stream captured INSIDE the page.
1734
+ *
1735
+ * Structurally identical to any other {@link TextAccessor} — the same
1736
+ * `{{token}}` grammar, the same ANSI stripping, the same `.grep()` — and
1737
+ * marked so the matcher augmentation can say the one thing that differs: its
1738
+ * golden lives on the server, so `toMatch` is awaited here where it is
1739
+ * synchronous everywhere else.
1740
+ */
1741
+ var RenderedText = class extends TextAccessor {
1742
+ /** The marker the `toMatch` overload reads. Never asserted on directly. */
1743
+ capturedInPage = true;
1744
+ };
1745
+ //#endregion
1746
+ //#region src/specification/facets/component/component.result.ts
1747
+ /**
1748
+ * What a render resolves to — the component as the page saw it, after the
1749
+ * scenario ran.
1750
+ *
1751
+ * Five accessors and no more: the ARIA outline a golden pins, the two
1752
+ * renderings a probe reads, and the two streams a spec wants silent. Nothing
1753
+ * here reaches back into React — a spec that needs the component's internals
1754
+ * is asserting the implementation, not the surface a user meets.
1755
+ */
1756
+ var RenderResult = class {
1757
+ /** The browser console as a stream — one `[type] text` line per message. */
1758
+ console;
1759
+ /** Rendered text of the whole document body (`innerText`). */
1760
+ content;
1761
+ /** Console messages of type `error` only, plus any uncaught page error. */
1762
+ errors;
1763
+ /** The mounted markup, serialised — the escape hatch for a class or an attribute. */
1764
+ html;
1765
+ /** The ARIA snapshot of the rendered body — the outline a golden pins. */
1766
+ tree;
1767
+ constructor(streams) {
1768
+ this.console = new RenderedText(streams.console, "console", "");
1769
+ this.content = new RenderedText(streams.content, "content", "");
1770
+ this.errors = new RenderedText(streams.errors, "errors", "");
1771
+ this.html = new RenderedText(streams.html, "html", "");
1772
+ this.tree = new RenderedText(streams.tree, "tree", "");
1773
+ }
1774
+ };
1775
+ //#endregion
1776
+ //#region src/specification/facets/component/component.chain.ts
1777
+ /** The console methods a render records; everything else is left alone. */
1778
+ const CONSOLE_METHODS = [
1779
+ "debug",
1780
+ "error",
1781
+ "info",
1782
+ "log",
1783
+ "warn"
1784
+ ];
1785
+ const EMPTY = {
1786
+ clock: null,
1787
+ contracts: [],
1788
+ viewport: null,
1789
+ wrap: null
1790
+ };
1791
+ /** Record what the page writes to the console for the length of the render. */
1792
+ function recordConsole() {
1793
+ const entries = [];
1794
+ const originals = /* @__PURE__ */ new Map();
1795
+ for (const method of CONSOLE_METHODS) {
1796
+ const original = console[method];
1797
+ originals.set(method, original);
1798
+ console[method] = (...args) => {
1799
+ entries.push({
1800
+ text: args.map(String).join(" "),
1801
+ type: method
1802
+ });
1803
+ original(...args);
1804
+ };
1805
+ }
1806
+ const onError = (event) => {
1807
+ entries.push({
1808
+ text: event.message,
1809
+ type: "error"
1810
+ });
1811
+ };
1812
+ globalThis.addEventListener("error", onError);
1813
+ let stopped = false;
1814
+ return {
1815
+ entries,
1816
+ stop: () => {
1817
+ if (stopped) return;
1818
+ stopped = true;
1819
+ for (const method of CONSOLE_METHODS) {
1820
+ const original = originals.get(method);
1821
+ if (original !== void 0) console[method] = original;
1822
+ }
1823
+ globalThis.removeEventListener("error", onError);
1824
+ }
1825
+ };
1826
+ }
1827
+ /** Is the subject a function that fills a container, rather than a React tree? */
1828
+ function isDomMount(subject) {
1829
+ return typeof subject === "function";
1830
+ }
1831
+ /** A bare request needs its response — the same refusal every facet gives. */
1832
+ function inlinePair(request, response) {
1833
+ if (response === void 0) throw new Error(".intercept(): a bare request needs its response — pass a contract (defineContract({ request, response })) or the inline pair .intercept(request, response).");
1834
+ return {
1835
+ request,
1836
+ response
1837
+ };
1838
+ }
1839
+ /**
1840
+ * What the page is still holding, and the teardown that lets it go.
1841
+ *
1842
+ * The React adapter's own auto-cleanup is a `beforeEach` registered when its
1843
+ * module loads — and this package loads it lazily, INSIDE the first render, so
1844
+ * that hook never covers the test that triggered it. The seam does the unmount
1845
+ * itself, on the test that rendered: two renders' markup sharing one document
1846
+ * is how a second `button('Open')` appears and a descriptor that named exactly
1847
+ * one element starts refusing.
1848
+ */
1849
+ let mounted = null;
1850
+ /** Everything one test may have left behind, undone — no hook in any spec. */
1851
+ async function resetComponentScope(resized) {
1852
+ await unmountHeld();
1853
+ if (resized) await setViewport(providedViewport());
1854
+ resetWorkerContracts();
1855
+ releaseClock();
1856
+ }
1857
+ /** Take down whatever is still mounted, and hold nothing afterwards. */
1858
+ async function unmountHeld() {
1859
+ const surface = mounted;
1860
+ mounted = null;
1861
+ if (surface !== null) try {
1862
+ await surface.unmount();
1863
+ } catch {}
1864
+ }
1865
+ /** Mount the subject, dressing a React tree in the chain's wrapper and the project's. */
1866
+ async function mount(state, subject) {
1867
+ if (isDomMount(subject)) return mountDom(subject);
1868
+ const outer = projectWrapper();
1869
+ const dress = (ui) => {
1870
+ const inner = state.wrap ? state.wrap(ui) : ui;
1871
+ return outer ? outer(inner) : inner;
1872
+ };
1873
+ const surface = await mountReact(dress(subject));
1874
+ return {
1875
+ ...surface,
1876
+ rerender: async (ui) => {
1877
+ await surface.rerender(dress(ui));
1878
+ }
1879
+ };
1880
+ }
1881
+ /** The terminal action: mount, run the scenario, capture what the page shows. */
1882
+ async function render(state, subject, scenario) {
1883
+ await unmountHeld();
1884
+ const recorder = recordConsole();
1885
+ afterThisTest(async () => {
1886
+ recorder.stop();
1887
+ await resetComponentScope(state.viewport !== null);
1888
+ });
1889
+ if (state.viewport !== null) await setViewport(state.viewport);
1890
+ const instant = state.clock ?? providedClock();
1891
+ if (instant !== void 0) pinClock(instant);
1892
+ const registration = await registerWorkerContracts(state.contracts);
1893
+ const surface = await mount(state, subject);
1894
+ mounted = surface;
1895
+ try {
1896
+ if (scenario) await scenario(componentVerbs(surface));
1897
+ } finally {
1898
+ recorder.stop();
1899
+ }
1900
+ const violation = registration.violation();
1901
+ if (violation !== null) throw violation;
1902
+ const { entries } = recorder;
1903
+ return new RenderResult({
1904
+ console: entries.map((entry) => `[${entry.type}] ${entry.text}`).join("\n"),
1905
+ content: document.body.innerText,
1906
+ errors: entries.filter((entry) => entry.type === "error").map((entry) => entry.text).join("\n"),
1907
+ html: surface.container.innerHTML,
1908
+ tree: await ariaTree()
1909
+ });
1910
+ }
1911
+ /** Every setup forks a chain, so the exported handle never carries a test's state. */
1912
+ function chainOf(state) {
1913
+ return {
1914
+ clock: (iso) => chainOf({
1915
+ ...state,
1916
+ clock: iso
1917
+ }),
1918
+ intercept: (requestOrContracts, maybeResponse) => {
1919
+ const added = Array.isArray(requestOrContracts) || isContracts(requestOrContracts) || isContract(requestOrContracts) ? contractsOf(requestOrContracts) : [inlinePair(requestOrContracts, maybeResponse)];
1920
+ return chainOf({
1921
+ ...state,
1922
+ contracts: [...state.contracts, ...added]
1923
+ });
1924
+ },
1925
+ render: async (subject, scenario) => await render(state, subject, scenario),
1926
+ viewport: (size) => chainOf({
1927
+ ...state,
1928
+ viewport: size
1929
+ }),
1930
+ wrap: (wrapper) => chainOf({
1931
+ ...state,
1932
+ wrap: wrapper
1933
+ })
1934
+ };
1935
+ }
1936
+ /** The handle a component test imports. */
1937
+ const component = chainOf(EMPTY);
1938
+ //#endregion
1939
+ //#region src/specification/facets/_common/result/json.ts
1940
+ /**
1941
+ * Read-only accessor for a JSON payload parsed from a text stream (stdout).
1942
+ *
1943
+ * Lazily parses the JSON on first use; parse errors are deferred until the
1944
+ * value is read so that callers can still read the raw stream text without
1945
+ * triggering a throw.
1946
+ *
1947
+ * ANSI escape sequences are stripped by default before `JSON.parse`
1948
+ * (CONVENTIONS D6). When a `transform` is configured on the spec runner, it
1949
+ * runs on the stripped text — an escape hatch for application noise not
1950
+ * covered by the `{{token}}` grammar.
1951
+ *
1952
+ * Assertions go through `expect()`: `expect(result.json).toMatch('name.json')`
1953
+ * (deep-equal against `_expected/<name>`, with `{{placeholder}}` support).
1954
+ */
1955
+ var JsonAccessor = class {
1956
+ /** @internal Ref-capture scope shared by the current spec execution. */
1957
+ captures;
1958
+ /** @internal */
1959
+ rawText;
1960
+ /** @internal Test-file directory — fixture resolution root for matchers. */
1961
+ testDir;
1962
+ /** @internal */
1963
+ transform;
1964
+ constructor(rawText, testDir, transform, captures) {
1965
+ this.rawText = rawText;
1966
+ this.testDir = testDir;
1967
+ this.transform = transform;
1968
+ this.captures = captures ?? new CaptureScope();
1969
+ }
1970
+ /**
1971
+ * The parsed JSON value. Throws if the text is not valid JSON.
1972
+ *
1973
+ * `Value` is `unknown` unless the subject that produced this accessor
1974
+ * knows better — `.call<T>()` does, and hands its T straight through so a
1975
+ * one-field reading needs no cast in the test.
1976
+ */
1977
+ get value() {
1978
+ const stripped = stripAnsiCodes(this.rawText);
1979
+ const source = this.transform ? this.transform(stripped) : stripped;
1980
+ try {
1981
+ return JSON.parse(source);
1982
+ } catch {
1983
+ const preview = source.slice(0, 200);
1984
+ throw new Error(`stdout is not valid JSON: ${preview}`);
1985
+ }
1986
+ }
1987
+ };
1988
+ //#endregion
1989
+ //#region src/specification/facets/_common/result/table.ts
1990
+ /**
1991
+ * Read-only accessor for a database table after a specification run.
1992
+ *
1993
+ * Assertions go through `expect()` (async — they query the database):
1994
+ *
1995
+ * await expect(result.table('users', { database: 'db' })).toMatchRows({
1996
+ * columns: ['name'],
1997
+ * rows: [['Alice']],
1998
+ * });
1999
+ * await expect(result.table('users', { database: 'db' })).toBeEmpty();
2000
+ */
2001
+ var TableAccessor = class {
2002
+ /** @internal Ref-capture scope shared by the current spec execution. */
2003
+ captures;
2004
+ /** @internal */
2005
+ db;
2006
+ /** The table name this accessor reads. */
2007
+ name;
2008
+ constructor(name, db, captures) {
2009
+ this.name = name;
2010
+ this.db = db;
2011
+ this.captures = captures ?? new CaptureScope();
2012
+ }
2013
+ /** @internal Query the table — used by the toMatchRows / toBeEmpty matchers. */
2014
+ async query(columns) {
2015
+ return await this.db.query(this.name, columns);
2016
+ }
2017
+ };
2018
+ //#endregion
2019
+ //#region src/specification/facets/website/elements.ts
2020
+ const named = (kind) => (name, options) => ({
2021
+ kind,
2022
+ name,
2023
+ ...options?.exact ? { exact: true } : {}
2024
+ });
2025
+ /** A button (or element with the button role), by accessible name. */
2026
+ const button = named("button");
2027
+ /** A form field, by label. */
2028
+ const field = named("field");
2029
+ /** A heading, by accessible name. */
2030
+ const heading = named("heading");
2031
+ /** A link, by accessible name. */
2032
+ const link = named("link");
2033
+ /** An element containing the given text. */
2034
+ const content = named("text");
2035
+ /** The escape hatch: an element by `data-testid`. Prefer user-facing elements. */
2036
+ const testId = (id) => ({
2037
+ kind: "testId",
2038
+ name: id
2039
+ });
2040
+ const landmark = (kind) => (name, options) => ({
2041
+ kind,
2042
+ ...name === void 0 ? {} : { name },
2043
+ ...options?.exact ? { exact: true } : {}
2044
+ });
2045
+ /** The `banner` landmark — the page header. */
2046
+ const banner = landmark("banner");
2047
+ /** The `complementary` landmark — an `<aside>`, a sidebar. */
2048
+ const complementary = landmark("complementary");
2049
+ /** The `contentinfo` landmark — the page footer. */
2050
+ const contentinfo = landmark("contentinfo");
2051
+ /** The `form` landmark — a form carrying an accessible name. */
2052
+ const form = landmark("form");
2053
+ /** The `main` landmark — the primary content of the document. */
2054
+ const main = landmark("main");
2055
+ /** The `navigation` landmark — a `<nav>`. Name it when a page has several. */
2056
+ const navigation = landmark("navigation");
2057
+ /** The `region` landmark — a `<section>` carrying an accessible name. */
2058
+ const region = landmark("region");
2059
+ /** The `search` landmark. */
2060
+ const search = landmark("search");
2061
+ /**
2062
+ * Restrict a descriptor to the inside of another — the answer to ambiguity,
2063
+ * and the one the framework prefers over a test id.
2064
+ *
2065
+ * click(within(navigation(), link('Articles')))
2066
+ *
2067
+ * Composes outside-in: the scope may itself be scoped, so a deeply nested
2068
+ * target reads `within(main(), within(region('Series'), link('Part 2')))`.
2069
+ * Any descriptor works as a scope, including `testId()` when a container has
2070
+ * no landmark role to stand on.
2071
+ */
2072
+ const within = (scope, target) => ({
2073
+ ...target,
2074
+ scope: target.scope ? {
2075
+ ...target.scope,
2076
+ scope
2077
+ } : scope
2078
+ });
2079
+ /** A modal or non-modal `<dialog>`, by accessible name. A closed one is absent. */
2080
+ const dialog = landmark("dialog");
2081
+ /** A live region announcing a result — `role="status"`, an `<output>`. */
2082
+ const status = landmark("status");
2083
+ /** A table, by its caption or accessible name. */
2084
+ const table = landmark("table");
2085
+ /** A row of a table or grid, by the text of its cells. */
2086
+ const row = landmark("row");
2087
+ /** An item of a list, by its text. Retires the `.first()` of an unnamed `<li>`. */
2088
+ const listitem = landmark("listitem");
2089
+ /**
2090
+ * An option of a select or a listbox, by its label — named inside the field
2091
+ * that holds it: `within(field('Channel'), option('LinkedIn'))`.
2092
+ *
2093
+ * Asserted by PRESENCE, not by visibility: the options of a collapsed
2094
+ * `<select>` are in the document and in the accessibility tree, and none of
2095
+ * them has a box on the screen until it is opened. `see(option('LinkedIn'))`
2096
+ * therefore asks "is it offered", and `see(selected(option('LinkedIn')))`
2097
+ * asks which one the field is on.
2098
+ */
2099
+ const option = named("option");
2100
+ /**
2101
+ * Where the keyboard is: `see(focused(button('Open')))` asserts the element has
2102
+ * focus, `gone(focused(x))` that it does not.
2103
+ *
2104
+ * A modifier rather than a descriptor of its own, because focus is a STATE of
2105
+ * an element the vocabulary can already name. It is a verb's business and never
2106
+ * a golden's: the accessibility tree carries no focus, so a tree snapshot of a
2107
+ * dialog that took the keyboard and one that did not are byte-identical.
2108
+ */
2109
+ const focused = (element) => ({
2110
+ ...element,
2111
+ focused: true
2112
+ });
2113
+ /**
2114
+ * Whether the element accepts input: `see(disabled(button('Delete')))` asserts
2115
+ * it refuses, `see(enabled(button('Delete')))` that it takes it.
2116
+ *
2117
+ * Modifiers rather than descriptors, for the same reason as `focused`: being
2118
+ * disabled is a state of an element the vocabulary already names. Unlike focus,
2119
+ * the ARIA tree carries it, so a golden pins a whole outline's enablement and
2120
+ * these name the ONE control a test is about. They also buy the direction a
2121
+ * behavioural substitute cannot reach — clicking a disabled control is a
2122
+ * timeout, never an assertion.
2123
+ */
2124
+ const disabled = (element) => ({
2125
+ ...element,
2126
+ disabled: true
2127
+ });
2128
+ /** The other direction of {@link disabled} — the element takes input. */
2129
+ const enabled = (element) => ({
2130
+ ...element,
2131
+ disabled: false
2132
+ });
2133
+ /**
2134
+ * Which option the field is on: `see(selected(option('LinkedIn')))`, and
2135
+ * `gone(selected(option('X')))` for the one it left.
2136
+ *
2137
+ * A modifier for the same reason as {@link disabled}: being chosen is a state
2138
+ * of an element the vocabulary already names. No matcher answers for it — a
2139
+ * `<option>` is not a checkbox — so both adapters read the `:checked` the CSS
2140
+ * spec gives a selected option.
2141
+ */
2142
+ const selected = (element) => ({
2143
+ ...element,
2144
+ selected: true
2145
+ });
2146
+ /**
2147
+ * What the field holds: `see(valued(field('Title'), 'Launch teaser'))`, and
2148
+ * `gone(valued(field('Title'), '…'))` for a value it no longer holds.
2149
+ *
2150
+ * A modifier for the same reason as {@link disabled}: what a field holds is a
2151
+ * state of an element the vocabulary already names, and this is how the ONE
2152
+ * field a test is about is waited for — a golden pins a whole outline instead.
2153
+ * Read from the node's live value, never from the `value` ATTRIBUTE, which a
2154
+ * controlled input never moves.
2155
+ */
2156
+ const valued = (element, value) => ({
2157
+ ...element,
2158
+ value
2159
+ });
2160
+ //#endregion
2161
+ //#region src/specification/contracts/filters.ts
2162
+ /** Does an observed text satisfy a declared {@link TextFilter}? */
2163
+ function matchesText(filter, actual) {
2164
+ if (filter === void 0) return true;
2165
+ if (typeof filter === "string") return actual === filter;
2166
+ if (filter instanceof RegExp) return filter.test(actual);
2167
+ return structuralEquals(filter, actual, new CaptureScope());
2168
+ }
2169
+ //#endregion
2170
+ //#region src/integrations/anthropic/anthropic.ts
2171
+ const ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
2172
+ function matchesFilter(body, filter) {
2173
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2174
+ if (!matchesText(filter.system, typeof body?.system === "string" ? body.system : "")) return false;
2175
+ const userMsg = body?.messages?.find((m) => m.role === "user")?.content ?? "";
2176
+ if (!matchesText(filter.user, typeof userMsg === "string" ? userMsg : JSON.stringify(userMsg))) return false;
2177
+ if (filter.tools) {
2178
+ const names = body?.tools?.map((t) => t.name).filter(Boolean) ?? [];
2179
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2180
+ }
2181
+ return true;
2182
+ }
2183
+ function buildReply(data) {
2184
+ return {
2185
+ status: 200,
2186
+ body: {
2187
+ id: "msg-test",
2188
+ type: "message",
2189
+ role: "assistant",
2190
+ content: [{
2191
+ type: "text",
2192
+ text: typeof data === "string" ? data : JSON.stringify(data)
2193
+ }],
2194
+ model: "claude-sonnet-4-20250514",
2195
+ stop_reason: "end_turn",
2196
+ usage: {
2197
+ input_tokens: 10,
2198
+ output_tokens: 10
2199
+ }
2200
+ }
2201
+ };
2202
+ }
2203
+ /**
2204
+ * Anthropic API intercept helpers.
2205
+ */
2206
+ const anthropic = {
2207
+ /**
2208
+ * Request: match Messages API calls, optionally routed through a
2209
+ * custom gateway URL. When used with a JSON fixture file, the data is
2210
+ * returned as-is (no wrapping) because Anthropic fixtures are typically
2211
+ * already in the Messages API response shape.
2212
+ *
2213
+ * @example
2214
+ * anthropic.messages()
2215
+ * anthropic.messages({ system: /classify/ })
2216
+ * anthropic.messages({ user: buildPrompt() }) // string = EXACT equality
2217
+ * anthropic.messages({ user: /classify/ }, GATEWAY)
2218
+ */
2219
+ messages(filter, url) {
2220
+ return {
2221
+ adapter: "anthropic",
2222
+ method: "POST",
2223
+ url: url ?? ANTHROPIC_MESSAGES_URL,
2224
+ match: filter ? ({ body }) => matchesFilter(body, filter) : void 0,
2225
+ wrap(data) {
2226
+ if (data && typeof data === "object" && !Array.isArray(data)) return {
2227
+ status: 200,
2228
+ body: data
2229
+ };
2230
+ return buildReply(data);
2231
+ }
2232
+ };
2233
+ },
2234
+ /** Response: wrap data in Anthropic messages format. */
2235
+ reply(data) {
2236
+ return buildReply(data);
2237
+ },
2238
+ /** Response: return an Anthropic error. */
2239
+ error(status, message) {
2240
+ return {
2241
+ status,
2242
+ body: {
2243
+ type: "error",
2244
+ error: {
2245
+ type: status === 429 ? "rate_limit_error" : "api_error",
2246
+ message: message ?? `Anthropic error (${status})`
2247
+ }
2248
+ }
2249
+ };
2250
+ },
2251
+ /** Response: simulate a timeout. */
2252
+ timeout() {
2253
+ return {
2254
+ status: 200,
2255
+ body: {},
2256
+ delay: 3e4
2257
+ };
2258
+ }
2259
+ };
2260
+ //#endregion
2261
+ //#region src/specification/contracts/http.ts
2262
+ function wrapJson(data) {
2263
+ return {
2264
+ status: 200,
2265
+ body: data
2266
+ };
2267
+ }
2268
+ const TEXT_CONTENT_TYPE = "text/plain; charset=utf-8";
2269
+ const STREAM_CONTENT_TYPE = "application/octet-stream";
2270
+ const SSE_CONTENT_TYPE = "text/event-stream";
2271
+ /** The wire form of one event — the frame an `EventSource` parses. */
2272
+ function frameEvent(event) {
2273
+ const lines = [];
2274
+ if (event.event !== void 0) lines.push(`event: ${event.event}`);
2275
+ if (event.id !== void 0) lines.push(`id: ${event.id}`);
2276
+ if (event.retry !== void 0) lines.push(`retry: ${event.retry}`);
2277
+ const payload = typeof event.data === "string" ? event.data : JSON.stringify(event.data);
2278
+ for (const line of payload.split("\n")) lines.push(`data: ${line}`);
2279
+ return `${lines.join("\n")}\n\n`;
2280
+ }
2281
+ function matchesBody(body, expected) {
2282
+ if (typeof expected === "string") return (typeof body === "string" ? body : JSON.stringify(body ?? "")).includes(expected);
2283
+ if (expected instanceof RegExp) {
2284
+ const text = typeof body === "string" ? body : JSON.stringify(body ?? "");
2285
+ return expected.test(text);
2286
+ }
2287
+ return structuralSubset(expected, body, new CaptureScope());
2288
+ }
2289
+ function matchesEntries(expected, lookup) {
2290
+ return Object.entries(expected).every(([key, value]) => {
2291
+ const actual = lookup(key);
2292
+ if (actual === void 0) return false;
2293
+ return value instanceof RegExp ? value.test(actual) : actual === value;
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Build the `match` predicate for an HTTP request filter, or `undefined` when
2298
+ * no filter is supplied (fires on any URL/method match).
2299
+ */
2300
+ function buildMatch(filter) {
2301
+ if (!filter) return;
2302
+ return (request) => {
2303
+ if (filter.body !== void 0 && !matchesBody(request.body, filter.body)) return false;
2304
+ if (filter.headers && !matchesEntries(filter.headers, (key) => request.headers[key.toLowerCase()])) return false;
2305
+ if (filter.query) {
2306
+ let params;
2307
+ try {
2308
+ params = new URL(request.url, "http://contract.invalid").searchParams;
2309
+ } catch {
2310
+ return false;
2311
+ }
2312
+ if (!matchesEntries(filter.query, (key) => params.get(key) ?? void 0)) return false;
2313
+ }
2314
+ return true;
2315
+ };
2316
+ }
2317
+ function declare(method, url, filter) {
2318
+ return {
2319
+ adapter: "http",
2320
+ match: buildMatch(filter),
2321
+ method,
2322
+ url,
2323
+ wrap: wrapJson
2324
+ };
2325
+ }
2326
+ /**
2327
+ * Generic HTTP contract helpers for any URL. The url is absolute (string or
2328
+ * RegExp), or a PATH FORM starting with `/` — `http.get('/articles/{{uuid}}')`
2329
+ * matches that path on ANY origin, which is what an app calling its own
2330
+ * backend needs. An optional {@link HttpContractFilter} narrows matching by
2331
+ * body, headers, or query — a request that hits the URL/method but fails the
2332
+ * filter counts as unmatched (strict contracts, CONVENTIONS D7).
2333
+ *
2334
+ * @example
2335
+ * defineContract({ request: http.get('/articles/{{uuid}}'), response: http.json(article) })
2336
+ * defineContract({ request: http.post(URL, { body: { user: 'alice' } }), response: http.empty() })
2337
+ */
2338
+ const http = {
2339
+ any(url, filter) {
2340
+ return declare("*", url, filter);
2341
+ },
2342
+ delete(url, filter) {
2343
+ return declare("DELETE", url, filter);
2344
+ },
2345
+ get(url, filter) {
2346
+ return declare("GET", url, filter);
2347
+ },
2348
+ patch(url, filter) {
2349
+ return declare("PATCH", url, filter);
2350
+ },
2351
+ post(url, filter) {
2352
+ return declare("POST", url, filter);
2353
+ },
2354
+ put(url, filter) {
2355
+ return declare("PUT", url, filter);
2356
+ },
2357
+ /** Response: a body-less reply (204 by default). */
2358
+ empty(status = 204) {
2359
+ return {
2360
+ status,
2361
+ body: null
2362
+ };
2363
+ },
2364
+ /** Response: an error status. Without a body, `{ error: 'HTTP <status>' }`. */
2365
+ error(status, body) {
2366
+ return {
2367
+ status,
2368
+ body: body === void 0 ? { error: `HTTP ${status}` } : body
2369
+ };
2370
+ },
2371
+ /** Response: a JSON body (200 by default). */
2372
+ json(body, init) {
2373
+ return {
2374
+ status: init?.status ?? 200,
2375
+ body,
2376
+ delay: init?.delay,
2377
+ headers: init?.headers
2378
+ };
2379
+ },
2380
+ /**
2381
+ * Response: no response at all — the request fails in transport, the way a
2382
+ * server that is not running fails it. `fetch` rejects; no status is served.
2383
+ */
2384
+ unreachable() {
2385
+ return {
2386
+ body: null,
2387
+ transport: "network-error"
2388
+ };
2389
+ },
2390
+ /**
2391
+ * Response: a body that arrives in PIECES, written in order.
2392
+ *
2393
+ * A subject that reads a response as it lands — a token-by-token render, a
2394
+ * progress bar, a reconnect on a half-read body — is specified by the
2395
+ * chunks and their order, which a single serialised body cannot state.
2396
+ * Honoured by all three engines: msw's server, msw's worker, and the
2397
+ * `node:http` stub the website and mobile facets serve from.
2398
+ *
2399
+ * @example
2400
+ * http.stream(['Hel', 'lo, ', 'world'], { contentType: 'text/plain', delay: 10 })
2401
+ */
2402
+ stream(chunks, init) {
2403
+ return {
2404
+ status: init?.status ?? 200,
2405
+ body: {
2406
+ chunks: [...chunks],
2407
+ contentType: init?.contentType ?? STREAM_CONTENT_TYPE,
2408
+ delayBetweenChunks: init?.delay ?? 0,
2409
+ kind: STREAM_BODY
2410
+ },
2411
+ headers: init?.headers
2412
+ };
2413
+ },
2414
+ /**
2415
+ * Response: a server-sent event stream — one chunk per event, framed the
2416
+ * way an `EventSource` reads them, served as `text/event-stream`.
2417
+ *
2418
+ * @example
2419
+ * http.sse([{ data: { token: 'Hel' } }, { data: { token: 'lo' } }, { event: 'done', data: '' }])
2420
+ */
2421
+ sse(events, init) {
2422
+ return {
2423
+ status: init?.status ?? 200,
2424
+ body: {
2425
+ chunks: events.map(frameEvent),
2426
+ contentType: SSE_CONTENT_TYPE,
2427
+ delayBetweenChunks: init?.delay ?? 0,
2428
+ kind: STREAM_BODY
2429
+ },
2430
+ headers: {
2431
+ "cache-control": "no-cache",
2432
+ ...init?.headers
2433
+ }
2434
+ };
2435
+ },
2436
+ /** Response: a text body, served as `text/plain` (200 by default). */
2437
+ text(body, init) {
2438
+ return {
2439
+ status: init?.status ?? 200,
2440
+ body,
2441
+ delay: init?.delay,
2442
+ headers: {
2443
+ "content-type": TEXT_CONTENT_TYPE,
2444
+ ...init?.headers
2445
+ }
2446
+ };
2447
+ }
2448
+ };
2449
+ //#endregion
2450
+ //#region src/integrations/openai/openai.ts
2451
+ const OPENAI_CHAT_URL = "https://api.openai.com/v1/chat/completions";
2452
+ const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
2453
+ function matchesChatFilter(body, filter) {
2454
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2455
+ if (!matchesText(filter.system, body?.messages?.find((m) => m.role === "system")?.content ?? "")) return false;
2456
+ if (!matchesText(filter.user, body?.messages?.find((m) => m.role === "user")?.content ?? "")) return false;
2457
+ if (filter.tools) {
2458
+ const names = body?.tools?.map((t) => t.function?.name).filter(Boolean) ?? [];
2459
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2460
+ }
2461
+ if (filter.temperature !== void 0 && body?.temperature !== filter.temperature) return false;
2462
+ return true;
2463
+ }
2464
+ function matchesResponsesFilter(body, filter) {
2465
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2466
+ const systemInput = body?.input?.find?.((m) => m.role === "system")?.content ?? "";
2467
+ if (!matchesText(filter.system, body?.instructions || systemInput)) return false;
2468
+ const userText = (body?.input ?? []).filter((m) => m.role === "user").map((m) => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join(" ");
2469
+ if (!matchesText(filter.user, userText)) return false;
2470
+ if (filter.tools) {
2471
+ const names = body?.tools?.map((t) => t.name ?? t.function?.name).filter(Boolean) ?? [];
2472
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2473
+ }
2474
+ return true;
2475
+ }
2476
+ function buildChatReply(data) {
2477
+ const content = typeof data === "string" ? data : JSON.stringify(data);
2478
+ return {
2479
+ status: 200,
2480
+ body: {
2481
+ id: "chatcmpl-test",
2482
+ object: "chat.completion",
2483
+ created: Math.floor(Date.now() / 1e3),
2484
+ model: "gpt-4o-test",
2485
+ choices: [{
2486
+ index: 0,
2487
+ message: {
2488
+ role: "assistant",
2489
+ content
2490
+ },
2491
+ finish_reason: "stop"
2492
+ }],
2493
+ usage: {
2494
+ prompt_tokens: 10,
2495
+ completion_tokens: 10,
2496
+ total_tokens: 20
2497
+ }
2498
+ }
2499
+ };
2500
+ }
2501
+ function buildResponsesReply(data) {
2502
+ const text = typeof data === "string" ? data : JSON.stringify(data);
2503
+ return {
2504
+ status: 200,
2505
+ body: {
2506
+ id: "resp-test",
2507
+ object: "response",
2508
+ created_at: Math.floor(Date.now() / 1e3),
2509
+ model: "gpt-4o-test",
2510
+ output: [{
2511
+ type: "message",
2512
+ id: "msg-test",
2513
+ role: "assistant",
2514
+ content: [{
2515
+ type: "output_text",
2516
+ text,
2517
+ annotations: []
2518
+ }]
2519
+ }],
2520
+ usage: {
2521
+ input_tokens: 10,
2522
+ output_tokens: 10,
2523
+ total_tokens: 20
2524
+ }
2525
+ }
2526
+ };
2527
+ }
2528
+ /**
2529
+ * OpenAI API intercept helpers.
2530
+ */
2531
+ const openai = {
2532
+ /**
2533
+ * Request: match Chat Completions API calls. STRING filters mean EXACT
2534
+ * equality (pass the app's own prompt builder); loosen deliberately with a
2535
+ * RegExp or `match.includes(...)`.
2536
+ *
2537
+ * @example
2538
+ * openai.chat() // any chat call
2539
+ * openai.chat({ model: 'gpt-4o' }) // exact model
2540
+ * openai.chat({ system: buildPrompt() }) // exact system prompt
2541
+ * openai.chat({ system: /classify/ }) // pattern
2542
+ */
2543
+ chat(filter) {
2544
+ return {
2545
+ adapter: "openai",
2546
+ method: "POST",
2547
+ url: OPENAI_CHAT_URL,
2548
+ match: filter ? ({ body }) => matchesChatFilter(body, filter) : void 0,
2549
+ wrap: buildChatReply
2550
+ };
2551
+ },
2552
+ /**
2553
+ * Request: match Responses API calls (AI SDK v5+) with auto-wrapping.
2554
+ * String filters mean EXACT equality (see {@link openai.chat}).
2555
+ * When used with a JSON file, the data is automatically wrapped in the
2556
+ * Responses API envelope.
2557
+ *
2558
+ * @param filter - Optional body filters.
2559
+ * @param url - Custom gateway URL (default: api.openai.com).
2560
+ *
2561
+ * @example
2562
+ * openai.responses({ user: /Report Ingestion/ }, GATEWAY)
2563
+ */
2564
+ responses(filter, url) {
2565
+ return {
2566
+ adapter: "openai",
2567
+ method: "POST",
2568
+ url: url ?? OPENAI_RESPONSES_URL,
2569
+ match: filter ? ({ body }) => matchesResponsesFilter(body, filter) : void 0,
2570
+ wrap: buildResponsesReply
2571
+ };
2572
+ },
2573
+ /**
2574
+ * Response: wrap data in Chat Completions format.
2575
+ *
2576
+ * @example
2577
+ * openai.reply({ categories: ['TECH'] })
2578
+ */
2579
+ reply(data) {
2580
+ return buildChatReply(data);
2581
+ },
2582
+ /** Response: return an OpenAI error. */
2583
+ error(status, message) {
2584
+ return {
2585
+ status,
2586
+ body: { error: {
2587
+ message: message ?? `OpenAI error (${status})`,
2588
+ type: status === 429 ? "rate_limit_error" : "api_error",
2589
+ code: status === 429 ? "rate_limit_exceeded" : null
2590
+ } }
2591
+ };
2592
+ },
2593
+ /** Response: return malformed content. */
2594
+ malformed(content) {
2595
+ return buildChatReply(content);
2596
+ },
2597
+ /** Response: simulate a timeout. */
2598
+ timeout() {
2599
+ return {
2600
+ status: 200,
2601
+ body: {},
2602
+ delay: 3e4
2603
+ };
2604
+ }
2605
+ };
2606
+ //#endregion
2607
+ //#region src/vitest/mock-of.ts
2608
+ function mockOf(options) {
2609
+ return options?.deep === false ? mock() : mockDeep();
2610
+ }
2611
+ //#endregion
2612
+ //#region src/vitest/mock-of-date.ts
2613
+ /**
2614
+ * Freeze or reset the global Date for deterministic time-dependent tests.
2615
+ * Wraps the `mockdate` package.
2616
+ */
2617
+ const mockOfDate = MockDatePackage;
2618
+ //#endregion
2619
+ //#region src/vitest/clock.ts
2620
+ /** The instant `iso` names, or a refusal that says what an instant looks like. */
2621
+ function instantOf(method, iso) {
2622
+ const at = new Date(iso);
2623
+ if (Number.isNaN(at.getTime())) throw new TypeError(`clock.${method}(): "${iso}" is not an instant — pass an ISO-8601 string (e.g. '2026-03-04T09:30:00Z').`);
2624
+ return at;
2625
+ }
2626
+ /**
2627
+ * One clock per test — a second one taken inside the first is refused rather
2628
+ * than nested.
2629
+ *
2630
+ * Disposing gives the REAL clock back, which is the only thing vitest's fake
2631
+ * timers can restore: the instant, the `toFake` set and the queue a previous
2632
+ * scope held are not readable, so an inner scope that ended would silently end
2633
+ * the outer one too. A refusal says which of the two the test meant.
2634
+ */
2635
+ function take(method, options) {
2636
+ if (vi.isFakeTimers()) throw new Error(`clock.${method}(): a clock is already pinned — one scope per test. End the first scope before taking another, or state the instant on the chain (\`.clock(iso)\`) rather than around it.`);
2637
+ vi.useFakeTimers(options);
2638
+ return { [Symbol.dispose]: () => {
2639
+ vi.useRealTimers();
2640
+ } };
2641
+ }
2642
+ const clock = {
2643
+ /**
2644
+ * Move the pinned clock forward by `ms` — and, under {@link clock.run},
2645
+ * fire every callback that came due, awaiting what each of them started.
2646
+ *
2647
+ * Only a pinned clock moves: called with no clock taken, it says so rather
2648
+ * than silently doing nothing to the real one.
2649
+ */
2650
+ async advance(ms) {
2651
+ if (!vi.isFakeTimers()) throw new Error("clock.advance(): no clock is pinned — take one first with `using _ = clock.at('<iso>')` (the calendar) or `using _ = clock.run()` (the scheduler).");
2652
+ await vi.advanceTimersByTimeAsync(ms);
2653
+ },
2654
+ /**
2655
+ * Pin `Date` at `iso` for the current scope. `Date` ONLY: the scheduler
2656
+ * stays real, so a subject that awaits, renders or polls keeps running.
2657
+ *
2658
+ * @example
2659
+ * using _ = clock.at('2026-03-04T09:30:00Z');
2660
+ * expect(stampedAt()).toBe('2026-03-04T09:30:00.000Z');
2661
+ */
2662
+ at(iso) {
2663
+ return take("at", {
2664
+ now: instantOf("at", iso),
2665
+ toFake: ["Date"]
2666
+ });
2667
+ },
2668
+ /**
2669
+ * Take the scheduler as well as the calendar: `setTimeout`, `setInterval`
2670
+ * and their friends queue instead of firing, and {@link clock.advance} is
2671
+ * what makes them due. For a subject whose behaviour IS elapsed time — a
2672
+ * debounce, a retry backoff, a poll — where waiting for real would be the
2673
+ * arbitrary sleep J2 forbids.
2674
+ *
2675
+ * @example
2676
+ * using _ = clock.run('2026-03-04T09:30:00Z');
2677
+ * const pending = retrying(failsTwice);
2678
+ * await clock.advance(5_000);
2679
+ * await expect(pending).resolves.toBe('ok');
2680
+ */
2681
+ run(iso) {
2682
+ return take("run", iso === void 0 ? {} : { now: instantOf("run", iso) });
2683
+ }
2684
+ };
2685
+ //#endregion
2686
+ //#region src/specification/assertions/required.ts
2687
+ /**
2688
+ * The value, or a failure that says what was missing and why it mattered.
2689
+ *
2690
+ * A test reaching into a captured structure — a row, a header, the third
2691
+ * element of a list — meets `T | undefined` and has to do something about it.
2692
+ * The two things it usually does are both wrong: `!` erases the question, and
2693
+ * an `if (!x) throw new Error('missing')` re-states the same three lines in
2694
+ * every repository (the estate had two hand-written copies of exactly this).
2695
+ * `required` is that gesture with the reason attached, so the failure reads as
2696
+ * a sentence rather than as a `TypeError` two frames further down.
2697
+ *
2698
+ * @example
2699
+ * const id = required(result.response.body.id, 'the creation reply carries the new id');
2700
+ */
2701
+ function required(value, why) {
2702
+ if (value === null || value === void 0) throw new Error(`required(): ${why} — got ${value === null ? "null" : "undefined"}. State it in the Given, or assert on what the subject actually produced.`);
2703
+ return value;
2704
+ }
2705
+ //#endregion
2706
+ //#region src/specification/assertions/wait-until.ts
2707
+ const DEFAULT_TIMEOUT_MS = 5e3;
2708
+ const DEFAULT_INTERVAL_MS = 50;
2709
+ /**
2710
+ * Wait until a condition holds — the sanctioned answer to "the thing I am
2711
+ * specifying is not ready yet".
2712
+ *
2713
+ * A spec that sleeps for a guessed duration is a spec that is slow on a fast
2714
+ * machine and flaky on a slow one, which is why J2 refuses `setTimeout` under
2715
+ * `specs/`. Every facet that drives something already waits on a CONDITION —
2716
+ * a served page, a banner on stdout, an element the visitor can see — and this
2717
+ * is that primitive where no facet owns the waiting: a background write to
2718
+ * land, a queue to drain, a file to appear.
2719
+ *
2720
+ * The failure names the condition and how long it was given, so a timeout is a
2721
+ * sentence rather than "expected true, got false".
2722
+ *
2723
+ * The budget is measured on `performance.now()`, not on `Date` — `clock.at()`
2724
+ * freezes the calendar, and a deadline read off a frozen calendar never
2725
+ * arrives: the poll would run until vitest killed the test with a sentence
2726
+ * about the file rather than about the condition.
2727
+ *
2728
+ * Not for a subject under `clock.run()`: there the scheduler is the test's, and
2729
+ * `clock.advance(ms)` is what makes time pass.
2730
+ *
2731
+ * @example
2732
+ * await waitUntil(() => outbox.length === 1, { why: 'the job wrote its one message' });
2733
+ */
2734
+ async function waitUntil(predicate, options = {}) {
2735
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
2736
+ const interval = options.interval ?? DEFAULT_INTERVAL_MS;
2737
+ const deadline = performance.now() + timeout;
2738
+ for (;;) {
2739
+ if (await predicate()) return;
2740
+ if (performance.now() >= deadline) throw new Error(`waitUntil(): ${options.why ?? "the condition"} did not hold within ${timeout}ms. Raise the budget if the wait is legitimate, or wait on what actually changes.`);
2741
+ await pause(interval);
2742
+ }
2743
+ }
2744
+ //#endregion
2745
+ //#region src/browser/index.ts
2746
+ registerBrowserMatchers();
2747
+ /**
2748
+ * The module-scope network double, on msw's WORKER — the same contracts and
2749
+ * the same strictness the node entry publishes, served by the one engine a
2750
+ * page has. Everything new in this release that a page can use is real here.
2751
+ */
2752
+ const intercept = interceptThrough(registerWorkerContracts);
2753
+ /**
2754
+ * The six constructors, present and refusing. A component test never reaches
2755
+ * one: what it renders is a unit, and the assembled product behind an entry is
2756
+ * specified from a node project.
2757
+ */
2758
+ const specification = {
2759
+ api: () => refuse("specification.api()"),
2760
+ cli: () => refuse("specification.cli()"),
2761
+ integration: () => refuse("specification.integration()"),
2762
+ jobs: () => refuse("specification.jobs()"),
2763
+ mobile: () => refuse("specification.mobile()"),
2764
+ website: () => refuse("specification.website()")
2765
+ };
2766
+ const process = () => refuse("process()");
2767
+ const ProcessHandle = nodeOnlyClass("ProcessHandle");
2768
+ const postgres = () => refuse("postgres()");
2769
+ const redis = () => refuse("redis()");
2770
+ const sqlite = () => refuse("sqlite()");
2771
+ const ContainerAccessor = nodeOnlyClass("ContainerAccessor");
2772
+ const findContainersByLabel = () => refuse("findContainersByLabel()");
2773
+ const inspectContainer = () => refuse("inspectContainer()");
2774
+ const removeContainers = () => refuse("removeContainers()");
2775
+ const Orchestrator = nodeOnlyClass("Orchestrator");
2776
+ const BaseResult = nodeOnlyClass("BaseResult");
2777
+ const CallResult = nodeOnlyClass("CallResult");
2778
+ const CliResult = nodeOnlyClass("CliResult");
2779
+ const DirectoryAccessor = nodeOnlyClass("DirectoryAccessor");
2780
+ const FetchResult = nodeOnlyClass("FetchResult");
2781
+ const FilesystemAccessor = nodeOnlyClass("FilesystemAccessor");
2782
+ const HttpResult = nodeOnlyClass("HttpResult");
2783
+ const PageResult = nodeOnlyClass("PageResult");
2784
+ const ResponseAccessor = nodeOnlyClass("ResponseAccessor");
2785
+ const ScreenResult = nodeOnlyClass("ScreenResult");
2786
+ /**
2787
+ * `text()` is real here: only its anchor differs. Under node the accessor
2788
+ * remembers the caller's directory so a golden resolves against it; in a page
2789
+ * the golden commands read the test's own path server-side, so there is
2790
+ * nothing for the accessor to carry.
2791
+ */
2792
+ function text(value) {
2793
+ return new TextAccessor(value, "text", "");
2794
+ }
2795
+ //#endregion
2796
+ export { BaseResult, CallResult, CliResult, ContainerAccessor, DirectoryAccessor, FetchResult, FilesystemAccessor, HttpResult, JsonAccessor, Matcher, Orchestrator, PageResult, ProcessHandle, ResponseAccessor, ScreenResult, TableAccessor, TextAccessor, anthropic, banner, button, clock, complementary, component, content, contentinfo, defineContract, defineContracts, dialog, disabled, enabled, field, findContainersByLabel, focused, form, heading, http, inspectContainer, intercept, link, listitem, main, match, mockOf, mockOfDate, navigation, openai, option, postgres, process, redis, region, removeContainers, required, row, search, selected, specification, sqlite, status, table, testId, text, valued, waitUntil, within };