@docsxai/engine 0.2.1-rc.1 → 0.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +18 -5
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.d.ts +3 -3
  5. package/dist/auth/email-otp.d.ts +60 -60
  6. package/dist/auth/jwt-injection.d.ts +45 -45
  7. package/dist/auth/pat-header.d.ts +2 -2
  8. package/dist/auth/types.d.ts +2 -2
  9. package/dist/auth/ui-form.d.ts +54 -54
  10. package/dist/auth/webauthn.d.ts +22 -22
  11. package/dist/backend-client-contracts.d.ts +4 -2
  12. package/dist/backend-client-token.js +2 -1
  13. package/dist/calibrate.d.ts +2 -2
  14. package/dist/calibrate.js +5 -0
  15. package/dist/cli-backend-errors.d.ts +7 -0
  16. package/dist/cli-backend-errors.js +65 -0
  17. package/dist/cli-commands-authoring.js +57 -51
  18. package/dist/cli-commands-backend.js +49 -42
  19. package/dist/cli-commands-docpack.d.ts +5 -0
  20. package/dist/cli-commands-docpack.js +106 -66
  21. package/dist/cli-commands-pack.d.ts +2 -0
  22. package/dist/cli-commands-pack.js +65 -0
  23. package/dist/cli-commands-session.js +120 -125
  24. package/dist/cli-messages.d.ts +17 -0
  25. package/dist/cli-messages.js +80 -0
  26. package/dist/cli-retired.d.ts +6 -0
  27. package/dist/cli-retired.js +12 -0
  28. package/dist/cli-run-summary.d.ts +15 -0
  29. package/dist/cli-run-summary.js +33 -0
  30. package/dist/cli-usage.d.ts +1 -1
  31. package/dist/cli-usage.js +78 -5
  32. package/dist/cli-verify.d.ts +14 -0
  33. package/dist/cli-verify.js +54 -0
  34. package/dist/cli.js +15 -2
  35. package/dist/deprecation.d.ts +19 -0
  36. package/dist/deprecation.js +32 -0
  37. package/dist/diagnose.d.ts +25 -0
  38. package/dist/diagnose.js +69 -3
  39. package/dist/diff-compute.js +1 -0
  40. package/dist/doc-pack-io.d.ts +14 -0
  41. package/dist/doc-pack-io.js +121 -14
  42. package/dist/doc-pack.d.ts +2282 -387
  43. package/dist/doc-pack.js +135 -43
  44. package/dist/doctor-checks-plugins.js +4 -3
  45. package/dist/doctor-checks.d.ts +1 -1
  46. package/dist/doctor-checks.js +31 -6
  47. package/dist/doctor.d.ts +2 -0
  48. package/dist/doctor.js +27 -3
  49. package/dist/driver-budget.d.ts +6 -0
  50. package/dist/driver-budget.js +15 -0
  51. package/dist/egress-guard.d.ts +58 -0
  52. package/dist/egress-guard.js +136 -0
  53. package/dist/environment-spec.d.ts +67 -0
  54. package/dist/environment-spec.js +38 -0
  55. package/dist/export/playwright-test.js +42 -10
  56. package/dist/flow-file.d.ts +9 -3
  57. package/dist/flow-file.js +21 -1
  58. package/dist/flow-halt.d.ts +16 -0
  59. package/dist/flow-halt.js +76 -0
  60. package/dist/flow-hidden.d.ts +9 -0
  61. package/dist/flow-hidden.js +20 -0
  62. package/dist/flow-lint.js +91 -1
  63. package/dist/flow-matrix-lint.d.ts +10 -0
  64. package/dist/flow-matrix-lint.js +40 -0
  65. package/dist/flow-matrix.d.ts +44 -0
  66. package/dist/flow-matrix.js +238 -0
  67. package/dist/flow-name-rules.d.ts +15 -0
  68. package/dist/flow-name-rules.js +39 -0
  69. package/dist/flow-runtime.d.ts +52 -22
  70. package/dist/flow-runtime.js +63 -117
  71. package/dist/flow-success.d.ts +3 -0
  72. package/dist/flow-success.js +37 -0
  73. package/dist/flow-tree.d.ts +2 -0
  74. package/dist/flow-tree.js +17 -5
  75. package/dist/flow-wait.d.ts +3 -0
  76. package/dist/flow-wait.js +22 -0
  77. package/dist/index.d.ts +5 -0
  78. package/dist/index.js +5 -0
  79. package/dist/matrix-spec.d.ts +145 -0
  80. package/dist/matrix-spec.js +120 -0
  81. package/dist/page-hide.d.ts +10 -0
  82. package/dist/page-hide.js +45 -0
  83. package/dist/page-settle.d.ts +39 -0
  84. package/dist/page-settle.js +142 -0
  85. package/dist/playwright-driver.d.ts +28 -8
  86. package/dist/playwright-driver.js +73 -28
  87. package/dist/plugins/manifest.d.ts +9 -9
  88. package/dist/run-flows.d.ts +40 -0
  89. package/dist/run-flows.js +129 -0
  90. package/dist/style.d.ts +2 -2
  91. package/dist/upload-path.d.ts +15 -0
  92. package/dist/upload-path.js +63 -0
  93. package/dist/verify-compare.d.ts +43 -0
  94. package/dist/verify-compare.js +237 -0
  95. package/dist/verify-determinism.d.ts +16 -0
  96. package/dist/verify-determinism.js +88 -0
  97. package/dist/verify-report.d.ts +53 -0
  98. package/dist/verify-report.js +141 -0
  99. package/dist/verify-tree.d.ts +27 -0
  100. package/dist/verify-tree.js +95 -0
  101. package/dist/viewer-bin.d.ts +6 -0
  102. package/dist/viewer-bin.js +24 -0
  103. package/dist/zip.d.ts +2 -2
  104. package/package.json +3 -2
