@docsxai/engine 0.3.0-rc.3 → 0.3.0-rc.5

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 (181) hide show
  1. package/README.md +44 -34
  2. package/dist/atomic-write.d.ts +19 -0
  3. package/dist/atomic-write.js +127 -0
  4. package/dist/auth/api-login.d.ts +9 -51
  5. package/dist/auth/api-login.js +3 -3
  6. package/dist/auth/browser-session.js +1 -1
  7. package/dist/auth/cookie-jar.d.ts +4 -4
  8. package/dist/auth/cookie-jar.js +4 -4
  9. package/dist/auth/email-otp.d.ts +11 -147
  10. package/dist/auth/email-otp.js +4 -4
  11. package/dist/auth/http-basic.js +1 -1
  12. package/dist/auth/index.js +3 -3
  13. package/dist/auth/jwt-injection.d.ts +7 -131
  14. package/dist/auth/jwt-injection.js +5 -5
  15. package/dist/auth/manual-capture.d.ts +3 -3
  16. package/dist/auth/manual-capture.js +2 -2
  17. package/dist/auth/mtls.d.ts +1 -6
  18. package/dist/auth/mtls.js +1 -1
  19. package/dist/auth/pat-header.d.ts +1 -9
  20. package/dist/auth/pat-header.js +1 -1
  21. package/dist/auth/storage-state-cache.d.ts +16 -6
  22. package/dist/auth/storage-state-cache.js +65 -15
  23. package/dist/auth/test-backdoor.d.ts +2 -13
  24. package/dist/auth/test-backdoor.js +3 -3
  25. package/dist/auth/totp.d.ts +1 -1
  26. package/dist/auth/totp.js +4 -4
  27. package/dist/auth/types.d.ts +3 -3
  28. package/dist/auth/types.js +4 -4
  29. package/dist/auth/ui-form.d.ts +24 -153
  30. package/dist/auth/ui-form.js +3 -3
  31. package/dist/auth/webauthn.d.ts +7 -67
  32. package/dist/auth/webauthn.js +3 -3
  33. package/dist/auth.js +1 -1
  34. package/dist/backend-client-contracts.d.ts +1 -1
  35. package/dist/backend-client-contracts.js +2 -2
  36. package/dist/backend-client-oauth-login.js +1 -1
  37. package/dist/backend-client-state-cache.d.ts +2 -2
  38. package/dist/backend-client-state-cache.js +8 -8
  39. package/dist/backend-client-token.js +4 -4
  40. package/dist/backend-client-transport.d.ts +2 -2
  41. package/dist/backend-client-transport.js +3 -3
  42. package/dist/backend-client.js +6 -6
  43. package/dist/browser-build.d.ts +6 -0
  44. package/dist/browser-build.js +12 -0
  45. package/dist/browser-launch-error.d.ts +18 -0
  46. package/dist/browser-launch-error.js +63 -0
  47. package/dist/browser-wait.d.ts +7 -0
  48. package/dist/browser-wait.js +12 -0
  49. package/dist/calibrate.d.ts +6 -2
  50. package/dist/calibrate.js +20 -13
  51. package/dist/cli-backend-errors.d.ts +5 -0
  52. package/dist/cli-backend-errors.js +24 -3
  53. package/dist/cli-commands-auth.d.ts +1 -0
  54. package/dist/cli-commands-auth.js +114 -0
  55. package/dist/cli-commands-authoring.d.ts +0 -1
  56. package/dist/cli-commands-authoring.js +124 -101
  57. package/dist/cli-commands-backend.d.ts +1 -1
  58. package/dist/cli-commands-backend.js +76 -21
  59. package/dist/cli-commands-docpack.d.ts +3 -1
  60. package/dist/cli-commands-docpack.js +145 -39
  61. package/dist/cli-commands-init.d.ts +1 -0
  62. package/dist/cli-commands-init.js +100 -0
  63. package/dist/cli-commands-pack.d.ts +1 -1
  64. package/dist/cli-commands-pack.js +6 -4
  65. package/dist/cli-commands-session.d.ts +1 -3
  66. package/dist/cli-commands-session.js +109 -180
  67. package/dist/cli-commands-site.d.ts +2 -0
  68. package/dist/cli-commands-site.js +77 -0
  69. package/dist/cli-commands-style.d.ts +1 -0
  70. package/dist/cli-commands-style.js +85 -0
  71. package/dist/cli-flags.d.ts +18 -0
  72. package/dist/cli-flags.js +77 -0
  73. package/dist/cli-help.d.ts +30 -0
  74. package/dist/cli-help.js +174 -0
  75. package/dist/cli-messages.d.ts +30 -0
  76. package/dist/cli-messages.js +97 -0
  77. package/dist/cli-node-guard.d.ts +1 -0
  78. package/dist/cli-node-guard.js +8 -0
  79. package/dist/cli-retired.js +6 -0
  80. package/dist/cli-run-stale.d.ts +2 -0
  81. package/dist/cli-run-stale.js +13 -0
  82. package/dist/cli-run-summary.js +7 -3
  83. package/dist/cli-shared.d.ts +30 -1
  84. package/dist/cli-shared.js +112 -12
  85. package/dist/cli-unexpected.d.ts +12 -2
  86. package/dist/cli-unexpected.js +50 -4
  87. package/dist/cli-usage.d.ts +1 -1
  88. package/dist/cli-usage.js +115 -66
  89. package/dist/cli-value-flags.d.ts +8 -0
  90. package/dist/cli-value-flags.js +34 -0
  91. package/dist/cli-version.d.ts +6 -0
  92. package/dist/cli-version.js +25 -0
  93. package/dist/cli.d.ts +1 -0
  94. package/dist/cli.js +42 -19
  95. package/dist/deprecation.d.ts +2 -0
  96. package/dist/deprecation.js +2 -0
  97. package/dist/device-scale-factor.d.ts +14 -0
  98. package/dist/device-scale-factor.js +38 -0
  99. package/dist/diagnose.js +14 -13
  100. package/dist/diff-compute.js +22 -8
  101. package/dist/diff-report.js +3 -3
  102. package/dist/diff-types.js +1 -1
  103. package/dist/diff.js +3 -3
  104. package/dist/doc-pack-io.js +62 -47
  105. package/dist/doc-pack.d.ts +567 -3487
  106. package/dist/doc-pack.js +47 -33
  107. package/dist/doctor-checks-config.d.ts +12 -0
  108. package/dist/doctor-checks-config.js +229 -0
  109. package/dist/doctor-checks-plugins.js +2 -2
  110. package/dist/doctor-checks-site.d.ts +3 -0
  111. package/dist/doctor-checks-site.js +21 -0
  112. package/dist/doctor-checks.d.ts +13 -2
  113. package/dist/doctor-checks.js +94 -79
  114. package/dist/doctor-next.d.ts +5 -0
  115. package/dist/doctor-next.js +52 -0
  116. package/dist/doctor.d.ts +36 -2
  117. package/dist/doctor.js +88 -29
  118. package/dist/environment-spec.d.ts +36 -44
  119. package/dist/environment-spec.js +31 -3
  120. package/dist/export/adf.d.ts +1 -1
  121. package/dist/export/adf.js +16 -27
  122. package/dist/export/playwright-test.d.ts +1 -1
  123. package/dist/export/playwright-test.js +13 -15
  124. package/dist/flow-file.d.ts +1 -1
  125. package/dist/flow-file.js +22 -4
  126. package/dist/flow-halt.d.ts +1 -1
  127. package/dist/flow-halt.js +15 -3
  128. package/dist/flow-lint.d.ts +3 -1
  129. package/dist/flow-lint.js +39 -26
  130. package/dist/flow-matrix-lint.js +2 -2
  131. package/dist/flow-runtime.d.ts +17 -6
  132. package/dist/flow-runtime.js +48 -17
  133. package/dist/flow-success.js +4 -4
  134. package/dist/flow-tree.js +2 -2
  135. package/dist/index.d.ts +2 -0
  136. package/dist/index.js +2 -0
  137. package/dist/main-module.d.ts +1 -0
  138. package/dist/main-module.js +17 -0
  139. package/dist/matrix-spec.d.ts +33 -106
  140. package/dist/matrix-spec.js +12 -3
  141. package/dist/node-floor.d.ts +4 -0
  142. package/dist/node-floor.js +14 -0
  143. package/dist/obstacles.js +1 -1
  144. package/dist/open-in-browser.d.ts +22 -0
  145. package/dist/open-in-browser.js +37 -0
  146. package/dist/playwright-driver.d.ts +8 -12
  147. package/dist/playwright-driver.js +75 -70
  148. package/dist/playwright-instrumented-browser.d.ts +10 -7
  149. package/dist/playwright-instrumented-browser.js +35 -12
  150. package/dist/plugins/load.d.ts +1 -1
  151. package/dist/plugins/load.js +4 -4
  152. package/dist/plugins/lock.js +11 -8
  153. package/dist/plugins/manifest.d.ts +16 -35
  154. package/dist/plugins/manifest.js +5 -5
  155. package/dist/plugins/plan.d.ts +3 -3
  156. package/dist/plugins/plan.js +14 -14
  157. package/dist/plugins/registry.d.ts +1 -1
  158. package/dist/plugins/registry.js +1 -1
  159. package/dist/plugins/runtime.js +3 -3
  160. package/dist/plugins/types.d.ts +1 -1
  161. package/dist/plugins-cli.js +36 -28
  162. package/dist/posix-path.d.ts +2 -0
  163. package/dist/posix-path.js +7 -0
  164. package/dist/redact.js +2 -2
  165. package/dist/run-flows.d.ts +7 -0
  166. package/dist/run-flows.js +75 -27
  167. package/dist/style.d.ts +2 -2
  168. package/dist/style.js +13 -11
  169. package/dist/verify-determinism.js +2 -1
  170. package/dist/verify-next-step.d.ts +2 -0
  171. package/dist/verify-next-step.js +24 -0
  172. package/dist/verify-report.js +3 -2
  173. package/dist/viewer-bin.d.ts +9 -3
  174. package/dist/viewer-bin.js +35 -12
  175. package/dist/workspace-templates.d.ts +15 -0
  176. package/dist/workspace-templates.js +88 -0
  177. package/dist/workspace.d.ts +78 -5
  178. package/dist/workspace.js +47 -28
  179. package/dist/zip.d.ts +1 -1
  180. package/dist/zip.js +23 -6
  181. package/package.json +6 -6
