@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
@@ -0,0 +1,136 @@
1
+ // Opt-in request guard for the browser a run drives. With `DOCSX_EGRESS_GUARD=1` (or an explicit
2
+ // `egressGuard` option on `launchPlaywrightSession`) every request the page makes is checked
3
+ // before it leaves: documents, subresources, fetches and each redirect hop (Chromium reports a
4
+ // redirect as a new request). A request whose host is, or resolves to, a link-local or
5
+ // cloud-metadata address is aborted; with `DOCSX_EGRESS_DENY_PRIVATE=1` loopback, RFC 1918, CGNAT
6
+ // and unique-local addresses are aborted too. A lookup that fails or returns nothing aborts the
7
+ // request.
8
+ //
9
+ // WebSocket connections go through the same check (`routeWebSocket`). What the run's output says is
10
+ // generic ("address not allowed"): the resolved address stays in the `detail` argument of
11
+ // `onBlock`, which nothing writes to stderr.
12
+ //
13
+ // Not covered: the name is resolved here and again by the browser, so a DNS answer that changes
14
+ // between the two (DNS rebinding) gets through. Put an egress firewall under a hosted
15
+ // deployment. This module has no Playwright import: the driver hands it a context.
16
+ import { lookup as dnsLookup } from "node:dns/promises";
17
+ import { hostProblem, parseIpv4, parseIpv6 } from "./address-class.js";
18
+ export const EGRESS_GUARD_ENV = "DOCSX_EGRESS_GUARD";
19
+ export const EGRESS_DENY_PRIVATE_ENV = "DOCSX_EGRESS_DENY_PRIVATE";
20
+ /** True for `1`, `true` and `yes` in any case. */
21
+ export function envFlagOn(value) {
22
+ return value !== undefined && /^(?:1|true|yes)$/i.test(value.trim());
23
+ }
24
+ /** True for `0`, `false` and `no` in any case, the spellings that say off on purpose. */
25
+ export function envFlagOff(value) {
26
+ return value !== undefined && /^(?:0|false|no)$/i.test(value.trim());
27
+ }
28
+ /** The guard `env` asks for, or undefined when `DOCSX_EGRESS_GUARD` is not on. */
29
+ export function egressGuardFromEnv(env) {
30
+ if (!envFlagOn(env[EGRESS_GUARD_ENV]))
31
+ return undefined;
32
+ return { denyPrivate: envFlagOn(env[EGRESS_DENY_PRIVATE_ENV]) };
33
+ }
34
+ /** An explicit option wins; otherwise the process environment decides. */
35
+ export function resolveEgressGuard(explicit, env = process.env) {
36
+ return explicit ?? egressGuardFromEnv(env);
37
+ }
38
+ /** Default longest wait for a hostname lookup. */
39
+ export const LOOKUP_TIMEOUT_MS = 5000;
40
+ /** `work`, or a rejection once `ms` have passed. */
41
+ function withDeadline(work, ms) {
42
+ let timer;
43
+ const deadline = new Promise((_, reject) => {
44
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
45
+ });
46
+ return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
47
+ }
48
+ const defaultLookup = async (hostname) => (await dnsLookup(hostname, { all: true, verbatim: true })).map((a) => a.address);
49
+ /** Schemes that never leave the browser. */
50
+ const INERT_SCHEMES = new Set(["data:", "blob:", "about:"]);
51
+ const NETWORK_SCHEMES = new Set(["http:", "https:", "ws:", "wss:"]);
52
+ /** Why a request to `rawUrl` must not go out, or null when it may. */
53
+ export async function requestProblem(rawUrl, opts = {}) {
54
+ let url;
55
+ try {
56
+ url = new URL(rawUrl);
57
+ }
58
+ catch {
59
+ return "the URL does not parse";
60
+ }
61
+ if (INERT_SCHEMES.has(url.protocol))
62
+ return null;
63
+ if (!NETWORK_SCHEMES.has(url.protocol))
64
+ return `the ${url.protocol} scheme is not allowed`;
65
+ const denyPrivate = opts.denyPrivate === true;
66
+ const host = url.hostname.replace(/\.+$/, "");
67
+ const direct = hostProblem(host, denyPrivate);
68
+ if (direct)
69
+ return `${host} is a ${direct} address`;
70
+ if (parseIpv4(host) || parseIpv6(host))
71
+ return null;
72
+ let addresses;
73
+ try {
74
+ const pending = Promise.resolve().then(() => (opts.lookup ?? defaultLookup)(host));
75
+ addresses = await withDeadline(pending, opts.lookupTimeoutMs ?? LOOKUP_TIMEOUT_MS);
76
+ }
77
+ catch (e) {
78
+ return `${host} did not resolve (${e.message}), refused`;
79
+ }
80
+ if (addresses.length === 0)
81
+ return `${host} resolved to no address, refused`;
82
+ for (const address of addresses) {
83
+ const problem = hostProblem(address, denyPrivate);
84
+ if (problem)
85
+ return `${host} resolves to ${address}, a ${problem} address`;
86
+ }
87
+ return null;
88
+ }
89
+ /** Context options a guarded context needs: a service worker's own fetches are not routed. */
90
+ export function egressContextOptions(guard) {
91
+ return guard ? { serviceWorkers: "block" } : {};
92
+ }
93
+ /** What the run's output says about a refused request. */
94
+ export const BLOCKED_REASON = "address not allowed";
95
+ /** `rawUrl` without userinfo, query and fragment, safe to print. */
96
+ export function printableUrl(rawUrl) {
97
+ try {
98
+ const url = new URL(rawUrl);
99
+ url.username = "";
100
+ url.password = "";
101
+ url.search = "";
102
+ url.hash = "";
103
+ return url.href;
104
+ }
105
+ catch {
106
+ return "<unparseable URL>";
107
+ }
108
+ }
109
+ /** Route every request and WebSocket of `context` through {@link requestProblem}; a no-op without a guard. */
110
+ export async function installEgressGuard(context, guard) {
111
+ if (!guard)
112
+ return;
113
+ /** The detail of why `rawUrl` is refused, or null; reports a refusal. A failed check refuses. */
114
+ const refusal = async (rawUrl) => {
115
+ const detail = await requestProblem(rawUrl, guard).catch((e) => `the check failed (${e.message}), refused`);
116
+ if (detail === null)
117
+ return null;
118
+ const shown = printableUrl(rawUrl);
119
+ if (guard.onBlock)
120
+ guard.onBlock(shown, BLOCKED_REASON, detail);
121
+ else
122
+ process.stderr.write(`egress-guard: blocked ${shown}: ${BLOCKED_REASON}\n`);
123
+ return detail;
124
+ };
125
+ await context.route(/.*/, async (route) => {
126
+ if ((await refusal(route.request().url())) === null)
127
+ return route.continue();
128
+ return route.abort("blockedbyclient");
129
+ });
130
+ await context.routeWebSocket(/.*/, async (ws) => {
131
+ if ((await refusal(ws.url())) === null)
132
+ ws.connectToServer();
133
+ else
134
+ await ws.close();
135
+ });
136
+ }
@@ -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
- readonly cause?: unknown;
4
- constructor(message: string, cause?: unknown);
4
+ readonly cause?: unknown | undefined;
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
+ }