package/dist/flow-lint.js CHANGED
@@ -1,11 +1,34 @@
1
1
  // Static analysis of flow-files. Catches common authoring mistakes at write-time, before a run.
2
2
  // Pure-static — no Playwright, no live page. Run via `docsxai lint`.
3
3
  import { locatorRefName, referencedLocatorNames } from "./flow-file.js";
4
+ import { hiddenAtEachStep } from "./flow-hidden.js";
5
+ import { lintMatrix } from "./flow-matrix-lint.js";
4
6
  /** Heuristic — names that suggest a step kicks off a multi-minute backend op. */
5
7
  const LONG_ASYNC = /generate|create|process|submit|upload|translate|render|publish|export/i;
6
8
  /** A "bare" data-attribute selector like `[data-foo="x"]` with no further qualifier. */
7
9
  const BARE_DATA_ATTR = /^\[data-[a-z][a-z0-9-]*="[^"]+"\]$/;
8
10
  const DEEP_CHAIN_THRESHOLD = 4;
11
+ /** Actions that wait on their `target`, so an absent target costs the whole default timeout. */
12
+ const TARGET_WAIT_ACTIONS = new Set([
13
+ "click",
14
+ "fill",
15
+ "upload",
16
+ "press",
17
+ "hover",
18
+ "select",
19
+ "check",
20
+ "uncheck",
21
+ "hide",
22
+ ]);
23
+ /** Steps that stall the full default wait when their element is absent, and set no shorter one. */
24
+ function waitsFullDefault(step) {
25
+ if (step.timeout_ms !== undefined)
26
+ return false;
27
+ if (TARGET_WAIT_ACTIONS.has(step.action))
28
+ return step.target !== undefined;
29
+ const w = step.wait_for;
30
+ return (step.action === "wait" && typeof w === "object" && "selector" in w && w.timeout_ms === undefined);
31
+ }
9
32
  export async function lintFlow(flow, opts = {}) {
10
33
  const issues = [];
11
34
  // R001 — extends chain depth; R005 — extends target missing
@@ -43,6 +66,8 @@ export async function lintFlow(flow, opts = {}) {
43
66
  });
44
67
  }
45
68
  }
69
+ // R015 — the variants a `matrix` expands to; R016 — `copy_by_locale` keys no variant uses
70
+ issues.push(...lintMatrix(flow));
46
71
  // R007 — terminal step lacks `success` (with `extends`, this flow's steps run last, so its
47
72
  // final step IS the merged flow's terminal step)
48
73
  const lastStep = flow.steps[flow.steps.length - 1];
@@ -63,7 +88,8 @@ export async function lintFlow(flow, opts = {}) {
63
88
  return name ? (flow.locators[name] ?? v) : v;
64
89
  };
65
90
  const flowRedactionSelectors = new Set((flow.redactions ?? []).flatMap((r) => ("selector" in r ? [resolveMaybe(r.selector)] : [])));