@@ -1,42 +1,60 @@
1
- // Calibration-aid commands — the static / inspection tools an engineer leans on while hand-authoring
1
+ // Calibration-aid commands, the static / inspection tools an engineer leans on while hand-authoring
2
2
  // or fixing a flow-file. None of them mutate the doc pack; they read, check, and report:
3
- // inspect — open the app (cached session loaded) and dump [data-testid]s for pinning locators
4
- // lint — pure-static flow-file checks (R001…R004 + plugin-contributed rules)
5
- // flow-tree — the extends graph, orphans, and resolution issues
6
- // diagnose — halt context + recommendations for one step (optional live --cdp probe)
7
- // style — init/validate docs/style.yaml; --check scans prose for jargon leaks
3
+ // inspect: open the app (cached session loaded) and dump [data-testid]s for pinning locators
4
+ // lint: pure-static flow-file checks (R001…R004 + plugin-contributed rules)
5
+ // flow-tree: the extends graph, orphans, and resolution issues
6
+ // diagnose: halt context + recommendations for one step (optional live --cdp probe)
8
7
  import { promises as fs } from "node:fs";
9
8
  import * as path from "node:path";
10
9
  import { LocalStorageStateCache, parseAuthStrategyFile } from "./auth.js";
10
+ import { waitForBrowserClose } from "./browser-wait.js";
11
+ import { describeBrowserLaunch, describePageLoad } from "./browser-launch-error.js";
11
12
  import { expandFlowVariants, FlowFileError, parseFlowFile, resolveFlowExtends, } from "./flow-file.js";
