@docsxai/engine 0.2.0 → 0.3.0-rc.1

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 (89) hide show
  1. package/README.md +26 -6
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.js +6 -2
  5. package/dist/backend-client-contracts.d.ts +2 -0
  6. package/dist/calibrate.js +5 -0
  7. package/dist/cli-commands-authoring.js +23 -4
  8. package/dist/cli-commands-backend.js +2 -2
  9. package/dist/cli-commands-docpack.d.ts +5 -0
  10. package/dist/cli-commands-docpack.js +70 -24
  11. package/dist/cli-commands-pack.d.ts +2 -0
  12. package/dist/cli-commands-pack.js +69 -0
  13. package/dist/cli-commands-session.js +92 -88
  14. package/dist/cli-retired.d.ts +6 -0
  15. package/dist/cli-retired.js +12 -0
  16. package/dist/cli-usage.d.ts +1 -1
  17. package/dist/cli-usage.js +53 -5
  18. package/dist/cli-verify.d.ts +14 -0
  19. package/dist/cli-verify.js +54 -0
  20. package/dist/cli.js +14 -1
  21. package/dist/deprecation.d.ts +19 -0
  22. package/dist/deprecation.js +32 -0
  23. package/dist/diagnose.d.ts +25 -0
  24. package/dist/diagnose.js +69 -3
  25. package/dist/diff-compute.js +1 -0
  26. package/dist/doc-pack-io.d.ts +14 -0
  27. package/dist/doc-pack-io.js +121 -14
  28. package/dist/doc-pack.d.ts +2165 -181
  29. package/dist/doc-pack.js +152 -42
  30. package/dist/doctor-checks.d.ts +1 -1
  31. package/dist/doctor-checks.js +29 -5
  32. package/dist/driver-budget.d.ts +6 -0
  33. package/dist/driver-budget.js +15 -0
  34. package/dist/egress-guard.d.ts +58 -0
  35. package/dist/egress-guard.js +136 -0
  36. package/dist/environment-spec.d.ts +67 -0
  37. package/dist/environment-spec.js +38 -0
  38. package/dist/export/playwright-test.js +42 -10
  39. package/dist/flow-file.d.ts +7 -1
  40. package/dist/flow-file.js +21 -1
  41. package/dist/flow-halt.d.ts +16 -0
  42. package/dist/flow-halt.js +76 -0
  43. package/dist/flow-hidden.d.ts +9 -0
  44. package/dist/flow-hidden.js +20 -0
  45. package/dist/flow-lint.js +91 -1
  46. package/dist/flow-matrix-lint.d.ts +10 -0
  47. package/dist/flow-matrix-lint.js +40 -0
  48. package/dist/flow-matrix.d.ts +44 -0
  49. package/dist/flow-matrix.js +238 -0
  50. package/dist/flow-name-rules.d.ts +15 -0
  51. package/dist/flow-name-rules.js +39 -0
  52. package/dist/flow-runtime.d.ts +67 -21
  53. package/dist/flow-runtime.js +72 -110
  54. package/dist/flow-success.d.ts +3 -0
  55. package/dist/flow-success.js +37 -0
  56. package/dist/flow-tree.d.ts +2 -0
  57. package/dist/flow-tree.js +17 -5
  58. package/dist/flow-wait.d.ts +3 -0
  59. package/dist/flow-wait.js +22 -0
  60. package/dist/index.d.ts +6 -0
  61. package/dist/index.js +6 -0
  62. package/dist/matrix-spec.d.ts +145 -0
  63. package/dist/matrix-spec.js +120 -0
  64. package/dist/obstacles.d.ts +33 -0
  65. package/dist/obstacles.js +72 -0
  66. package/dist/page-hide.d.ts +10 -0
  67. package/dist/page-hide.js +45 -0
  68. package/dist/page-nearby-boxes.d.ts +9 -0
  69. package/dist/page-nearby-boxes.js +92 -0
  70. package/dist/page-settle.d.ts +39 -0
  71. package/dist/page-settle.js +142 -0
  72. package/dist/playwright-driver.d.ts +30 -8
  73. package/dist/playwright-driver.js +88 -18
  74. package/dist/run-flows.d.ts +40 -0
  75. package/dist/run-flows.js +129 -0
  76. package/dist/upload-path.d.ts +15 -0
  77. package/dist/upload-path.js +63 -0
  78. package/dist/verify-compare.d.ts +43 -0
  79. package/dist/verify-compare.js +237 -0
  80. package/dist/verify-determinism.d.ts +16 -0
  81. package/dist/verify-determinism.js +88 -0
  82. package/dist/verify-report.d.ts +53 -0
  83. package/dist/verify-report.js +141 -0
  84. package/dist/verify-tree.d.ts +27 -0
  85. package/dist/verify-tree.js +95 -0
  86. package/dist/viewer-bin.d.ts +6 -0
  87. package/dist/viewer-bin.js +24 -0
  88. package/dist/workspace.d.ts +8 -0
  89. package/package.json +7 -6
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ export declare const ViewportSize: z.ZodObject<{
3
+ width: z.ZodNumber;
4
+ height: z.ZodNumber;
5
+ }, "strict", z.ZodTypeAny, {
6
+ width: number;
7
+ height: number;
8
+ }, {
9
+ width: number;
10
+ height: number;
11
+ }>;
12
+ export type ViewportSize = z.infer<typeof ViewportSize>;
13
+ export declare const ViewportPreset: z.ZodEnum<["desktop", "tablet", "mobile"]>;
14
+ export type ViewportPreset = z.infer<typeof ViewportPreset>;
15
+ /** Named viewport presets — `desktop` 1440×900, `tablet` 834×1112, `mobile` 390×844. */
16
+ export declare const VIEWPORT_PRESETS: Record<ViewportPreset, ViewportSize>;
17
+ /** BCP-47 language tag (e.g. `en-GB`); shared by `environment.locale`, matrix locales and `copy_by_locale` keys. */
18
+ export declare const LocaleTag: z.ZodString;
19
+ export declare const ColorScheme: z.ZodEnum<["light", "dark"]>;
20
+ export type ColorScheme = z.infer<typeof ColorScheme>;
21
+ /**
22
+ * Deterministic execution environment for a flow. All fields optional; applied at browser-context
23
+ * creation (so the whole flow runs under them). With `extends`, the child flow's `environment`
24
+ * wins per-key over the parent's (a child can pin just `viewport` and inherit the parent's clock).
25
+ */
26
+ export declare const EnvironmentSpec: z.ZodObject<{
27
+ /** ISO-8601 instant the page clock is frozen at — `new Date()` etc. return this for the whole run. */
28
+ clock: z.ZodOptional<z.ZodString>;
29
+ /** BCP-47 language tag (e.g. `en-GB`). */
30
+ locale: z.ZodOptional<z.ZodString>;
31
+ /** IANA timezone (e.g. `Europe/Amsterdam`). */
32
+ timezone: z.ZodOptional<z.ZodString>;
33
+ /** `{ width, height }` in CSS pixels, or a named preset — see {@link VIEWPORT_PRESETS}. */
34
+ viewport: z.ZodOptional<z.ZodUnion<[z.ZodEnum<["desktop", "tablet", "mobile"]>, z.ZodObject<{
35
+ width: z.ZodNumber;
36
+ height: z.ZodNumber;
37
+ }, "strict", z.ZodTypeAny, {
38
+ width: number;
39
+ height: number;
40
+ }, {
41
+ width: number;
42
+ height: number;
43
+ }>]>>;
44
+ color_scheme: z.ZodOptional<z.ZodEnum<["light", "dark"]>>;
45
+ reduced_motion: z.ZodOptional<z.ZodBoolean>;
46
+ }, "strict", z.ZodTypeAny, {
47
+ clock?: string | undefined;
48
+ locale?: string | undefined;
49
+ timezone?: string | undefined;
50
+ viewport?: {
51
+ width: number;
52
+ height: number;
53
+ } | "desktop" | "tablet" | "mobile" | undefined;
54
+ color_scheme?: "light" | "dark" | undefined;
55
+ reduced_motion?: boolean | undefined;
56
+ }, {
57
+ clock?: string | undefined;
58
+ locale?: string | undefined;
59
+ timezone?: string | undefined;
60
+ viewport?: {
61
+ width: number;
62
+ height: number;
63
+ } | "desktop" | "tablet" | "mobile" | undefined;
64
+ color_scheme?: "light" | "dark" | undefined;
65
+ reduced_motion?: boolean | undefined;
66
+ }>;
67
+ export type EnvironmentSpec = z.infer<typeof EnvironmentSpec>;
@@ -0,0 +1,38 @@
1
+ // Execution-environment schema: the `environment:` block of a flow-file and the viewport shapes a
2
+ // matrix axis reuses. A leaf module (imports only zod) so `doc-pack.ts` and `matrix-spec.ts` can
3
+ // both depend on it; `doc-pack.ts` re-exports everything here, so importers are unchanged.
4
+ import { z } from "zod";
5
+ export const ViewportSize = z
6
+ .object({ width: z.number().int().positive(), height: z.number().int().positive() })
7
+ .strict();
8
+ export const ViewportPreset = z.enum(["desktop", "tablet", "mobile"]);
9
+ /** Named viewport presets — `desktop` 1440×900, `tablet` 834×1112, `mobile` 390×844. */
10
+ export const VIEWPORT_PRESETS = {
11
+ desktop: { width: 1440, height: 900 },
12
+ tablet: { width: 834, height: 1112 },
13
+ mobile: { width: 390, height: 844 },
14
+ };
15
+ /** BCP-47 language tag (e.g. `en-GB`); shared by `environment.locale`, matrix locales and `copy_by_locale` keys. */
16
+ export const LocaleTag = z
17
+ .string()
18
+ .regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]+)*$/, "must be a BCP-47 language tag (e.g. en-GB)");
19
+ export const ColorScheme = z.enum(["light", "dark"]);
20
+ /**
21
+ * Deterministic execution environment for a flow. All fields optional; applied at browser-context
22
+ * creation (so the whole flow runs under them). With `extends`, the child flow's `environment`
23
+ * wins per-key over the parent's (a child can pin just `viewport` and inherit the parent's clock).
24
+ */
25
+ export const EnvironmentSpec = z
26
+ .object({
27
+ /** ISO-8601 instant the page clock is frozen at — `new Date()` etc. return this for the whole run. */
28
+ clock: z.string().datetime({ offset: true, local: true }).optional(),
29
+ /** BCP-47 language tag (e.g. `en-GB`). */
30
+ locale: LocaleTag.optional(),
31
+ /** IANA timezone (e.g. `Europe/Amsterdam`). */
32
+ timezone: z.string().min(1).optional(),
33
+ /** `{ width, height }` in CSS pixels, or a named preset — see {@link VIEWPORT_PRESETS}. */
34
+ viewport: z.union([ViewportPreset, ViewportSize]).optional(),
35
+ color_scheme: ColorScheme.optional(),
36
+ reduced_motion: z.boolean().optional(),
37
+ })
38
+ .strict();
@@ -69,46 +69,75 @@ function actionLines(step, ids) {
69
69
  const missing = (what) => [
70
70
  `// step "${step.id}": ${step.action} without ${what} — nothing to emit`,
71
71
  ];
72
+ // A step's `timeout_ms` becomes Playwright's per-call `{ timeout }`; absent, the call is unchanged.
73
+ const callOpts = step.timeout_ms !== undefined ? `{ timeout: ${step.timeout_ms} }` : null;
74
+ const call = (method, ...args) => `await ${target}.${method}(${[...args, ...(callOpts ? [callOpts] : [])].join(", ")});`;
72
75
  switch (step.action) {
73
76
  case "navigate":
74
77
  return value === undefined
75
78
  ? missing("a value")
76
79
  : [`await page.goto(${JSON.stringify(value)});`];
77
80
  case "click":
78
- return target === null ? missing("a target") : [`await ${target}.click();`];
81
+ return target === null ? missing("a target") : [call("click")];
79
82
  case "fill":
80
- return target === null
81
- ? missing("a target")
82
- : [`await ${target}.fill(${JSON.stringify(value ?? "")});`];
83
+ return target === null ? missing("a target") : [call("fill", JSON.stringify(value ?? ""))];
83
84
  case "select":
84
85
  return target === null || value === undefined
85
86
  ? missing("a target/value")
86
- : [`await ${target}.selectOption(${JSON.stringify(value)});`];
87
+ : [call("selectOption", JSON.stringify(value))];
87
88
  case "check":
88
- return target === null ? missing("a target") : [`await ${target}.check();`];
89
+ return target === null ? missing("a target") : [call("check")];
89
90
  case "uncheck":
90
- return target === null ? missing("a target") : [`await ${target}.uncheck();`];
91
+ return target === null ? missing("a target") : [call("uncheck")];
91
92
  case "hover":
92
- return target === null ? missing("a target") : [`await ${target}.hover();`];
93
+ return target === null ? missing("a target") : [call("hover")];
93
94
  case "press":
94
95
  if (value === undefined)
95
96
  return missing("a key value");
96
97
  return target === null
97
98
  ? [`await page.keyboard.press(${JSON.stringify(value)});`]
98
- : [`await ${target}.press(${JSON.stringify(value)});`];
99
+ : [call("press", JSON.stringify(value))];
99
100
  case "upload":
100
101
  return target === null || value === undefined
101
102
  ? missing("a target/value")
102
- : [`await ${target}.setInputFiles(${JSON.stringify(value)});`];
103
+ : [call("setInputFiles", JSON.stringify(value))];
103
104
  case "wait":
104
105
  return []; // the step's wait_for carries the semantics
106
+ case "hide":
107
+ return target === null ? missing("a target") : hideLines(target, step.timeout_ms);
108
+ case "show":
109
+ return showLines(target);
105
110
  }
106
111
  }