66
- for (const step of flow.steps) {
91
+ const hiddenAt = hiddenAtEachStep(flow, resolveMaybe);
92
+ for (const [index, step] of flow.steps.entries()) {
67
93
  const anns = step.annotation ? [step.annotation] : (step.annotations ?? []);
68
94
  // R002 — annotation anchored to a likely-unmounting action target
69
95
  if (anns.length && (step.action === "click" || step.action === "navigate") && step.target) {
@@ -121,6 +147,56 @@ export async function lintFlow(flow, opts = {}) {
121
147
  suggestion: "add a `wait_for: { selector: … }` or a `success:` check to make the presence test explicit",
122
148
  });
123
149
  }
150
+ // R011 — optional step with no short timeout: a miss costs the full default wait
151
+ if (step.optional && waitsFullDefault(step)) {
152
+ issues.push({
153
+ code: "R011",
154
+ severity: "info",
155
+ flow: flow.name,
156
+ stepId: step.id,
157
+ message: "`optional: true` step has no `timeout_ms` — when its element is absent the run waits Playwright's full 30 s default before skipping it",
158
+ suggestion: step.action === "wait"
159
+ ? "add `timeout_ms: 1500` to the step (or to its `wait_for`) so a miss is skipped fast"
160
+ : "add `timeout_ms: 1500` (100–30000) so a miss is skipped fast; keep the default only if the element can legitimately take longer to appear",
161
+ });
162
+ }
163
+ // R012 — `hide` with no target (the runtime would halt on it)
164
+ if (step.action === "hide" && !step.target) {
165
+ issues.push({
166
+ code: "R012",
167
+ severity: "error",
168
+ flow: flow.name,
169
+ stepId: step.id,
170
+ message: "`hide` has no `target` — there is nothing to hide, and the run halts on this step",
171
+ suggestion: "set `target` to the element (a `$ref` or an inline selector) to hide",
172
+ });
173
+ }
174
+ // R013 — step reaches an element an earlier `hide` step hid: a hidden element isn't visible,
175
+ // so a click waits out its timeout, an annotation has nothing to anchor to, a visible-wait never ends
176
+ const reached = [];
177
+ if (step.target && !["hide", "show", "navigate"].includes(step.action))
178
+ reached.push([step.target, `\`${step.action}\` target`, hiddenAt[index].before]);
179
+ for (const ann of anns) {
180
+ const anchor = ann.target ?? step.target;
181
+ if (anchor)
182
+ reached.push([anchor, "annotation anchor", hiddenAt[index].after]);
183
+ }
184
+ if (step.wait_for && typeof step.wait_for === "object" && "selector" in step.wait_for)
185
+ reached.push([step.wait_for.selector, "`wait_for` selector", hiddenAt[index].after]);
186
+ if (step.success && "visible" in step.success)
187
+ reached.push([step.success.visible, "`success.visible` selector", hiddenAt[index].after]);
188
+ for (const [ref, role, hidden] of reached) {
189
+ if (!hidden.has(resolveMaybe(ref)))
190
+ continue;
191
+ issues.push({
192
+ code: "R013",
193
+ severity: "warning",
194
+ flow: flow.name,
195
+ stepId: step.id,
196
+ message: `${role} \`${ref}\` is hidden by an earlier \`hide\` step, so it can never be visible here`,
197
+ suggestion: "add a `show` step (with this target, or none to show everything) before this step, or move the `hide` after it",
198
+ });
199
+ }
124
200
  // R009 — element_stable with no selector context (a no-op)
125
201
  if (step.wait_for === "element_stable" && !step.target) {
126
202
  issues.push({
@@ -132,6 +208,20 @@ export async function lintFlow(flow, opts = {}) {
132
208
  suggestion: "give the step a `target`, or wait on a concrete element with `wait_for: { selector: $x }`",
133
209
  });
134
210
  }
211
+ // R014 — a bare `wait` step that only sleeps (a guess at how long the page needs to settle)
212
+ if (step.action === "wait" &&
213
+ typeof step.wait_for === "object" &&
214
+ "timeout_ms" in step.wait_for &&
215
+ !("selector" in step.wait_for)) {
216
+ issues.push({
217
+ code: "R014",
218
+ severity: "info",
219
+ flow: flow.name,
220
+ stepId: step.id,
221
+ message: `\`wait_for: { timeout_ms: ${step.wait_for.timeout_ms} }\` is a blind sleep: it waits that long whether or not the page needed it`,
222
+ suggestion: "use `wait_for: settled` (fonts, visible images and layout), or wait on a concrete element with `wait_for: { selector: $x }`; keep the sleep only for an animation nothing else can detect",
223
+ });
224
+ }
135
225
  // R010 — annotation anchored to a redacted element (the call-out would point at a black box)
136
226
  const stepRedactionSelectors = new Set([
137
227
  ...flowRedactionSelectors,
@@ -0,0 +1,10 @@
1
+ import type { FlowFile } from "./doc-pack.js";
2
+ export type MatrixLintIssue = {
3
+ code: string;
4
+ severity: "info" | "warning";
5
+ flow: string;
6
+ stepId?: string;
7
+ message: string;
8
+ suggestion?: string;
9
+ };
10
+ export declare function lintMatrix(flow: FlowFile): MatrixLintIssue[];
@@ -0,0 +1,40 @@
1
+ // Lint rules for the flow matrix. Pure-static, like `flow-lint.ts`, which runs them.
2
+ // R015 (info) — the variants the flow's `matrix` expands to, in run order
3
+ // R016 (warning) — a `copy_by_locale` key that no variant locale can use
4
+ import { matrixVariantIds } from "./flow-matrix.js";
5
+ /** A `copy_by_locale` key serves a locale when it is that tag or its language. */
6
+ function serves(key, locale) {
7
+ const k = key.toLowerCase();
8
+ const l = locale.toLowerCase();
9
+ return k === l || k === l.split("-")[0];
10
+ }
11
+ export function lintMatrix(flow) {
12
+ const issues = [];
13
+ if (flow.matrix) {
14
+ const ids = matrixVariantIds(flow.matrix);
15
+ issues.push({
16
+ code: "R015",
17
+ severity: "info",
18
+ flow: flow.name,
19
+ message: `\`matrix\` expands to ${ids.length} variant${ids.length !== 1 ? "s" : ""}: ${ids.join(", ")}`,
20
+ });
21
+ }
22
+ const locales = flow.matrix?.locales ?? (flow.environment?.locale ? [flow.environment.locale] : []);
23
+ for (const step of flow.steps) {
24
+ const anns = step.annotation ? [step.annotation] : (step.annotations ?? []);
25
+ for (const ann of anns) {
26
+ const dead = Object.keys(ann.copy_by_locale ?? {}).filter((key) => !locales.some((l) => serves(key, l)));
27
+ if (dead.length === 0)
28
+ continue;
29
+ issues.push({
30
+ code: "R016",
31
+ severity: "warning",
32
+ flow: flow.name,
33
+ stepId: step.id,
34
+ message: `\`copy_by_locale\` key${dead.length !== 1 ? "s" : ""} ${dead.map((k) => `\`${k}\``).join(", ")} match${dead.length === 1 ? "es" : ""} no variant locale (${locales.length ? locales.join(", ") : "the flow has no matrix locales and no environment.locale"}), so ${dead.length !== 1 ? "they are" : "it is"} never used`,
35
+ suggestion: "add the locale to `matrix.locales` (or set `environment.locale`), or fix the key to a tag or language the flow runs",
36
+ });
37
+ }
38
+ }
39
+ return issues;
40
+ }
@@ -0,0 +1,44 @@
1
+ import type { FlowFile, StepAnnotation } from "./doc-pack.js";
2
+ import type { ColorScheme } from "./environment-spec.js";
3
+ import { type MatrixSpec, type ResolvedMatrixViewport, type VariantInfo } from "./matrix-spec.js";
4
+ /** Thrown when a flow's `matrix`, `only`/`skip` or `copy_by_locale` cannot expand. */
5
+ export declare class FlowMatrixError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ /** One cell of the matrix: the value on each axis the matrix names. */
9
+ export interface VariantCombo {
10
+ locale?: string;
11
+ color_scheme?: ColorScheme;
12
+ viewport?: ResolvedMatrixViewport;
13
+ }
14
+ /** A flow resolved for one variant. `id` and `info` are null for a flow without a `matrix`. */
15
+ export interface FlowVariant {
16
+ id: string | null;
17
+ info: VariantInfo | null;
18
+ /** The flow to run: no `matrix`, no `only`/`skip`, `copy` resolved, `environment` overridden. */
19
+ flow: FlowFile;
20
+ }
21
+ /** The cells of a matrix: locales outermost, then color schemes, then viewports, each in declared order. */
22
+ export declare function matrixCombos(matrix: MatrixSpec): VariantCombo[];
23
+ /** `<locale>.<color_scheme>.<viewport name>`, leaving out the axes the matrix does not name. */
24
+ export declare function variantId(combo: VariantCombo): string;
25
+ /** The ids a matrix expands to, in expansion order. */
26
+ export declare function matrixVariantIds(matrix: MatrixSpec): string[];
27
+ /** Doc-pack directory (relative to the workspace) holding a flow's outputs for a variant. */
28
+ export declare function variantDocDir(flow: string, variant: string | null | undefined): string;
29
+ /** True when `want` is `have` or its language (`es` matches `es-ES`), ignoring case. */
30
+ export declare function localeMatches(want: string, have: string): boolean;
31
+ /** Call-out text for a locale: the exact tag, then its language, else `copy`. */
32
+ export declare function pickCopy(ann: StepAnnotation, locale: string | undefined): string;
33
+ /**
34
+ * Expand a flow into its variants. A flow without a `matrix` returns itself, `id: null`, unless it
35
+ * uses `only`/`skip` (an error: they need a matrix) or `copy_by_locale` (resolved against
36
+ * `environment.locale`). Throws {@link FlowMatrixError} on a selector no matrix entry can match, or
37
+ * on a variant left with no steps.
38
+ */
39
+ export declare function expandFlow(flow: FlowFile): FlowVariant[];
40
+ /**
41
+ * Expand a set of flows into their variants, in the order given. Throws {@link FlowMatrixError}
42
+ * when two flow names differ only by case: both would write `docs/<name>/` on a case-insensitive disk.
43
+ */
44
+ export declare function expandFlows(flows: readonly FlowFile[]): FlowVariant[];
@@ -0,0 +1,238 @@
1
+ // Flow matrix expansion: one flow-file becomes one flow per variant (locale x color scheme x
2
+ // viewport). Pure and deterministic: the output depends only on the parsed flow, in declared
3
+ // order, so two parses of one file expand identically. See
4
+ // docs/ai-context/architecture/flow-matrix-decision.md for the design.
5
+ //
6
+ // A flow without a `matrix` expands to itself (`id: null`), with the one addition that
7
+ // `copy_by_locale` resolves against `environment.locale`. That path adds nothing to the output
8
+ // of a flow that uses none of the matrix keys: the returned flow is the input object.
9
+ import { findCaseCollision } from "./flow-name-rules.js";
10
+ import { resolveMatrixViewport, } from "./matrix-spec.js";
11
+ /** Thrown when a flow's `matrix`, `only`/`skip` or `copy_by_locale` cannot expand. */
12
+ export class FlowMatrixError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = "FlowMatrixError";
16
+ }
17
+ }
18
+ /** The cells of a matrix: locales outermost, then color schemes, then viewports, each in declared order. */
19
+ export function matrixCombos(matrix) {
20
+ const combos = [];
21
+ const viewports = matrix.viewports?.map(resolveMatrixViewport);
22
+ for (const locale of matrix.locales ?? [undefined]) {
23
+ for (const color_scheme of matrix.color_schemes ?? [undefined]) {
24
+ for (const viewport of viewports ?? [undefined]) {
25
+ combos.push({
26
+ ...(locale !== undefined ? { locale } : {}),
27
+ ...(color_scheme !== undefined ? { color_scheme } : {}),
28
+ ...(viewport !== undefined ? { viewport } : {}),
29
+ });
30
+ }
31
+ }
32
+ }
33
+ return combos;
34
+ }
35
+ /** `<locale>.<color_scheme>.<viewport name>`, leaving out the axes the matrix does not name. */
36
+ export function variantId(combo) {
37
+ return [combo.locale, combo.color_scheme, combo.viewport?.name]
38
+ .filter((s) => s !== undefined)
39
+ .join(".");
40
+ }
41
+ /** The ids a matrix expands to, in expansion order. */
42
+ export function matrixVariantIds(matrix) {
43
+ return matrixCombos(matrix).map(variantId);
44
+ }
45
+ function variantInfo(combo) {
46
+ return {
47
+ id: variantId(combo),
48
+ ...(combo.locale !== undefined ? { locale: combo.locale } : {}),
49
+ ...(combo.color_scheme !== undefined ? { color_scheme: combo.color_scheme } : {}),
50
+ ...(combo.viewport !== undefined ? { viewport: combo.viewport } : {}),
51
+ };
52
+ }
53
+ /** Doc-pack directory (relative to the workspace) holding a flow's outputs for a variant. */
54
+ export function variantDocDir(flow, variant) {
55
+ return variant ? `docs/${flow}/${variant}` : `docs/${flow}`;
56
+ }
57
+ /** True when `want` is `have` or its language (`es` matches `es-ES`), ignoring case. */
58
+ export function localeMatches(want, have) {
59
+ const w = want.toLowerCase();
60
+ const h = have.toLowerCase();
61
+ return h === w || h.startsWith(`${w}-`);
62
+ }
63
+ function axisMatches(sel, axis, combo) {
64
+ const wanted = sel[axis];
65
+ if (wanted === undefined)
66
+ return true;
67
+ if (axis === "locale") {
68
+ const have = combo.locale;
69
+ return have !== undefined && wanted.some((w) => localeMatches(w, have));
70
+ }
71
+ const have = axis === "viewport" ? combo.viewport?.name : combo.color_scheme;
72
+ return have !== undefined && wanted.includes(have);
73
+ }
74
+ function selectorMatches(sel, combo) {
75
+ return ["viewport", "color_scheme", "locale"].every((a) => axisMatches(sel, a, combo));
76
+ }
77
+ /** Kept when `only` (if any) matches and `skip` (if any) does not. */
78
+ function applies(item, combo) {
79
+ if (item.only && !selectorMatches(item.only, combo))
80
+ return false;
81
+ return !(item.skip && selectorMatches(item.skip, combo));
82
+ }
83
+ /** Call-out text for a locale: the exact tag, then its language, else `copy`. */
84
+ export function pickCopy(ann, locale) {
85
+ const byLocale = ann.copy_by_locale;
86
+ if (!byLocale || locale === undefined)
87
+ return ann.copy;
88
+ const find = (tag) => {
89
+ const key = Object.keys(byLocale).find((k) => k.toLowerCase() === tag.toLowerCase());
90
+ return key === undefined ? undefined : byLocale[key];
91
+ };
92
+ return find(locale) ?? find(locale.split("-")[0]) ?? ann.copy;
93
+ }
94
+ function resolveAnnotation(ann, combo, locale) {
95
+ if (!applies(ann, combo))
96
+ return undefined;
97
+ if (!ann.only && !ann.skip && !ann.copy_by_locale)
98
+ return ann;
99
+ const { only: _only, skip: _skip, copy_by_locale: _copy, ...rest } = ann;
100
+ return { ...rest, copy: pickCopy(ann, locale) };
101
+ }
102
+ function touchesVariants(step) {
103
+ const hasKeys = (a) => !!(a.only || a.skip || a.copy_by_locale);
104
+ return !!(step.only ||
105
+ step.skip ||
106
+ (step.annotation && hasKeys(step.annotation)) ||
107
+ step.annotations?.some(hasKeys));
108
+ }
109
+ function resolveStep(step, combo, locale) {
110
+ if (!applies(step, combo))
111
+ return undefined;
112
+ if (!touchesVariants(step))
113
+ return step;
114
+ const { only: _only, skip: _skip, annotation, annotations, ...rest } = step;
115
+ const out = { ...rest };
116
+ if (annotation) {
117
+ const a = resolveAnnotation(annotation, combo, locale);
118
+ if (a)
119
+ out.annotation = a;
120
+ }
121
+ if (annotations) {
122
+ const list = annotations
123
+ .map((a) => resolveAnnotation(a, combo, locale))
124
+ .filter((a) => a !== undefined);
125
+ if (list.length > 0)
126
+ out.annotations = list;
127
+ }
128
+ return out;
129
+ }
130
+ /** Every `only`/`skip` selector in the flow, with where it sits. */
131
+ function selectorsOf(flow) {
132
+ const found = [];
133
+ const add = (where, kind, item) => {
134
+ const sel = item[kind];
135
+ if (sel)
136
+ found.push({ where: `${where} \`${kind}\``, sel });
137
+ };
138
+ for (const step of flow.steps) {
139
+ const at = `step "${step.id}"`;
140
+ for (const kind of ["only", "skip"]) {
141
+ add(at, kind, step);
142
+ if (step.annotation)
143
+ add(`${at} annotation`, kind, step.annotation);
144
+ step.annotations?.forEach((a, i) => add(`${at} annotations[${i}]`, kind, a));
145
+ }
146
+ }
147
+ return found;
148
+ }
149
+ /** Throws unless every value a selector names can match some entry of the matrix. */
150
+ function assertSelectorsResolve(flow, matrix) {
151
+ const names = matrix.viewports?.map((v) => resolveMatrixViewport(v).name);
152
+ const known = {
153
+ viewport: names,
154
+ color_scheme: matrix.color_schemes,
155
+ locale: matrix.locales,
156
+ };
157
+ const problems = [];
158
+ for (const { where, sel } of selectorsOf(flow)) {
159
+ for (const axis of ["viewport", "color_scheme", "locale"]) {
160
+ const wanted = sel[axis];
161
+ if (wanted === undefined)
162
+ continue;
163
+ const axisValues = known[axis];
164
+ if (axisValues === undefined) {
165
+ const key = axis === "color_scheme" ? "color_schemes" : `${axis}s`;
166
+ problems.push(`${where}: names \`${axis}\` but the matrix has no \`${key}\``);
167
+ continue;
168
+ }
169
+ for (const w of wanted) {
170
+ const ok = axis === "locale" ? axisValues.some((l) => localeMatches(w, l)) : axisValues.includes(w);
171
+ if (!ok)
172
+ problems.push(`${where}: ${axis} "${w}" is not in the matrix (${axisValues.join(", ")})`);
173
+ }
174
+ }
175
+ }
176
+ if (problems.length > 0) {
177
+ throw new FlowMatrixError(`flow "${flow.name}": \`only\`/\`skip\` do not match the matrix:\n${problems.map((p) => ` • ${p}`).join("\n")}`);
178
+ }
179
+ }
180
+ function withEnvironment(flow, combo) {
181
+ const env = {
182
+ ...flow.environment,
183
+ ...(combo.locale !== undefined ? { locale: combo.locale } : {}),
184
+ ...(combo.color_scheme !== undefined ? { color_scheme: combo.color_scheme } : {}),
185
+ ...(combo.viewport !== undefined
186
+ ? { viewport: { width: combo.viewport.width, height: combo.viewport.height } }
187
+ : {}),
188
+ };
189
+ return Object.keys(env).length > 0 ? env : undefined;
190
+ }
191
+ /**
192
+ * Expand a flow into its variants. A flow without a `matrix` returns itself, `id: null`, unless it
193
+ * uses `only`/`skip` (an error: they need a matrix) or `copy_by_locale` (resolved against
194
+ * `environment.locale`). Throws {@link FlowMatrixError} on a selector no matrix entry can match, or
195
+ * on a variant left with no steps.
196
+ */
197
+ export function expandFlow(flow) {
198
+ const { matrix, ...rest } = flow;
199
+ if (!matrix) {
200
+ const bad = selectorsOf(flow);
201
+ if (bad.length > 0) {
202
+ throw new FlowMatrixError(`flow "${flow.name}": ${bad[0].where} needs a \`matrix\`${bad.length > 1 ? ` (so do ${bad.length - 1} more uses of \`only\`/\`skip\`)` : ""}; a flow without one has a single variant`);
203
+ }
204
+ const locale = flow.environment?.locale;
205
+ const steps = flow.steps.map((s) => resolveStep(s, {}, locale));
206
+ const same = steps.every((s, i) => s === flow.steps[i]);
207
+ return [{ id: null, info: null, flow: same ? flow : { ...flow, steps } }];
208
+ }
209
+ assertSelectorsResolve(flow, matrix);
210
+ return matrixCombos(matrix).map((combo) => {
211
+ const locale = combo.locale ?? flow.environment?.locale;
212
+ const steps = flow.steps
213
+ .map((s) => resolveStep(s, combo, locale))
214
+ .filter((s) => s !== undefined);
215
+ const id = variantId(combo);
216
+ if (steps.length === 0) {
217
+ throw new FlowMatrixError(`flow "${flow.name}": variant "${id}" has no steps left after \`only\`/\`skip\``);
218
+ }
219
+ const environment = withEnvironment(flow, combo);
220
+ const { environment: _env, ...withoutEnv } = rest;
221
+ return {
222
+ id,
223
+ info: variantInfo(combo),
224
+ flow: { ...withoutEnv, ...(environment ? { environment } : {}), steps },
225
+ };
226
+ });
227
+ }
228
+ /**
229
+ * Expand a set of flows into their variants, in the order given. Throws {@link FlowMatrixError}
230
+ * when two flow names differ only by case: both would write `docs/<name>/` on a case-insensitive disk.
231
+ */
232
+ export function expandFlows(flows) {
233
+ const clash = findCaseCollision(flows.map((f) => f.name));
234
+ if (clash) {
235
+ throw new FlowMatrixError(`flows "${clash[0]}" and "${clash[1]}" differ only by case and would share one directory on a case-insensitive disk; rename one`);
236
+ }
237
+ return flows.flatMap((flow) => expandFlow(flow));
238
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * True when Windows would treat `name` as a device: the part before the first `.` is `con`, `prn`,
3
+ * `aux`, `nul`, `com1`-`com9` or `lpt1`-`lpt9`, in any case. `con`, `CON.v2` and `lpt1.flow` all
4
+ * qualify, `console` does not.
5
+ */
6
+ export declare function isWindowsDeviceName(name: string): boolean;
7
+ /** True when `name` ends in a dot, which Windows drops from a file name. */
8
+ export declare function hasTrailingDot(name: string): boolean;
9
+ /**
10
+ * The first two names in `names` that differ only by case, in the order given, or null. Exact
11
+ * duplicates are not a collision. A case-insensitive disk (macOS, Windows) writes both to one path.
12
+ */
13
+ export declare function findCaseCollision(names: Iterable<string>): [string, string] | null;
14
+ /** Throws an `Error` naming the colliding pair, or returns. `what` reads as "flow names", "variant ids". */
15
+ export declare function assertNoCaseCollision(names: Iterable<string>, what: string): void;
@@ -0,0 +1,39 @@
1
+ // Name rules a flow name shares with the file system it lands on: Windows device names, a
2
+ // trailing dot, and two names that are one directory on a case-insensitive disk. Pure, so the
3
+ // schema (`FlowName`), the pull validator and the loaders that gather a set of names all agree.
4
+ const WINDOWS_DEVICE_STEM = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
5
+ /**
6
+ * True when Windows would treat `name` as a device: the part before the first `.` is `con`, `prn`,
7
+ * `aux`, `nul`, `com1`-`com9` or `lpt1`-`lpt9`, in any case. `con`, `CON.v2` and `lpt1.flow` all
8
+ * qualify, `console` does not.
9
+ */
10
+ export function isWindowsDeviceName(name) {
11
+ return WINDOWS_DEVICE_STEM.test(name.split(".", 1)[0] ?? "");
12
+ }
13
+ /** True when `name` ends in a dot, which Windows drops from a file name. */
14
+ export function hasTrailingDot(name) {
15
+ return name.endsWith(".");
16
+ }
17
+ /**
18
+ * The first two names in `names` that differ only by case, in the order given, or null. Exact
19
+ * duplicates are not a collision. A case-insensitive disk (macOS, Windows) writes both to one path.
20
+ */
21
+ export function findCaseCollision(names) {
22
+ const seen = new Map();
23
+ for (const name of names) {
24
+ const key = name.toLowerCase();
25
+ const earlier = seen.get(key);
26
+ if (earlier !== undefined && earlier !== name)
27
+ return [earlier, name];
28
+ if (earlier === undefined)
29
+ seen.set(key, name);
30
+ }
31
+ return null;
32
+ }
33
+ /** Throws an `Error` naming the colliding pair, or returns. `what` reads as "flow names", "variant ids". */
34
+ export function assertNoCaseCollision(names, what) {
35
+ const pair = findCaseCollision(names);
36
+ if (pair) {
37
+ throw new Error(`${what} "${pair[0]}" and "${pair[1]}" differ only by case and would share one directory on a case-insensitive disk; rename one`);
38
+ }
39
+ }
@@ -1,4 +1,4 @@
1
- import { type AnnotationsFile, type BoundingBox, type FlowFile, type RedactionRegion, type RedactionStyle, type Step } from "./doc-pack.js";
1
+ import { type AnnotationsFile, type BoundingBox, type FlowFile, type RedactionRegion, type RedactionStyle, type Step, type VariantInfo } from "./doc-pack.js";
2
2
  import { type NearbyBoxes } from "./obstacles.js";
3
3
  /**
4
4
  * A redaction with its locator ref already resolved to a concrete selector. `selector` entries are
@@ -16,16 +16,48 @@ export type ResolvedRedaction = {
16
16
  /** What the runtime needs from a browser. Selectors passed here are already resolved (no `$ref`). */
17
17
  export interface BrowserDriver {
18
18
  goto(url: string): Promise<void>;
19
- click(selector: string): Promise<void>;
20
- fill(selector: string, value: string): Promise<void>;
21
- upload(selector: string, filePath: string): Promise<void>;
22
- press(selector: string | null, key: string): Promise<void>;
23
- hover(selector: string): Promise<void>;
24
- selectOption(selector: string, value: string): Promise<void>;
25
- setChecked(selector: string, checked: boolean): Promise<void>;
19
+ /**
20
+ * The seven target actions take an optional `timeoutMs`: how long to wait for the target to become
21
+ * actionable before throwing. Undefined keeps the driver default, so a step without `timeout_ms`
22
+ * behaves exactly as before.
23
+ */
24
+ click(selector: string, timeoutMs?: number): Promise<void>;
25
+ fill(selector: string, value: string, timeoutMs?: number): Promise<void>;
26
+ upload(selector: string, filePath: string, timeoutMs?: number): Promise<void>;
27
+ press(selector: string | null, key: string, timeoutMs?: number): Promise<void>;
28
+ hover(selector: string, timeoutMs?: number): Promise<void>;
29
+ selectOption(selector: string, value: string, timeoutMs?: number): Promise<void>;
30
+ setChecked(selector: string, checked: boolean, timeoutMs?: number): Promise<void>;
31
+ /**
32
+ * Hide every element `selector` matches: `visibility: hidden`, so the element keeps its box and
33
+ * nothing reflows, and it stays out of every later screenshot (halt shots too). Waits up to
34
+ * `timeoutMs` for a match to exist, throws if none does. The hiding is by selector and holds for
35
+ * the rest of the session, across navigations and re-renders, until {@link showElements}.
36
+ * Implementations apply a fixed engine-owned rule; the selector is data, never CSS or script.
37
+ *
38
+ * Optional, like {@link waitForSettled}: a driver written before `hide` existed still satisfies the
39
+ * interface. The runtime halts a `hide` step on a driver without it, with a message naming the method.
40
+ */
41
+ hideElements?(selector: string, timeoutMs?: number): Promise<void>;
42
+ /**
43
+ * Undo {@link hideElements} for the selector as it was given there, or for everything when `null`. Instant; matching nothing is fine.
44
+ * Optional; the runtime halts a `show` step on a driver without it, with a message naming the method.
45
+ */
46
+ showElements?(selector: string | null): Promise<void>;
26
47
  waitForNetworkIdle(): Promise<void>;
27
48
  waitForLoad(): Promise<void>;
28
49
  waitForElementStable(selector: string): Promise<void>;
50
+ /**
51
+ * Wait until the page has settled: web fonts loaded, the images inside the viewport finished
52
+ * loading, and the layout of the viewport-visible elements unchanged across consecutive frames.
53
+ * Bounded by `timeoutMs` (default 10 s); rejects with a message starting `settled: page did not
54
+ * settle` and naming what was still moving when the budget ran out. Selector-free: an
55
+ * implementation runs a fixed engine-owned check, and no flow value reaches the page.
56
+ *
57
+ * Optional so a driver written before `settled` existed still satisfies the interface. The
58
+ * runtime halts a `wait_for: settled` step on a driver without it, with a message that says so.
59
+ */
60
+ waitForSettled?(timeoutMs?: number): Promise<void>;
29
61
  /** Wait for `selector` to appear. `timeoutMs` overrides the driver's default (use for slow backend ops). */
30
62
  waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
31
63
  waitForTimeout(ms: number): Promise<void>;
@@ -47,8 +79,11 @@ export interface BrowserDriver {
47
79
  * driver's; `selectObstacles` sorts, clips and caps. Returns `null` when the target isn't visible
48
80
  * within `timeoutMs`; rejects if the scan itself runs past `timeoutMs`. The scan happens after the
49
81
  * screenshot, so a continuously animating page can drift from the image. Only called when a workspace turns on `annotations.obstacles`.
82
+ *
83
+ * Optional. With `annotations.obstacles` on, the runtime halts an annotated step on a driver
84
+ * without it, with a message naming the method; with it off, the method is never called.
50
85
  */
51
- nearbyBoxes(selector: string, radius: number, timeoutMs?: number): Promise<NearbyBoxes | null>;
86
+ nearbyBoxes?(selector: string, radius: number, timeoutMs?: number): Promise<NearbyBoxes | null>;
52
87
  /** Capture a clean screenshot (no baked annotations), applying any `redactions` before it hits disk. */
53
88
  screenshot(relPath: string, redactions?: ResolvedRedaction[]): Promise<void>;
54
89
  /**
@@ -70,23 +105,18 @@ export interface BrowserDriver {
70
105
  * (off-screen, covered). Listed in the order calibration usually cares about them.
71
106
  */
72
107
  export type ActionableState = "actionable" | "not-found" | "multiple-matches" | "detached" | "not-visible" | "off-screen" | "covered" | "disabled";
73
- export declare class FlowExecutionError extends Error {
74
- readonly stepId: string;
75
- readonly cause?: unknown;
76
- constructor(message: string, stepId: string, cause?: unknown);
77
- }
78
- /**
79
- * Best-effort 1-line cause extracted from a Playwright actionability log (or similar driver
80
- * error). Returns undefined when nothing matches — keeps the halt message short rather than
81
- * guessing. Surfaced as a `[cause]` prefix on the halt message so the agent doesn't have to
82
- * scan the multi-line actionability log.
83
- */
84
- export declare function inferHaltCause(rawError: string): string | undefined;
108
+ export { FlowExecutionError, inferHaltCause } from "./flow-halt.js";
85
109
  export interface RunFlowOptions {
86
110
  /** Resolve a locator name → selector. Defaults to the flow-file's own `locators` map. */
87
111
  resolveLocator?: (name: string) => string | undefined;
88
- /** Where screenshots are written, relative to the doc pack root. Default: `docs/<flow>/screenshots/<step>.png`. */
112
+ /** Where screenshots are written, relative to the doc pack root. Default: `docs/<flow>/screenshots/<step>.png`, or `docs/<flow>/<variant>/screenshots/<step>.png` with `variant`. */
89
113
  screenshotPath?: (flow: string, stepId: string) => string;
114
+ /**
115
+ * The matrix variant `flow` was expanded for (from `expandFlow`). Moves the default screenshot and
116
+ * halt-shot paths under `docs/<flow>/<variant>/`, names the variant in a halt message, and is recorded
117
+ * as `variant` in the returned annotations. Absent for a flow without a `matrix`: output is unchanged.
118
+ */
119
+ variant?: VariantInfo;
90
120
  /** If false, skip screenshot/annotation capture (pure flow validation). Default: true. */
91
121
  captureDocs?: boolean;
92
122
  /** If set, stop after executing the step with this id — run only a prefix of the flow (for calibration). */