12
13
  import { variantDocDir } from "./flow-matrix.js";
13
14
  import { buildDiagnoseReport, formatReportText, pickDiagnoseVariant, probeLive, } from "./diagnose.js";
14
15
  import { formatIssuesText, lintFlow } from "./flow-lint.js";
15
16
  import { buildFlowTree, formatTreeText } from "./flow-tree.js";
16
- import { formatJargonHitsText, initStyleIfAbsent, loadStyle, scanWorkspaceForJargon, StyleError, writeStyle, } from "./style.js";
17
17
  import { readPluginsLock, readWorkspacePluginsConfig } from "./plugins/lock.js";
18
18
  import { resolvePlugins } from "./plugins/runtime.js";
19
19
  import { launchPlaywrightSession } from "./playwright-driver.js";
20
20
  import { loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
21
- import { listFlowFiles, parseFlags } from "./cli-shared.js";
22
- import { shellQuote, usageError, withNext } from "./cli-messages.js";
21
+ import { bareValueFlagExit, claimFlowName, listFlowFiles } from "./cli-shared.js";
22
+ import { parseCommandFlags } from "./cli-flags.js";
23
+ import { describeFsProblem, shellQuote, usageError, withNext } from "./cli-messages.js";
23
24
  export async function cmdInspect(args) {
24
- const { positionals, flags } = parseFlags(args);
25
+ const parsed = parseCommandFlags("inspect", args);
26
+ if (typeof parsed === "number")
27
+ return parsed;
28
+ const { positionals, flags } = parsed;
25
29
  const workspaceDir = positionals[0];
26
30
  if (!workspaceDir)
27
31
  return usageError("inspect", "missing <workspace-dir>");
32
+ const bare = bareValueFlagExit("inspect", flags, [
33
+ "url",
34
+ "selector",
35
+ "cdp",
36
+ "wait",
37
+ "wait-for",
38
+ "role",
39
+ ]);
40
+ if (bare !== undefined)
41
+ return bare;
42
+ const waitFlag = flags.get("wait");
43
+ if (typeof waitFlag === "string" && !/^\d+$/.test(waitFlag)) {
44
+ return usageError("inspect", `--wait must be a whole number of milliseconds (got "${waitFlag}")`);
45
+ }
28
46
  const wsCfg = await loadWorkspaceConfig(workspaceDir);
29
47
  const cdp = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
30
48
  const explicitUrl = typeof flags.get("url") === "string" ? flags.get("url") : undefined;
31
49
  const url = explicitUrl ?? wsCfg?.app_url;
32
50
  if (!cdp && !url) {
33
- return usageError("inspect", "no URL — pass --url <url>, set app_url in .docsxai.json, or use --cdp <endpoint>");
51
+ return usageError("inspect", "no URL: pass --url <url>, set app_url in .docsxai.json, or use --cdp <endpoint>");
34
52
  }
35
53
  const selector = typeof flags.get("selector") === "string" ? flags.get("selector") : undefined;
36
54
  const headed = flags.get("headed") === true;
37
55
  const ignoreHTTPSErrors = flags.get("ignore-https-errors") === true || !!wsCfg?.ignore_https_errors;
38
56
  const waitForSel = typeof flags.get("wait-for") === "string" ? flags.get("wait-for") : undefined;
39
- const waitMs = typeof flags.get("wait") === "string" ? Math.max(0, Number(flags.get("wait")) || 0) : 800;
57
+ const waitMs = typeof waitFlag === "string" ? Number(waitFlag) : 800;
40
58
  let storageState;
41
59
  if (!cdp) {
42
60
  let role = typeof flags.get("role") === "string" ? flags.get("role") : undefined;
@@ -48,11 +66,19 @@ export async function cmdInspect(args) {
48
66
  role = "editor";
49
67
  }
50
68
  }
51
- storageState =
52
- (await new LocalStorageStateCache(resolveWorkspacePath(workspaceDir, ".auth")).load(role)) ??
53
- undefined;
69
+ try {
70
+ storageState =
71
+ (await new LocalStorageStateCache(resolveWorkspacePath(workspaceDir, ".auth")).load(role)) ?? undefined;
72
+ }
73
+ catch (e) {
74
+ const problem = describeFsProblem(e);
75
+ if (!problem)
76
+ throw e;
77
+ process.stderr.write(`inspect: ${withNext(problem.reason, problem.next)}\n`);
78
+ return 1;
79
+ }
54
80
  if (!storageState) {
55
- process.stderr.write(`inspect: no valid cached session for role "${role}" — inspecting unauthenticated (\`docsxai capture-auth\` first if the app needs login)\n`);
81
+ process.stderr.write(`inspect: no valid cached session for role "${role}", so it inspects unauthenticated (run \`docsxai capture-auth\` first if the app needs login)\n`);
56
82
  }
57
83
  }
58
84
  let session;
@@ -70,21 +96,22 @@ export async function cmdInspect(args) {
70
96
  });
71
97
  }
72
98
  catch (e) {
73
- const msg = e.message;
74
- if (/Executable doesn't exist|playwright install/i.test(msg)) {
75
- process.stderr.write("inspect: no Chromium binary — `npx playwright-core install chromium` (source checkout: `pnpm -C packages/engine exec playwright-core install chromium`)\n");
76
- return 1;
77
- }
78
- process.stderr.write(`inspect: failed to launch browser: ${msg}\n`);
99
+ const problem = describeBrowserLaunch(e.message, cdp);
100
+ process.stderr.write(`inspect: ${problem.next ? withNext(problem.reason, problem.next) : problem.reason}\n`);
79
101
  return 1;
80
102
  }