112
+ // `hide` / `show` have no Playwright call of their own. The generated spec marks the matched
113
+ // elements with the engine's data attribute and gives them an inline `visibility: hidden` (the same
114
+ // look as the engine's rule, layout kept), so a later `show` lifts exactly what a `hide` set. It
115
+ // waits for the element to exist, as the runtime does. The code is the spec's own, in the
116
+ // adopter's suite.
117
+ const HIDE_MARK = "data-docsxai-hidden";
118
+ function hideLines(target, timeoutMs) {
119
+ const wait = timeoutMs !== undefined ? `, timeout: ${timeoutMs}` : "";
120
+ return [
121
+ `await ${target}.first().waitFor({ state: "attached"${wait} });`,
122
+ `await ${target}.evaluateAll((els) => els.forEach((el) => { el.setAttribute("${HIDE_MARK}", ""); el.style.setProperty("visibility", "hidden", "important"); }));`,
123
+ ];
124
+ }
125
+ function showLines(target) {
126
+ const lift = `els.forEach((el) => { el.removeAttribute("${HIDE_MARK}"); el.style.removeProperty("visibility"); })`;
127
+ return [`await ${target ?? `page.locator("[${HIDE_MARK}]")`}.evaluateAll((els) => ${lift});`];
128
+ }
107
129
  function waitLines(wait, step, ids) {
108
130
  if (wait === "network_idle")
109
131
  return [`await page.waitForLoadState("networkidle");`];
110
132
  if (wait === "load")
111
133
  return [`await page.waitForLoadState("load");`];
134
+ if (wait === "settled") {
135
+ // Fonts and network are what a generated spec can wait on without docsxai's in-page poll.
136
+ return [
137
+ `await page.waitForLoadState("networkidle"); // settled`,
138
+ `await page.evaluate(() => document.fonts.ready);`,
139
+ ];
140
+ }
112
141
  if (wait === "element_stable") {
113
142
  // Playwright actions auto-wait for element stability; approximate the standalone wait with a
114
143
  // visibility wait on the step target when there is one.
@@ -163,6 +192,9 @@ export function exportFlowAsPlaywrightTest(flow, options = {}) {
163
192
  if (flow.extends) {
164
193
  throw new Error(`flow "${flow.name}": resolve \`extends\` before exporting (resolveFlowExtends)`);
165
194
  }
195
+ if (flow.matrix) {
196
+ throw new Error(`flow "${flow.name}": a flow with a \`matrix\` has no single spec yet; export one variant (expandFlow) or drop the matrix`);
197
+ }
166
198
  const fileName = options.flowFileName ?? flow.name;
167
199
  const ids = locatorIdentifiers(flow);
168
200
  const lines = [
@@ -1,10 +1,16 @@
1
1
  import { FlowFile } from "./doc-pack.js";
2
+ import { type FlowVariant } from "./flow-matrix.js";
2
3
  export declare class FlowFileError extends Error {
3
4
  readonly cause?: unknown | undefined;
4
5
  constructor(message: string, cause?: unknown | undefined);
5
6
  }
6
7
  /** Parse + validate a flow-file from YAML text. Throws {@link FlowFileError} with a readable message on failure. */
7
8
  export declare function parseFlowFile(yamlText: string, source?: string): FlowFile;
9
+ /**
10
+ * Expand a flow into its matrix variants (see `flow-matrix.ts`), reporting a bad `only`/`skip`
11
+ * or a variant with no steps as a {@link FlowFileError}. A flow without a `matrix` yields one variant.
12
+ */
13
+ export declare function expandFlowVariants(flow: FlowFile, source?: string): FlowVariant[];
8
14
  /** Serialize a {@link FlowFile} back to canonical YAML. */
9
15
  export declare function serializeFlowFile(flow: FlowFile): string;
10
16
  /** Returns the locator name if `value` is a `$name` reference, else `null` (it's an inline selector). */
@@ -15,7 +21,7 @@ export declare function referencedLocatorNames(flow: FlowFile): Set<string>;
15
21
  * Resolve a flow's `extends` chain into a single flow: parent's steps first, then this flow's. `locators` and
16
22
  * `prerequisites` are merged (this flow wins on locator-name collisions); `environment` merges per-key with
17
23
  * this flow's keys winning; `redactions` concatenate (parent's first); step ids must be unique across the
18
- * merge. Chains are followed recursively; cycles throw. `loadFlowFile(name)` parses `flows/<name>.flow.yaml`
24
+ * merge. `matrix` is the child's own (never inherited). Chains are followed recursively; cycles throw. `loadFlowFile(name)` parses `flows/<name>.flow.yaml`
19
25
  * (a flow with its own `extends` un-resolved — this function recurses). The result has no `extends`.
20
26
  */
21
27
  export declare function resolveFlowExtends(flow: FlowFile, loadFlowFile: (name: string) => Promise<FlowFile> | FlowFile, visited?: Set<string>): Promise<FlowFile>;
package/dist/flow-file.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // `FlowFile` value, never raw YAML.
7
7
  import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
8
8
  import { FlowFile } from "./doc-pack.js";
9
+ import { expandFlow, FlowMatrixError } from "./flow-matrix.js";
9
10
  export class FlowFileError extends Error {
10
11
  cause;
11
12
  constructor(message, cause) {
@@ -41,8 +42,25 @@ export function parseFlowFile(yamlText, source = "<flow-file>") {
41
42
  if (!flow.extends)
42
43
  assertLocatorRefsResolve(flow, source);
43
44
  assertStepIdsUnique(flow, source);
45
+ // A flow with `extends` is checked once merged (a parent step may carry the `only`/`skip`).
46
+ if (!flow.extends)
47
+ expandFlowVariants(flow, source);
44
48
  return flow;
45
49
  }
50
+ /**
51
+ * Expand a flow into its matrix variants (see `flow-matrix.ts`), reporting a bad `only`/`skip`
52
+ * or a variant with no steps as a {@link FlowFileError}. A flow without a `matrix` yields one variant.
53
+ */
54
+ export function expandFlowVariants(flow, source) {
55
+ try {
56
+ return expandFlow(flow);
57
+ }
58
+ catch (e) {
59
+ if (e instanceof FlowMatrixError)
60
+ throw new FlowFileError(source ? `${source}: ${e.message}` : e.message, e);
61
+ throw e;
62
+ }
63
+ }
46
64
  /** Serialize a {@link FlowFile} back to canonical YAML. */
47
65
  export function serializeFlowFile(flow) {
48
66
  // Validate on the way out too, so we never write a malformed file.
@@ -138,7 +156,7 @@ function assertStepIdsUnique(flow, source) {
138
156
  * Resolve a flow's `extends` chain into a single flow: parent's steps first, then this flow's. `locators` and
139
157
  * `prerequisites` are merged (this flow wins on locator-name collisions); `environment` merges per-key with
140
158
  * this flow's keys winning; `redactions` concatenate (parent's first); step ids must be unique across the
141
- * merge. Chains are followed recursively; cycles throw. `loadFlowFile(name)` parses `flows/<name>.flow.yaml`
159
+ * merge. `matrix` is the child's own (never inherited). Chains are followed recursively; cycles throw. `loadFlowFile(name)` parses `flows/<name>.flow.yaml`
142
160
  * (a flow with its own `extends` un-resolved — this function recurses). The result has no `extends`.
143
161
  */
144
162
  export async function resolveFlowExtends(flow, loadFlowFile, visited = new Set()) {
@@ -170,6 +188,8 @@ export async function resolveFlowExtends(flow, loadFlowFile, visited = new Set()
170
188
  const merged = {
171
189
  name: flow.name,
172
190
  ...(Object.keys(environment).length ? { environment } : {}),
191
+ // `matrix` is not inherited: the merged flow expands by the child's own matrix, or not at all.
192
+ ...(flow.matrix ? { matrix: flow.matrix } : {}),
173
193
  ...(redactions.length ? { redactions } : {}),
174
194
  prerequisites: [...parent.prerequisites, ...flow.prerequisites],
175
195
  locators: { ...parent.locators, ...flow.locators },
@@ -0,0 +1,16 @@
1
+ export declare class FlowExecutionError extends Error {
2
+ readonly stepId: string;
3
+ readonly cause?: unknown | undefined;
4
+ /** Id of the matrix variant that halted; absent for a flow without a `matrix`. */
5
+ readonly variant?: string | undefined;
6
+ constructor(message: string, stepId: string, cause?: unknown | undefined,
7
+ /** Id of the matrix variant that halted; absent for a flow without a `matrix`. */
8
+ variant?: string | undefined);
9
+ }
10
+ /**
11
+ * Best-effort 1-line cause extracted from a Playwright actionability log (or similar driver
12
+ * error). Returns undefined when nothing matches — keeps the halt message short rather than
13
+ * guessing. Surfaced as a `[cause]` prefix on the halt message so the agent doesn't have to
14
+ * scan the multi-line actionability log.
15
+ */
16
+ export declare function inferHaltCause(rawError: string): string | undefined;
@@ -0,0 +1,76 @@
1
+ // Halt vocabulary of the runtime: the error a halted flow throws and the one-line cause inferred
2
+ // from a driver error. Leaf module: `flow-runtime.ts` and its step helpers all import it, it
3
+ // imports none of them.
4
+ export class FlowExecutionError extends Error {
5
+ stepId;
6
+ cause;
7
+ variant;
8
+ constructor(message, stepId, cause,
9
+ /** Id of the matrix variant that halted; absent for a flow without a `matrix`. */
10
+ variant) {
11
+ super(message);
12
+ this.stepId = stepId;
13
+ this.cause = cause;
14
+ this.variant = variant;
15
+ this.name = "FlowExecutionError";
16
+ }
17
+ }
18
+ /**
19
+ * Best-effort 1-line cause extracted from a Playwright actionability log (or similar driver
20
+ * error). Returns undefined when nothing matches — keeps the halt message short rather than
21
+ * guessing. Surfaced as a `[cause]` prefix on the halt message so the agent doesn't have to
22
+ * scan the multi-line actionability log.
23
+ */
24
+ export function inferHaltCause(rawError) {
25
+ const hints = [
26
+ [
27
+ /docsxai: cannot hide/i,
28
+ "the browser can't apply the hide rule (no constructable stylesheets), so the element would stay visible",
29
+ ],
30
+ [/element is disabled\b/i, "target is disabled"],
31
+ [/element is not enabled\b/i, "target is not enabled"],
32
+ [
33
+ /element is not visible\b/i,
34
+ "target is not visible (display:none / visibility:hidden / zero-sized)",
35
+ ],
36
+ [
37
+ /element is not attached\b/i,
38
+ "target was detached from the DOM (likely unmounted by an earlier action)",
39
+ ],
40
+ [/element is outside of the viewport\b/i, "target is outside the visible viewport"],
41
+ [/element is not stable\b/i, "target is animating / not yet stable"],
42
+ [
43
+ /settled: page did not settle/i,
44
+ "page never settled: fonts, images or layout kept changing (raise timeout_ms, hide the animated element, or wait on a concrete element)",
45
+ ],
46
+ [
47
+ /settled: driver has no waitForSettled/i,
48
+ "this browser driver can't run wait_for: settled (use network_idle plus a short wait)",
49
+ ],
50
+ [
51
+ /(hide|show): driver has no (hideElements|showElements)/i,
52
+ "this browser driver can't run hide or show steps (it has no hideElements / showElements)",
53
+ ],
54
+ [
55
+ /obstacles: driver has no nearbyBoxes/i,
56
+ "this browser driver can't scan for obstacles (it has no nearbyBoxes)",
57
+ ],
58
+ [/intercepts? pointer events\b/i, "target is covered by another element"],
59
+ [
60
+ /strict mode violation\b/i,
61
+ "selector matched multiple elements (strict-mode violation) — scope with :visible / :nth-match",
62
+ ],
63
+ [
64
+ /timeout .* exceeded.*waiting for/is,
65
+ "timeout waiting for selector — element didn't appear in time (consider raising timeout_ms or revisiting the locator)",
66
+ ],
67
+ ];
68
+ for (const [re, msg] of hints) {
69
+ if (re.test(rawError))
70
+ return msg;
71
+ }
72
+ const resolved = rawError.match(/locator resolved to (<[^>\n]*>)/);
73
+ if (resolved)
74
+ return `target resolved to ${resolved[1]}`;
75
+ return undefined;
76
+ }
@@ -0,0 +1,9 @@
1
+ import type { FlowFile } from "./doc-pack.js";
2
+ export interface HiddenAt {
3
+ /** Resolved selectors hidden when the step's action starts. */
4
+ before: ReadonlySet<string>;
5
+ /** Resolved selectors hidden once the step's action has run (what its screenshot sees). */
6
+ after: ReadonlySet<string>;
7
+ }
8
+ /** One entry per step, in step order. `resolve` turns a `target` (ref or inline) into a selector. */
9
+ export declare function hiddenAtEachStep(flow: FlowFile, resolve: (target: string) => string): HiddenAt[];
@@ -0,0 +1,20 @@
1
+ // Which selectors a flow's `hide` / `show` steps have hidden at each step. Pure and static: it
2
+ // reads the step list only, so `lint` and `diagnose` can say "this step reaches an element an
3
+ // earlier step hid" without a browser. A `show` with a target lifts only the selector a `hide`
4
+ // used (the same resolved string); a `show` with no target lifts everything.
5
+ /** One entry per step, in step order. `resolve` turns a `target` (ref or inline) into a selector. */
6
+ export function hiddenAtEachStep(flow, resolve) {
7
+ const hidden = new Set();
8
+ return flow.steps.map((step) => {
9
+ const before = new Set(hidden);
10
+ if (step.action === "hide" && step.target)
11
+ hidden.add(resolve(step.target));
12
+ if (step.action === "show") {
13
+ if (step.target)
14
+ hidden.delete(resolve(step.target));
15
+ else
16
+ hidden.clear();
17
+ }
18
+ return { before, after: new Set(hidden) };
19
+ });
20
+ }
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[];