81
103
  try {
82
104
  // In CDP-attach mode without an explicit --url, inspect whatever the attached browser already has open.
83
- if (url && (!cdp || explicitUrl))
105
+ if (url && (!cdp || explicitUrl)) {
106
+ let loadError;
84
107
  await session.page.goto(url, { waitUntil: "domcontentloaded" }).catch((e) => {
85
- const why = e.message.split("\n")[0];
86
- process.stderr.write(`inspect: warning — could not load ${url}: ${why}; is the app running?\n`);
108
+ loadError = e;
87
109
  });
110
+ if (loadError) {
111
+ process.stderr.write(`inspect: ${withNext(describePageLoad(loadError.message, url), `start the app, then docsxai inspect ${shellQuote(workspaceDir)}`)}\n`);
112
+ return 1;
113
+ }
114
+ }
88
115
  if (waitForSel)
89
116
  await session.page.waitForSelector(waitForSel, { timeout: 30_000 }).catch(() => undefined);
90
117
  else if (waitMs > 0)
@@ -112,15 +139,15 @@ export async function cmdInspect(args) {
112
139
  : e.offsetParent != null,
113
140
  })))
114
141
  .catch(() => []);
115
- process.stdout.write(` ${items.length} [data-testid] element(s) (✓ = visible) — pin these as locators:\n`);
142
+ process.stdout.write(` ${items.length} [data-testid] element(s) (✓ = visible), pin these as locators:\n`);
116
143
  for (const it of items) {
117
144
  process.stdout.write(` ${it.visible ? "✓" : " "} [data-testid="${it.testid}"] <${it.tag}> ${it.text ? `"${it.text}"` : ""}\n`);
118
145
  }
119
146
  process.stdout.write(` (--selector '<css>' dumps matching elements' HTML; --url <url> for a sub-page; --wait <ms> / --wait-for '<css>' to settle a slow SPA before snapshot; --cdp <endpoint> to attach to a running Chrome instead of launching; --headed to open it)\n`);
120
147
  }
121
148
  if (headed && !cdp) {
122
- process.stdout.write("inspect: browser is open — close it to exit.\n");
123
- await new Promise((resolve) => session.browser.on("disconnected", () => resolve()));
149
+ process.stdout.write("inspect: browser is open, close it to exit.\n");
150
+ await waitForBrowserClose(session.browser);
124
151
  }
125
152
  return 0;
126
153
  }
@@ -129,15 +156,22 @@ export async function cmdInspect(args) {
129
156
  return 1;
130
157
  }
131
158
  finally {
132
- if (!headed)
159
+ // A headed launch stays open for the operator; an attach has nothing to keep open.
160
+ if (!headed || cdp)
133
161
  await session.close();
134
162
  }
135
163
  }
136
164
  export async function cmdLint(args) {
137
- const { positionals, flags } = parseFlags(args);
165
+ const parsed = parseCommandFlags("lint", args);
166
+ if (typeof parsed === "number")
167
+ return parsed;
168
+ const { positionals, flags } = parsed;
138
169
  if (!positionals[0])
139
170
  return usageError("lint", "missing <workspace-dir>");
140
171
  const projectDir = positionals[0];
172
+ const bareLint = bareValueFlagExit("lint", flags, ["flow", "format"]);
173
+ if (bareLint !== undefined)
174
+ return bareLint;
141
175
  const flowFilter = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
142
176
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
143
177
  if (format !== "text" && format !== "json") {
@@ -152,15 +186,21 @@ export async function cmdLint(args) {
152
186
  return 2;
153
187
  }
154
188
  const flowsByName = new Map();
189
+ const fileNames = new Map();
190
+ const owners = new Map();
155
191
  for (const p of flowPaths) {
156
192
  try {
157
193
  const text = await fs.readFile(p, "utf8");
158
- const flow = parseFlowFile(text, path.basename(p));
194
+ const flow = parseFlowFile(text, p);
195
+ const duplicate = claimFlowName(owners, flow.name, p);
196
+ if (duplicate)
197
+ throw new FlowFileError(duplicate);
159
198
  flowsByName.set(flow.name, flow);
199
+ fileNames.set(flow.name, path.basename(p));
160
200
  }
161
201
  catch (e) {
162
- const msg = e instanceof FlowFileError ? e.message : e.message;
163
- process.stderr.write(`lint: ${withNext(`parse error in ${p}: ${msg}`, `fix the flow-file, then docsxai lint ${shellQuote(projectDir)}`)}\n`);
202
+ const msg = e instanceof FlowFileError ? e.message : `${p}: ${e.message}`;
203
+ process.stderr.write(`lint: ${withNext(msg, `fix the flow-file, then docsxai lint ${shellQuote(projectDir)}`)}\n`);
164
204
  return 1;
165
205
  }
166
206
  }
@@ -181,7 +221,7 @@ export async function cmdLint(args) {
181
221
  };
182
222
  // Lint-rule plugins: resolve the workspace's plugin registry and feed registered
183
223
  // rules through lintFlow's extraRules. A plugin-resolution failure degrades to
184
- // core rules with a warning — lint must stay usable while a plugin is broken.
224
+ // core rules with a warning, lint must stay usable while a plugin is broken.
185
225
  let extraRules = [];
186
226
  try {
187
227
  const cfg = await readWorkspacePluginsConfig(projectDir);
@@ -197,11 +237,15 @@ export async function cmdLint(args) {
197
237
  }
198
238
  }
199
239
  catch (e) {
200
- process.stderr.write(`lint: plugin rules skipped — ${e.message}\n`);
240
+ process.stderr.write(`lint: plugin rules skipped: ${e.message}\n`);
201
241
  }
202
242
  const issues = [];
203
243
  for (const flow of targets) {
204
- const result = await lintFlow(flow, { loadFlow, extraRules });
244
+ const result = await lintFlow(flow, {
245
+ loadFlow,
246
+ extraRules,
247
+ fileName: fileNames.get(flow.name),
248
+ });
205
249
  issues.push(...result);
206
250
  }
207
251
  if (format === "json") {
@@ -213,10 +257,16 @@ export async function cmdLint(args) {
213
257
  return issues.some((i) => i.severity === "error" || i.severity === "warning") ? 1 : 0;
214
258
  }
215
259
  export async function cmdFlowTree(args) {
216
- const { positionals, flags } = parseFlags(args);
260
+ const parsed = parseCommandFlags("flow-tree", args);
261
+ if (typeof parsed === "number")
262
+ return parsed;
263
+ const { positionals, flags } = parsed;
217
264
  if (!positionals[0])
218
265
  return usageError("flow-tree", "missing <workspace-dir>");
219
266
  const projectDir = positionals[0];
267
+ const bareTree = bareValueFlagExit("flow-tree", flags, ["format"]);
268
+ if (bareTree !== undefined)
269
+ return bareTree;
220
270
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
221
271
  if (format !== "text" && format !== "json") {
222
272
  return usageError("flow-tree", '--format must be "text" or "json"');
@@ -230,15 +280,19 @@ export async function cmdFlowTree(args) {
230
280
  return 2;
231
281
  }
232
282
  const flowsByName = new Map();
283
+ const owners = new Map();
233
284
  for (const p of flowPaths) {
234
285
  try {
235
286
  const text = await fs.readFile(p, "utf8");
236
- const flow = parseFlowFile(text, path.basename(p));
287
+ const flow = parseFlowFile(text, p);
288
+ const duplicate = claimFlowName(owners, flow.name, p);
289
+ if (duplicate)
290
+ throw new FlowFileError(duplicate);
237
291
  flowsByName.set(flow.name, flow);
238
292
  }
239
293
  catch (e) {
240
- const msg = e instanceof FlowFileError ? e.message : e.message;
241
- process.stderr.write(`flow-tree: ${withNext(`parse error in ${p}: ${msg}`, `fix the flow-file, then docsxai flow-tree ${shellQuote(projectDir)}`)}\n`);
294
+ const msg = e instanceof FlowFileError ? e.message : `${p}: ${e.message}`;
295
+ process.stderr.write(`flow-tree: ${withNext(msg, `fix the flow-file, then docsxai flow-tree ${shellQuote(projectDir)}`)}\n`);
242
296
  return 1;
243
297
  }
244
298
  }
@@ -252,10 +306,22 @@ export async function cmdFlowTree(args) {
252
306
  return tree.issues.length > 0 || tree.orphans.length > 0 ? 1 : 0;
253
307
  }
254
308
  export async function cmdDiagnose(args) {
255
- const { positionals, flags } = parseFlags(args);
309
+ const parsed = parseCommandFlags("diagnose", args);
310
+ if (typeof parsed === "number")
311
+ return parsed;
312
+ const { positionals, flags } = parsed;
256
313
  if (!positionals[0])
257
314
  return usageError("diagnose", "missing <workspace-dir>");
258
315
  const projectDir = positionals[0];
316
+ const bareDiagnose = bareValueFlagExit("diagnose", flags, [
317
+ "flow",
318
+ "step",
319
+ "cdp",
320
+ "variant",
321
+ "format",
322
+ ]);
323
+ if (bareDiagnose !== undefined)
324
+ return bareDiagnose;
259
325
  const flowName = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
260
326
  const stepId = typeof flags.get("step") === "string" ? flags.get("step") : undefined;
261
327
  const cdpEndpoint = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
@@ -269,27 +335,29 @@ export async function cmdDiagnose(args) {
269
335
  return usageError("diagnose", '--format must be "text" or "json"');
270
336
  }
271
337
  // Load the flow (resolving `extends` so step lookup works against the merged step list).
272
- const loadFlowFile = async (name) => {
338
+ const readFlowFile = async (name) => {
273
339
  const fp = resolveWorkspacePath(projectDir, "flows", `${name}.flow.yaml`);
274
- let text;
275
- try {
276
- text = await fs.readFile(fp, "utf8");
277
- }
278
- catch {
279
- throw new FlowFileError(withNext(`no flow named "${name}" at ${fp}`, `docsxai flow-tree ${shellQuote(projectDir)} (lists the flows)`));
280
- }
281
- return parseFlowFile(text, fp);
340
+ return parseFlowFile(await fs.readFile(fp, "utf8"), fp);
282
341
  };
283
342
  let flow;
284
343
  let variants;
285
344
  try {
286
- const parsed = await loadFlowFile(flowName);
287
- flow = parsed.extends ? await resolveFlowExtends(parsed, loadFlowFile) : parsed;
345
+ let parsed;
346
+ try {
347
+ parsed = await readFlowFile(flowName);
348
+ }
349
+ catch (e) {
350
+ if (e.code !== "ENOENT")
351
+ throw e;
352
+ const fp = resolveWorkspacePath(projectDir, "flows", `${flowName}.flow.yaml`);
353
+ throw new FlowFileError(withNext(`no flow named "${flowName}" at ${fp}`, `docsxai flow-tree ${shellQuote(projectDir)} (lists the flows)`));
354
+ }
355
+ flow = parsed.extends ? await resolveFlowExtends(parsed, readFlowFile) : parsed;
288
356
  variants = expandFlowVariants(flow);
289
357
  }
290
358
  catch (e) {
291
359
  const msg = e instanceof FlowFileError ? e.message : e.message;
292
- process.stderr.write(`diagnose: ${msg}\n`);
360
+ process.stderr.write(`diagnose: ${e instanceof FlowFileError && !msg.includes("\n next: ") ? withNext(msg, `docsxai lint ${shellQuote(projectDir)}`) : msg}\n`);
293
361
  return 1;
294
362
  }
295
363
  // A flow with a `matrix` is diagnosed one variant at a time: its steps and halt shot are the variant's.
@@ -308,7 +376,9 @@ export async function cmdDiagnose(args) {
308
376
  flow = picked.variant.flow;
309
377
  const step = flow.steps.find((s) => s.id === stepId);
310
378
  if (!step) {
311
- process.stderr.write(`diagnose: no step "${stepId}" in flow "${flowName}"${variantId ? ` variant "${variantId}"` : ""} (${variantId ? "variant" : "merged"} step list: ${flow.steps.map((s) => s.id).join(", ")})\n`);
379
+ const message = `no step "${stepId}" in flow "${flowName}"${variantId ? ` variant "${variantId}"` : ""} (steps: ${flow.steps.map((s) => s.id).join(", ")})`;
380
+ const next = `docsxai diagnose ${shellQuote(projectDir)} --flow ${shellQuote(flowName)} --step <step-id>${variantId ? ` --variant ${shellQuote(variantId)}` : ""}`;
381
+ process.stderr.write(`diagnose: ${withNext(message, next)}\n`);
312
382
  return 1;
313
383
  }
314
384
  const resolvedSelector = step.target
@@ -360,50 +430,3 @@ export async function cmdDiagnose(args) {
360
430
  }
361
431
  return 0;
362
432
  }
363
- export async function cmdStyle(args) {
364
- const { positionals, flags } = parseFlags(args);
365
- if (!positionals[0])
366
- return usageError("style", "missing <workspace-dir>");
367
- const projectDir = positionals[0];
368
- const check = flags.get("check") === true;
369
- const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
370
- if (format !== "text" && format !== "json") {
371
- return usageError("style", '--format must be "text" or "json"');
372
- }
373
- // init-if-absent (idempotent); then load + validate; then rederive JSON; then optional jargon check.
374
- const { created } = await initStyleIfAbsent(projectDir);
375
- let style;
376
- try {
377
- style = await loadStyle(projectDir);
378
- }
379
- catch (e) {
380
- if (e instanceof StyleError) {
381
- process.stderr.write(`style: ${withNext(e.message, `fix docs/style.yaml, then docsxai style ${shellQuote(projectDir)}`)}\n`);
382
- return 1;
383
- }
384
- throw e;
385
- }
386
- if (!style) {
387
- // Shouldn't happen after initStyleIfAbsent, but defensive.
388
- process.stderr.write(`style: failed to initialise style.yaml in ${projectDir}\n`);
389
- return 1;
390
- }
391
- // Always rewrite to ensure derived JSON stays in sync with YAML (idempotent).
392
- const paths = await writeStyle(projectDir, style);
393
- let hits = [];
394
- if (check) {
395
- hits = await scanWorkspaceForJargon(projectDir, style);
396
- }
397
- if (format === "json") {
398
- process.stdout.write(JSON.stringify({ style, paths, created, jargonLeaks: check ? hits : undefined }, null, 2) +
399
- "\n");
400
- }
401
- else {
402
- process.stdout.write(`style: ${created ? "created" : "validated"} ${path.relative(projectDir, paths.yamlPath)}; rederived ${path.relative(projectDir, paths.jsonPath)}\n`);
403
- if (check) {
404
- process.stdout.write("\n");
405
- process.stdout.write(formatJargonHitsText(hits));
406
- }
407
- }
408
- return check && hits.length > 0 ? 1 : 0;
409
- }
@@ -1,5 +1,5 @@
1
1
  export declare function cmdLogin(args: string[]): Promise<number>;
2
2
  export declare function cmdPush(args: string[]): Promise<number>;
3
3
  export declare function cmdPull(args: string[]): Promise<number>;
4
- /** `docsxai plugins …` — forwards to the plugin-runtime CLI verbatim. */
4
+ /** `docsxai plugins …`: forwards to the plugin-runtime CLI verbatim. */
5
5
  export declare function cmdPlugins(args: string[]): Promise<number>;
@@ -1,24 +1,31 @@
1
- // Backend / sync commands — everything that talks to `@docsxai/backend` over HTTP, plus the plugins
1
+ // Backend / sync commands, everything that talks to `@docsxai/backend` over HTTP, plus the plugins
2
2
  // subcommand delegation:
3
- // login — validate a bearer token (or run the OAuth 2.1 + PKCE flow with --oauth)
4
- // push — serialise the doc pack and POST it as a new revision (binds the workspace on first push)
5
- // pull — fetch a revision's artifacts back into the workspace files
6
- // plugins — forwards to plugins-cli (list | info | sync over the plugin runtime; no plugin code runs)
7
- import { promises as fs } from "node:fs";
3
+ // login: validate a bearer token (or run the OAuth 2.1 + PKCE flow with --oauth)
4
+ // push: serialise the doc pack and POST it as a new revision (binds the workspace on first push)
5
+ // pull: fetch a revision's artifacts back into the workspace files
6
+ // plugins: forwards to plugins-cli (list | info | sync over the plugin runtime; no plugin code runs)
8
7
  import * as path from "node:path";
9
8
  import { BackendClient, createBackendClient, oauthLogin, saveBackendTokenFile, } from "./backend-client.js";
10
9
  import { fetchScreenshotBlobs, readDocPack, UnsafePackNameError, uploadScreenshotBlobs, writeDocPack, } from "./doc-pack-io.js";
10
+ import { writeFileAtomic } from "./atomic-write.js";
11
11
  import { pluginsCli } from "./plugins-cli.js";
12
12
  import { loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
13
- import { parseFlags } from "./cli-shared.js";
13
+ import { bareValueFlagExit, isHttpUrl, workspaceDirProblem } from "./cli-shared.js";
14
+ import { parseCommandFlags } from "./cli-flags.js";
14
15
  import { configProblem, explainBackendFailure } from "./cli-backend-errors.js";
15
- import { redactUrl, sanitizeForTerminal, shellQuote, usageError, withNext, } from "./cli-messages.js";
16
+ import { describeFsError, redactUrl, sanitizeForTerminal, shellQuote, usageError, withNext, } from "./cli-messages.js";
16
17
  export async function cmdLogin(args) {
17
- const { positionals, flags } = parseFlags(args);
18
+ const parsed = parseCommandFlags("login", args);
19
+ if (typeof parsed === "number")
20
+ return parsed;
21
+ const { positionals, flags } = parsed;
18
22
  const backendUrl = typeof flags.get("backend-url") === "string" ? flags.get("backend-url") : undefined;
19
23
  if (!backendUrl) {
20
24
  return usageError("login", "--backend-url <url> required");
21
25
  }
26
+ if (!isHttpUrl(backendUrl)) {
27
+ return usageError("login", "--backend-url must be an http:// or https:// URL");
28
+ }
22
29
  const oauthFlag = flags.get("oauth");
23
30
  if (oauthFlag !== undefined) {
24
31
  // OAuth 2.1 authorization-code + PKCE against the backend's authorization server. Tokens land
@@ -62,7 +69,7 @@ export async function cmdLogin(args) {
62
69
  try {
63
70
  const h = await client.health();
64
71
  if (!h.ok) {
65
- const note = withNext(`backend health-check at ${redactUrl(backendUrl)} returned ok=false`, "check the backend's logs, then retry");
72
+ const note = withNext(`backend health-check at ${redactUrl(backendUrl)} returned ok=false`, "try again, then contact whoever runs the backend");
66
73
  process.stderr.write(`login: ${note}\n`);
67
74
  return 1;
68
75
  }
@@ -96,10 +103,21 @@ async function ensureBackendBinding(client, projectDir, cfg, workspaceName) {
96
103
  return { wsId, projectId, createdAny };
97
104
  }
98
105
  export async function cmdPush(args) {
99
- const { positionals, flags } = parseFlags(args);
106
+ const parsed = parseCommandFlags("push", args);
107
+ if (typeof parsed === "number")
108
+ return parsed;
109
+ const { positionals, flags } = parsed;
100
110
  if (!positionals[0])
101
111
  return usageError("push", "missing <workspace-dir>");
102
112
  const projectDir = positionals[0];
113
+ const barePush = bareValueFlagExit("push", flags, ["kind", "author"]);
114
+ if (barePush !== undefined)
115
+ return barePush;
116
+ const problem = await workspaceDirProblem(projectDir);
117
+ if (problem) {
118
+ process.stderr.write(`push: ${problem}\n`);
119
+ return 1;
120
+ }
103
121
  const wsCfg = await loadWorkspaceConfig(projectDir);
104
122
  if (!wsCfg?.backend_url) {
105
123
  const file = path.join(projectDir, ".docsxai.json");
@@ -120,7 +138,20 @@ export async function cmdPush(args) {
120
138
  client = await createBackendClient({ baseUrl: wsCfg.backend_url, workspaceDir: projectDir });
121
139
  }
122
140
  catch (e) {
123
- process.stderr.write(`push: ${sanitizeForTerminal(e.message)}\n`);
141
+ const text = explainBackendFailure(e, wsCfg.backend_url, projectDir) ??
142
+ sanitizeForTerminal(e.message);
143
+ process.stderr.write(`push: ${text}\n`);
144
+ return 1;
145
+ }
146
+ // Read the pack first: a file that cannot be read stops the push before the backend gets a
147
+ // workspace, a project or an unfinalized revision.
148
+ let payloads;
149
+ try {
150
+ payloads = await readDocPack(projectDir);
151
+ }
152
+ catch (e) {
153
+ const next = `fix the file, then docsxai push ${shellQuote(projectDir)}`;
154
+ process.stderr.write(`push: ${describeFsError(e) ?? withNext(sanitizeForTerminal(e.message), next)}\n`);
124
155
  return 1;
125
156
  }
126
157
  try {
@@ -132,18 +163,17 @@ export async function cmdPush(args) {
132
163
  backend_workspace_id: binding.wsId,
133
164
  backend_project_id: binding.projectId,
134
165
  };
135
- await fs.writeFile(resolveWorkspacePath(projectDir, ".docsxai.json"), JSON.stringify(updated, null, 2) + "\n", "utf8");
166
+ await writeFileAtomic(resolveWorkspacePath(projectDir, ".docsxai.json"), JSON.stringify(updated, null, 2) + "\n", "utf8");
136
167
  }
137
168
  const rev = await client.createRevision(binding.wsId, binding.projectId, {
138
169
  kind: kindArg,
139
170
  author,
140
171
  });
141
- const payloads = await readDocPack(projectDir);
142
172
  if (payloads.screenshots) {
143
173
  // Screenshot bytes go up as content-addressed blobs (HEAD-probed, so unchanged PNGs are
144
174
  // skipped); the artifact slot carries only the sha256 manifest.
145
175
  const { uploaded, skipped } = await uploadScreenshotBlobs(projectDir, payloads.screenshots, client);
146
- process.stdout.write(`push: screenshots — ${uploaded} blob(s) uploaded, ${skipped} already on the backend\n`);
176
+ process.stdout.write(`push: screenshots, ${uploaded} blob(s) uploaded, ${skipped} already on the backend\n`);
147
177
  }
148
178
  let pushed = 0;
149
179
  for (const [key, p] of Object.entries(payloads)) {
@@ -153,7 +183,7 @@ export async function cmdPush(args) {
153
183
  pushed++;
154
184
  }
155
185
  await client.finalizeRevision(binding.wsId, binding.projectId, rev.id);
156
- process.stdout.write(`push: revision ${sanitizeForTerminal(rev.id)} (${kindArg}, ${sanitizeForTerminal(author)}) on ${redactUrl(wsCfg.backend_url)} — ${pushed} artifact slot${pushed !== 1 ? "s" : ""} uploaded, finalized\n`);
186
+ process.stdout.write(`push: revision ${sanitizeForTerminal(rev.id)} (${kindArg}, ${sanitizeForTerminal(author)}) on ${redactUrl(wsCfg.backend_url)}, ${pushed} artifact slot${pushed !== 1 ? "s" : ""} uploaded, finalized\n`);
157
187
  return 0;
158
188
  }
159
189
  catch (e) {
@@ -164,11 +194,30 @@ export async function cmdPush(args) {
164
194
  return 1;
165
195
  }
166
196
  }
197
+ /** The artifact slots a revision holds; any other name in a revision is not requested. */
198
+ const KNOWN_ARTIFACTS = [
199
+ "flows",
200
+ "annotations",
201
+ "screenshots",
202
+ "style",
203
+ "locators",
204
+ ];
167
205
  export async function cmdPull(args) {
168
- const { positionals, flags } = parseFlags(args);
206
+ const parsed = parseCommandFlags("pull", args);
207
+ if (typeof parsed === "number")
208
+ return parsed;
209
+ const { positionals, flags } = parsed;
169
210
  if (!positionals[0])
170
211
  return usageError("pull", "missing <workspace-dir>");
171
212
  const projectDir = positionals[0];
213
+ const barePull = bareValueFlagExit("pull", flags, ["rev"]);
214
+ if (barePull !== undefined)
215
+ return barePull;
216
+ const problem = await workspaceDirProblem(projectDir);
217
+ if (problem) {
218
+ process.stderr.write(`pull: ${problem}\n`);
219
+ return 1;
220
+ }
172
221
  const wsCfg = await loadWorkspaceConfig(projectDir);
173
222
  if (!wsCfg?.backend_url || !wsCfg.backend_workspace_id || !wsCfg.backend_project_id) {
174
223
  const gap = wsCfg
@@ -184,22 +233,28 @@ export async function cmdPull(args) {
184
233
  client = await createBackendClient({ baseUrl: wsCfg.backend_url, workspaceDir: projectDir });
185
234
  }
186
235
  catch (e) {
187
- process.stderr.write(`pull: ${sanitizeForTerminal(e.message)}\n`);
236
+ const text = explainBackendFailure(e, wsCfg.backend_url, projectDir) ??
237
+ sanitizeForTerminal(e.message);
238
+ process.stderr.write(`pull: ${text}\n`);
188
239
  return 1;
189
240
  }
190
241
  try {
191
242
  const rev = await client.getRevision(wsCfg.backend_workspace_id, wsCfg.backend_project_id, revArg);
192
243
  const payloads = {};
193
244
  for (const artifact of rev.artifacts) {
245
+ if (!KNOWN_ARTIFACTS.includes(artifact)) {
246
+ process.stderr.write(`pull: warning, revision lists the artifact ${JSON.stringify(sanitizeForTerminal(String(artifact)))}, which this docsxai does not know; skipped\n`);
247
+ continue;
248
+ }
194
249
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
250
  payloads[artifact] = await client.getArtifact(wsCfg.backend_workspace_id, wsCfg.backend_project_id, rev.id, artifact);
196
251
  }
197
- // The screenshots artifact is a sha256 manifest — fetch the bytes behind it (integrity-checked).
252
+ // The screenshots artifact is a sha256 manifest, fetch the bytes behind it (integrity-checked).
198
253
  const screenshotBytes = payloads.screenshots
199
254
  ? await fetchScreenshotBlobs(payloads.screenshots, client)
200
255
  : undefined;
201
256
  const r = await writeDocPack(projectDir, payloads, screenshotBytes ? { screenshotBytes } : {});
202
- process.stdout.write(`pull: revision ${sanitizeForTerminal(rev.id)} (${sanitizeForTerminal(rev.kind)}, ${sanitizeForTerminal(rev.author)}) — wrote ${r.filesWritten} file(s) to ${sanitizeForTerminal(projectDir)}\n`);
257
+ process.stdout.write(`pull: revision ${sanitizeForTerminal(rev.id)} (${sanitizeForTerminal(rev.kind)}, ${sanitizeForTerminal(rev.author)}), wrote ${r.filesWritten} file(s) to ${sanitizeForTerminal(projectDir)}\n`);
203
258
  return 0;
204
259
  }
205
260
  catch (e) {
@@ -212,7 +267,7 @@ export async function cmdPull(args) {
212
267
  return 1;
213
268
  }
214
269
  }
215
- /** `docsxai plugins …` — forwards to the plugin-runtime CLI verbatim. */
270
+ /** `docsxai plugins …`: forwards to the plugin-runtime CLI verbatim. */
216
271
  export async function cmdPlugins(args) {
217
272
  return pluginsCli(args);
218
273
  }
@@ -1,6 +1,8 @@
1
1
  export declare function cmdRender(args: string[]): Promise<number>;
2
+ /** A flow name as `burn` passes it on: no separators, and no leading dot, so it can't name a parent or hidden path. */
3
+ export declare const FLOW_NAME: RegExp;
2
4
  /**
3
- * `burn` — bake each annotation into a copy of its screenshot, for surfaces that can't run the
5
+ * `burn`: bake each annotation into a copy of its screenshot, for surfaces that can't run the
4
6
  * interactive viewer. The renderer lives in `@docsxai/viewer`; this runs its `burn` command.
5
7
  */
6
8
  export declare function cmdBurn(args: string[]): Promise<number>;