@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,27 +1,28 @@
1
- // Runtime / session commands — the ones that stand up a workspace or drive a live browser:
2
- // init — scaffold a workspace
3
- // capture-auth — run a role's auth strategy and cache the session
4
- // calibrate — write flows/<name>.flow.yaml from a structured flow-guide
5
- // run — execute the workspace's flows against the live app, emitting annotations
1
+ // Runtime / session commands, the ones that stand up a workspace or drive a live browser:
2
+ // add-flow: write flows/<name>.flow.yaml from a structured flow-guide
3
+ // run: execute the workspace's flows against the live app, emitting annotations
6
4
  //
7
5
  // These reach into the engine's heavier subsystems (Playwright, auth, the flow runtime); the
8
- // thinner static/aid commands live in cli-commands-authoring.ts.
6
+ // thinner static/aid commands live in cli-commands-authoring.ts and capture-auth lives in cli-commands-auth.ts.
9
7
  import { promises as fs } from "node:fs";
10
8
  import * as path from "node:path";
11
- import { LocalStorageStateCache, makeStrategy, parseAuthStrategyFile, resolveCredsEnv, resolveStateCache, } from "./auth.js";
12
- import { calibrate } from "./calibrate.js";
9
+ import { cachedSessionIsCorrupt, parseAuthStrategyFile, resolveStateCache, storageStateFileName, } from "./auth.js";
10
+ import { calibrate, CalibrateError } from "./calibrate.js";
13
11
  import { expandFlowVariants, FlowFileError, parseFlowFile, resolveFlowExtends, } from "./flow-file.js";
14
12
  import { assertNoCaseCollision } from "./flow-name-rules.js";
15
13
  import { recordRunHistory } from "./backend-client.js";
14
+ import { resolveDeviceScaleFactor } from "./device-scale-factor.js";
16
15
  import { runFlowsInSessions } from "./run-flows.js";
17
- import { PlaywrightInstrumentedBrowser } from "./playwright-instrumented-browser.js";
18
- import { initWorkspace, loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
19
- import { listFlowFiles, parseFlags } from "./cli-shared.js";
16
+ import { loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
17
+ import { bareValueFlagExit, claimFlowName, flagMissingValue, isRunnableUrl, listFlowFiles, } from "./cli-shared.js";
18
+ import { parseCommandFlags } from "./cli-flags.js";
20
19
  import { emitVerifyReport, parseVerifyArgs } from "./cli-verify.js";
21
20
  import { verifyDeterminism } from "./verify-determinism.js";
22
21
  import { VerifyTreeError } from "./verify-tree.js";
23
- import { shellQuote, usageError, withNext } from "./cli-messages.js";
22
+ import { describeFsError, shellQuote, usageError, withNext } from "./cli-messages.js";
24
23
  import { reportRun } from "./cli-run-summary.js";
24
+ import { warnStaleMatrixOutputs } from "./cli-run-stale.js";
25
+ import { warnUnusableConfig } from "./cli-backend-errors.js";
25
26
  async function loadAuthStorageState(projectDir) {
26
27
  const descriptorPath = resolveWorkspacePath(projectDir, "auth", "strategy.yaml");
27
28
  let text;
@@ -29,22 +30,50 @@ async function loadAuthStorageState(projectDir) {
29
30
  text = await fs.readFile(descriptorPath, "utf8");
30
31
  }
31
32
  catch {
32
- return undefined; // no auth configured — run with a fresh context
33
+ return undefined; // no auth configured, run with a fresh context
33
34
  }
34
35
  const descriptor = parseAuthStrategyFile(text, descriptorPath);
35
36
  const role = descriptor.default_role;
36
37
  const cache = await resolveStateCache(descriptor.roles[role], projectDir);
37
38
  const state = await cache.load(role);
38
39
  if (!state) {
39
- throw new Error(withNext(`auth/strategy.yaml configures role "${role}" but there is no valid cached session at ${path.join(projectDir, ".auth", role + ".json")} (missing or expired)`, `docsxai capture-auth ${shellQuote(projectDir)}`));
40
+ throw new Error(withNext(`auth/strategy.yaml configures role "${role}" but there is no valid cached session at ${path.join(projectDir, ".auth", storageStateFileName(role))} (${(await cachedSessionIsCorrupt(resolveWorkspacePath(projectDir, ".auth"), role)) ? "the file is corrupt" : "missing or expired"})`, `docsxai capture-auth ${shellQuote(projectDir)}`));
40
41
  }
41
42
  return state;
42
43
  }
44
+ /** The flags of `run` that take a value; one given bare is a usage error, not a flag to ignore. */
45
+ const RUN_VALUE_FLAGS = [
46
+ "flow",
47
+ "stop-after",
48
+ "start-from",
49
+ "variant",
50
+ "cdp",
51
+ "base-url",
52
+ "concurrency",
53
+ "device-scale-factor",
54
+ ];
43
55
  export async function cmdRun(args) {
44
- const { positionals, flags } = parseFlags(args);
56
+ const parsed = parseCommandFlags("run", args);
57
+ if (typeof parsed === "number")
58
+ return parsed;
59
+ const { positionals, flags } = parsed;
45
60
  if (!positionals[0])
46
61
  return usageError("run", "missing <workspace-dir>");
47
62
  const projectDir = positionals[0];
63
+ const bare = flagMissingValue(flags, RUN_VALUE_FLAGS);
64
+ if (bare)
65
+ return usageError("run", `--${bare} needs a value`);
66
+ // An empty value is falsy downstream, so `--flow ""` would run every flow and `--variant ""` every variant.
67
+ const empty = RUN_VALUE_FLAGS.find((n) => flags.get(n) === "" && n !== "device-scale-factor");
68
+ if (empty)
69
+ return usageError("run", `--${empty} needs a value (got an empty string)`);
70
+ const concurrencyFlag = flags.get("concurrency");
71
+ if (typeof concurrencyFlag === "string" && !/^[1-9]\d*$/.test(concurrencyFlag)) {
72
+ return usageError("run", `--concurrency must be a whole number of 1 or more (got "${concurrencyFlag}")`);
73
+ }
74
+ const dsf = resolveDeviceScaleFactor(flags.get("device-scale-factor"), process.env, typeof flags.get("cdp") === "string");
75
+ if ("error" in dsf)
76
+ return usageError("run", dsf.error);
48
77
  const onlyFlow = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
49
78
  const stopAfter = typeof flags.get("stop-after") === "string" ? flags.get("stop-after") : undefined;
50
79
  const startFrom = typeof flags.get("start-from") === "string" ? flags.get("start-from") : undefined;
@@ -59,8 +88,19 @@ export async function cmdRun(args) {
59
88
  if (typeof verify === "string")
60
89
  return usageError("run", verify);
61
90
  const wsCfg = await loadWorkspaceConfig(projectDir);
62
- const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
63
- wsCfg?.app_url;
91
+ if (!wsCfg)
92
+ await warnUnusableConfig("run", projectDir);
93
+ const baseUrlFlag = typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined;
94
+ if (baseUrlFlag !== undefined && !isRunnableUrl(baseUrlFlag)) {
95
+ return usageError("run", "--base-url must be an http://, https:// or file:// URL");
96
+ }
97
+ const baseURL = baseUrlFlag ?? wsCfg?.app_url;
98
+ if (baseUrlFlag === undefined && wsCfg?.app_url !== undefined && !isRunnableUrl(wsCfg.app_url)) {
99
+ const file = resolveWorkspacePath(projectDir, ".docsxai.json");
100
+ const note = withNext(`app_url in ${file} is not an http://, https:// or file:// URL`, `fix app_url in ${file}, or pass --base-url <url>`);
101
+ process.stderr.write(`run: ${note}\n`);
102
+ return 1;
103
+ }
64
104
  const ignoreHTTPSErrors = flags.get("ignore-https-errors") === true || !!wsCfg?.ignore_https_errors;
65
105
  let flowPaths;
66
106
  try {
@@ -72,14 +112,7 @@ export async function cmdRun(args) {
72
112
  }
73
113
  const loadFlowFile = async (name) => {
74
114
  const fp = resolveWorkspacePath(projectDir, "flows", `${name}.flow.yaml`);
75
- let text;
76
- try {
77
- text = await fs.readFile(fp, "utf8");
78
- }
79
- catch {
80
- throw new FlowFileError(`\`extends\`: no flow named "${name}" at ${fp}`);
81
- }
82
- return parseFlowFile(text, fp);
115
+ return parseFlowFile(await fs.readFile(fp, "utf8"), fp);
83
116
  };
84
117
  // `flows` goes to the run loop, which expands each matrix flow itself; `units` is the same
85
118
  // expansion here, for the checks and messages that need the variant ids before anything launches.
@@ -87,6 +120,7 @@ export async function cmdRun(args) {
87
120
  const units = [];
88
121
  const matrixFlows = new Set();
89
122
  const knownFlows = [];
123
+ const flowOwners = new Map();
90
124
  let flowCount = 0;
91
125
  for (const fp of flowPaths) {
92
126
  let flow;
@@ -106,6 +140,11 @@ export async function cmdRun(args) {
106
140
  knownFlows.push(flow.name);
107
141
  if (onlyFlow && flow.name !== onlyFlow)
108
142
  continue;
143
+ const duplicate = claimFlowName(flowOwners, flow.name, fp);
144
+ if (duplicate) {
145
+ process.stderr.write(`run: ${withNext(duplicate, `docsxai lint ${shellQuote(projectDir)}`)}\n`);
146
+ return 1;
147
+ }
109
148
  flowCount++;
110
149
  flows.push(flow);
111
150
  if (flow.matrix)
@@ -114,8 +153,10 @@ export async function cmdRun(args) {
114
153
  }
115
154
  if (flowCount === 0) {
116
155
  process.stderr.write(onlyFlow
117
- ? `run: no flow named "${onlyFlow}" (flows: ${knownFlows.join(", ") || "none"})\n`
118
- : `run: ${withNext(`no flow-files in ${projectDir}/flows`, `docsxai calibrate ${shellQuote(projectDir)} --from <flow.yaml>`)}\n`);
156
+ ? `run: ${withNext(`no flow named "${onlyFlow}" (flows: ${knownFlows.join(", ") || "none"})`, knownFlows.length > 0
157
+ ? `docsxai flow-tree ${shellQuote(projectDir)} (lists the flows), then pass --flow <name>`
158
+ : `docsxai add-flow ${shellQuote(projectDir)} --from <flow.yaml>`)}\n`
159
+ : `run: ${withNext(`no flow-files in ${projectDir}/flows`, `docsxai add-flow ${shellQuote(projectDir)} --from <flow.yaml>`)}\n`);
119
160
  return 1;
120
161
  }
121
162
  try {
@@ -140,25 +181,38 @@ export async function cmdRun(args) {
140
181
  }
141
182
  units.splice(0, units.length, ...wanted);
142
183
  }
143
- for (const name of matrixFlows) {
144
- const stale = resolveWorkspacePath(projectDir, "docs", name, "annotations.json");
145
- if (await fs.access(stale).then(() => true, () => false)) {
146
- process.stderr.write(`run: warning — docs/${name}/annotations.json is from before ${name} had a matrix; its variants write to docs/${name}/<variant>/, so remove the old docs/${name}/ outputs\n`);
184
+ // A step id that no selected flow has would only fail after a browser had launched, as a halt.
185
+ for (const [flag, stepId] of [
186
+ ["start-from", startFrom],
187
+ ["stop-after", stopAfter],
188
+ ]) {
189
+ if (!stepId || units.some((u) => u.flow.steps.some((st) => st.id === stepId)))
190
+ continue;
191
+ const have = [...new Set(units.flatMap((u) => u.flow.steps.map((st) => st.id)))];
192
+ const where = onlyFlow ? `flow "${onlyFlow}"` : "any selected flow";
193
+ return usageError("run", `--${flag}: no step "${stepId}" in ${where} (steps: ${have.join(", ")})`);
194
+ }
195
+ await warnStaleMatrixOutputs(projectDir, matrixFlows);
196
+ if (!baseURL && !cdpEndpoint) {
197
+ const relative = units.some((u) => u.flow.steps.some((s) => s.action === "navigate" && s.value && !/^[a-z][a-z0-9+.-]*:/i.test(s.value)));
198
+ if (relative) {
199
+ const note = withNext("warning, a flow navigates to a relative path and there is no app_url", `set app_url in ${path.join(projectDir, ".docsxai.json")} or pass --base-url <url>`);
200
+ process.stderr.write(`run: ${note}\n`);
147
201
  }
148
202
  }
203
+ // An attached browser (--cdp) owns its own login; the cached session is not loaded over it.
149
204
  let storageState;
150
205
  try {
151
- storageState = await loadAuthStorageState(projectDir);
206
+ storageState = cdpEndpoint ? undefined : await loadAuthStorageState(projectDir);
152
207
  }
153
208
  catch (e) {
154
- process.stderr.write(`run: ${e.message}\n`);
209
+ process.stderr.write(`run: ${describeFsError(e) ?? e.message}\n`);
155
210
  return 1;
156
211
  }
157
212
  // Parallel runners: each flow gets its own Playwright session, so flows are isolated and can run together.
158
213
  // `--concurrency N` (default 1) caps how many run at once. `--pause` / `--stop-after` force concurrency=1
159
214
  // (they're single-flow calibration aids; mixing them with parallelism would be chaos).
160
- const concurrencyRaw = typeof flags.get("concurrency") === "string" ? Number(flags.get("concurrency")) : 1;
161
- const requestedConcurrency = Math.max(1, Math.floor(concurrencyRaw || 1));
215
+ const requestedConcurrency = typeof concurrencyFlag === "string" ? Number(concurrencyFlag) : 1;
162
216
  const forceSingle = pause || stopAfter || startFrom || cdpEndpoint;
163
217
  const concurrency = forceSingle ? 1 : requestedConcurrency;
164
218
  if (forceSingle && requestedConcurrency > 1) {
@@ -178,6 +232,7 @@ export async function cmdRun(args) {
178
232
  startFrom,
179
233
  obstacles: wsCfg?.annotations?.obstacles === true,
180
234
  concurrency,
235
+ ...(dsf.factor !== undefined ? { deviceScaleFactor: dsf.factor } : {}),
181
236
  };
182
237
  // Verification runs the same loop N times into isolated roots and prints the report on stdout, so
183
238
  // its progress lines go to stderr.
@@ -216,153 +271,23 @@ export async function cmdRun(args) {
216
271
  summary: `${okCount}/${units.length} ${noun} ok`,
217
272
  });
218
273
  if (history.warning)
219
- process.stderr.write(`run: warning — ${history.warning}\n`);
274
+ process.stderr.write(`run: warning: ${history.warning}\n`);
220
275
  return anyFailed ? 1 : 0;
221
276
  }
222
- export async function cmdCaptureAuth(args) {
223
- const { positionals, flags } = parseFlags(args);
224
- const projectDir = positionals[0];
225
- if (!projectDir)
226
- return usageError("capture-auth", "missing <workspace-dir>");
227
- const wsCfg = await loadWorkspaceConfig(projectDir);
228
- const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
229
- wsCfg?.app_url;
230
- if (!baseURL) {
231
- return usageError("capture-auth", "--base-url <url> is required (or set app_url in the workspace's .docsxai.json)");
232
- }
233
- const headless = flags.get("headless") === true;
234
- const ignoreHTTPSErrors = flags.get("ignore-https-errors") === true || !!wsCfg?.ignore_https_errors;
235
- const authCookie = typeof flags.get("auth-cookie") === "string" ? flags.get("auth-cookie") : undefined;
236
- const cdp = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
237
- const fresh = flags.get("fresh") === true;
238
- // Persistent Chrome profile under the workspace — re-running capture-auth reuses the login. (Not when attaching, or with --fresh.)
239
- const profileDir = fresh || cdp ? undefined : resolveWorkspacePath(projectDir, ".auth", "chrome-profile");
240
- const descriptorPath = resolveWorkspacePath(projectDir, "auth", "strategy.yaml");
241
- let descriptorText;
242
- try {
243
- descriptorText = await fs.readFile(descriptorPath, "utf8");
244
- }
245
- catch {
246
- process.stderr.write(`capture-auth: ${withNext(`no auth descriptor at ${descriptorPath}`, "write auth/strategy.yaml (`docsxai init <new-dir>` scaffolds an example to copy)")}\n`);
247
- return 1;
248
- }
249
- let role;
250
- let roleAuth;
251
- try {
252
- const descriptor = parseAuthStrategyFile(descriptorText, descriptorPath);
253
- role =
254
- typeof flags.get("role") === "string"
255
- ? flags.get("role")
256
- : descriptor.default_role;
257
- const ra = descriptor.roles[role];
258
- if (!ra) {
259
- const roles = Object.keys(descriptor.roles).join(", ");
260
- process.stderr.write(`capture-auth: role "${role}" not in ${descriptorPath} (roles: ${roles}); pass --role <role>\n`);
261
- return 1;
262
- }
263
- roleAuth = ra;
264
- }
265
- catch (e) {
266
- process.stderr.write(`capture-auth: ${e.message}\n`);
267
- return 1;
268
- }
269
- let creds;
270
- try {
271
- creds = resolveCredsEnv(roleAuth);
272
- }
273
- catch (e) {
274
- process.stderr.write(`capture-auth: ${e.message}\n`);
275
- return 1;
276
- }
277
- let strategy;
278
- try {
279
- strategy = makeStrategy(roleAuth, {
280
- instrumentedBrowser: () => new PlaywrightInstrumentedBrowser({
281
- headless,
282
- ignoreHTTPSErrors,
283
- ...(cdp ? { connectOverCdp: cdp } : {}),
284
- ...(profileDir ? { profileDir } : {}),
285
- }),
286
- });
287
- }
288
- catch (e) {
289
- process.stderr.write(`capture-auth: ${e.message}\n`);
290
- return 1;
291
- }
292
- try {
293
- process.stdout.write(`capture-auth: launching browser for role "${role}" (${roleAuth.strategy})${cdp ? ` — attaching to ${cdp}` : profileDir ? " — reusing saved profile if present" : " — fresh profile"}; log in if prompted, then trigger capture…\n`);
294
- const result = await strategy.authenticate({ creds, options: roleAuth.options, baseURL, role });
295
- const cookies = result.storageState.cookies ?? [];
296
- process.stdout.write(`capture-auth: captured ${cookies.length} cookie(s)${cookies.length ? " (newest expiry first):" : ""}\n`);
297
- for (const c of [...cookies].sort((a, b) => (b.expires || 0) - (a.expires || 0))) {
298
- const exp = c.expires && c.expires > 0 ? new Date(c.expires * 1000).toISOString() : "(session)";
299
- process.stdout.write(` ${c.name} @${c.domain} expires ${exp}\n`);
300
- }
301
- const { expiresAt, source } = await new LocalStorageStateCache(resolveWorkspacePath(projectDir, ".auth")).save(role, result, roleAuth, Date.now(), authCookie ? { authCookie } : {});
302
- process.stdout.write(`capture-auth: cached ${role} → ${path.join(projectDir, ".auth", role + ".json")}\n` +
303
- ` expires ${new Date(expiresAt).toISOString()} (from ${source}; re-run when it lapses)\n`);
304
- if (!/^auth-cookie/.test(source)) {
305
- process.stdout.write(` tip: pick the app's auth/session cookie from the list above and set 'cache.auth_cookie: <name>' in\n` +
306
- ` ${path.join(projectDir, "auth", "strategy.yaml")} (or pass --auth-cookie <name>) so the cache tracks its real expiry.\n`);
307
- }
308
- return 0;
309
- }
310
- catch (e) {
311
- process.stderr.write(`capture-auth: ${e.message}\n`);
312
- return 1;
313
- }
314
- }
315
- export async function cmdInit(args) {
316
- const { positionals, flags } = parseFlags(args);
317
- const persistTmp = flags.get("persist") === "tmp";
318
- const dir = positionals[0];
319
- if (!persistTmp && !dir)
320
- return usageError("init", "missing <workspace-dir> (or use --persist tmp)");
321
- const str = (k) => typeof flags.get(k) === "string" ? flags.get(k) : undefined;
322
- const auth = str("auth");
323
- if (auth !== undefined && auth !== "manual-capture" && auth !== "none") {
324
- process.stderr.write("init: --auth must be 'manual-capture' or 'none'\n");
325
- return 2;
326
- }
327
- const trigger = str("capture-trigger");
328
- if (trigger !== undefined && trigger !== "console" && trigger !== "button") {
329
- process.stderr.write("init: --capture-trigger must be 'console' or 'button'\n");
330
- return 2;
331
- }
332
- const appUrl = str("app-url");
333
- const role = str("role");
334
- const ttl = str("ttl");
335
- const authCookie = str("auth-cookie");
336
- try {
337
- const r = await initWorkspace({
338
- ...(dir ? { dir } : {}),
339
- persistTmp,
340
- ...(appUrl ? { appUrl } : {}),
341
- ...(auth ? { auth } : {}),
342
- ...(role ? { role } : {}),
343
- ...(ttl ? { ttl } : {}),
344
- ...(trigger ? { captureTrigger: trigger } : {}),
345
- ...(authCookie ? { authCookie } : {}),
346
- ignoreHttpsErrors: flags.get("ignore-https-errors") === true,
347
- force: flags.get("force") === true,
348
- });
349
- process.stdout.write(`init: workspace ${r.ephemeral ? "(ephemeral) " : ""}at ${r.dir}\n created: ${r.created.join(", ")}\n`);
350
- process.stdout.write(` next: ${appUrl ? "" : "(set app_url in .docsxai.json, then) "}docsxai capture-auth ${shellQuote(r.dir)} → …calibrate… → docsxai run ${shellQuote(r.dir)} → docsxai render ${shellQuote(r.dir)}\n`);
351
- return 0;
352
- }
353
- catch (e) {
354
- process.stderr.write(`init: ${e.message.replace(/^init: /, "")}\n`);
355
- return 1;
356
- }
357
- }
358
- export async function cmdCalibrate(args) {
359
- const { positionals, flags } = parseFlags(args);
277
+ export async function cmdAddFlow(args) {
278
+ const parsed = parseCommandFlags("add-flow", args);
279
+ if (typeof parsed === "number")
280
+ return parsed;
281
+ const { positionals, flags } = parsed;
360
282
  const workspaceDir = positionals[0];
361
283
  if (!workspaceDir)
362
- return usageError("calibrate", "missing <workspace-dir>");
284
+ return usageError("add-flow", "missing <workspace-dir>");
285
+ const bareCalibrate = bareValueFlagExit("add-flow", flags, ["from", "name"]);
286
+ if (bareCalibrate !== undefined)
287
+ return bareCalibrate;
363
288
  const from = typeof flags.get("from") === "string" ? flags.get("from") : undefined;
364
289
  if (!from) {
365
- return usageError("calibrate", "--from <flow.md|.yaml> is required (the structured flow-guide)");
290
+ return usageError("add-flow", "--from <flow.md|.yaml> is required (the structured flow-guide)");
366
291
  }
367
292
  const flowName = typeof flags.get("name") === "string" ? flags.get("name") : undefined;
368
293
  let text;
@@ -371,7 +296,7 @@ export async function cmdCalibrate(args) {
371
296
  }
372
297
  catch (e) {
373
298
  const code = e.code ?? "unreadable";
374
- process.stderr.write(`calibrate: cannot read ${from} (${code}); check the path\n`);
299
+ process.stderr.write(`add-flow: cannot read ${from} (${code}); check the path\n`);
375
300
  return 1;
376
301
  }
377
302
  try {
@@ -381,14 +306,18 @@ export async function cmdCalibrate(args) {
381
306
  fromSource: from,
382
307
  ...(flowName ? { flowName } : {}),
383
308
  });
384
- process.stdout.write(`calibrate: wrote ${r.flowFilePath} (${r.flow.steps.length} steps)\n`);
309
+ process.stdout.write(`add-flow: wrote ${r.flowFilePath} (${r.flow.steps.length} steps)\n`);
385
310
  if (r.wroteStyle)
386
- process.stdout.write(`calibrate: wrote default ${r.stylePath}\n`);
311
+ process.stdout.write(`add-flow: wrote default ${r.stylePath}\n`);
387
312
  process.stdout.write(` next: docsxai run ${shellQuote(workspaceDir)} (then: docsxai render ${shellQuote(workspaceDir)})\n`);
388
313
  return 0;
389
314
  }
390
315
  catch (e) {
391
- process.stderr.write(`calibrate: ${withNext(e.message, `fix ${shellQuote(from)}, then docsxai calibrate ${shellQuote(workspaceDir)} --from ${shellQuote(from)}`)}\n`);
316
+ const rerun = `docsxai add-flow ${shellQuote(workspaceDir)} --from ${shellQuote(from)}`;
317
+ const next = e instanceof CalibrateError && e.field === "name-flag"
318
+ ? `${rerun} --name <flow>`
319
+ : `fix ${shellQuote(from)}, then ${rerun}`;
320
+ process.stderr.write(`add-flow: ${withNext(e.message, next)}\n`);
392
321
  return 1;
393
322
  }
394
323
  }
@@ -0,0 +1,2 @@
1
+ /** `site`: run the viewer's `site` with the flags given; its exit code is this command's. */
2
+ export declare function cmdSite(args: string[]): Promise<number>;
@@ -0,0 +1,77 @@
1
+ // `site`: emit an Astro Starlight docs site from the workspace's doc pack. The emitter lives in
2
+ // `@docsxai/viewer`; like `burn` and `pack`, this checks the argv edge and runs the viewer's `site`
3
+ // command through the shared bin resolution, so one global install reaches it as `docsxai site`.
4
+ import { FLOW_NAME } from "./cli-commands-docpack.js";
5
+ import { nearestName } from "./cli-help.js";
6
+ import { usageError } from "./cli-messages.js";
7
+ import { runViewerBin } from "./viewer-bin.js";
8
+ /** The value flags other than `--flow`, which repeats; each of these may appear once. */
9
+ const VALUED = ["--out", "--title", "--accent", "--lang"];
10
+ const FLAGS = [...VALUED, "--build", "--flow"].map((f) => f.slice(2));
11
+ /** Parse `site`'s argv. Returns the usage-error message when the argv is malformed. */
12
+ function parseSiteArgs(args) {
13
+ const parsed = { workspace: "", values: new Map(), flows: [], build: false };
14
+ const positionals = [];
15
+ for (let i = 0; i < args.length; i++) {
16
+ let a = args[i];
17
+ if (!a.startsWith("--")) {
18
+ positionals.push(a);
19
+ continue;
20
+ }
21
+ const eq = a.indexOf("=");
22
+ let inline;
23
+ if (eq > 2) {
24
+ inline = a.slice(eq + 1);
25
+ a = a.slice(0, eq);
26
+ }
27
+ if (a === "--build") {
28
+ if (inline !== undefined)
29
+ return "--build takes no value";
30
+ parsed.build = true;
31
+ continue;
32
+ }
33
+ if (a !== "--flow" && !VALUED.includes(a)) {
34
+ const near = nearestName(a.slice(2), FLAGS);
35
+ return `unknown flag ${a}${near ? `, did you mean --${near}?` : ""}`;
36
+ }
37
+ const value = inline ?? args[++i];
38
+ if (value === undefined || value === "" || value.startsWith("--"))
39
+ return `${a} needs a value`;
40
+ if (a === "--flow") {
41
+ if (!FLOW_NAME.test(value))
42
+ return `--flow "${value}" is not a flow name`;
43
+ parsed.flows.push(value);
44
+ }
45
+ else {
46
+ if (parsed.values.has(a))
47
+ return `${a} given more than once`;
48
+ parsed.values.set(a, value);
49
+ }
50
+ }
51
+ if (positionals.length === 0)
52
+ return "missing <workspace-dir>";
53
+ if (positionals.length > 1)
54
+ return `unexpected argument "${positionals[1]}"`;
55
+ parsed.workspace = positionals[0];
56
+ return parsed;
57
+ }
58
+ /** `site`: run the viewer's `site` with the flags given; its exit code is this command's. */
59
+ export async function cmdSite(args) {
60
+ const parsed = parseSiteArgs(args);
61
+ if (typeof parsed === "string")
62
+ return usageError("site", parsed);
63
+ const valued = (flag) => {
64
+ const value = parsed.values.get(flag);
65
+ return value === undefined ? [] : [flag, value];
66
+ };
67
+ return runViewerBin("site", [
68
+ "site",
69
+ parsed.workspace,
70
+ ...valued("--out"),
71
+ ...(parsed.build ? ["--build"] : []),
72
+ ...valued("--title"),
73
+ ...valued("--accent"),
74
+ ...valued("--lang"),
75
+ ...parsed.flows.flatMap((f) => ["--flow", f]),
76
+ ]);
77
+ }
@@ -0,0 +1 @@
1
+ export declare function cmdStyle(args: string[]): Promise<number>;
@@ -0,0 +1,85 @@
1
+ // style: init/validate docs/style.yaml and rederive style.json; --check scans prose for jargon leaks.
2
+ // Split from cli-commands-authoring.ts to keep both files under the max-lines ceiling.
3
+ import * as path from "node:path";
4
+ import { bareValueFlagExit, workspaceDirProblem } from "./cli-shared.js";
5
+ import { parseCommandFlags } from "./cli-flags.js";
6
+ import { describeFsError, shellQuote, usageError, withNext } from "./cli-messages.js";
7
+ import { formatJargonHitsText, initStyleIfAbsent, loadStyle, scanWorkspaceForJargon, StyleError, writeStyle, } from "./style.js";
8
+ /** A style file the disk refused, as a `style:` line with the chmod; any other error is rethrown. */
9
+ function styleFsFailure(e) {
10
+ const line = describeFsError(e);
11
+ if (line === undefined)
12
+ throw e;
13
+ process.stderr.write(`style: ${line}\n`);
14
+ return 1;
15
+ }
16
+ export async function cmdStyle(args) {
17
+ const parsed = parseCommandFlags("style", args);
18
+ if (typeof parsed === "number")
19
+ return parsed;
20
+ const { positionals, flags } = parsed;
21
+ if (!positionals[0])
22
+ return usageError("style", "missing <workspace-dir>");
23
+ const projectDir = positionals[0];
24
+ const bareStyle = bareValueFlagExit("style", flags, ["format"]);
25
+ if (bareStyle !== undefined)
26
+ return bareStyle;
27
+ const check = flags.get("check") === true;
28
+ const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
29
+ if (format !== "text" && format !== "json") {
30
+ return usageError("style", '--format must be "text" or "json"');
31
+ }
32
+ const problem = await workspaceDirProblem(projectDir);
33
+ if (problem) {
34
+ process.stderr.write(`style: ${problem}\n`);
35
+ return 1;
36
+ }
37
+ // init-if-absent (idempotent); then load + validate; then rederive JSON; then optional jargon check.
38
+ let created;
39
+ try {
40
+ ({ created } = await initStyleIfAbsent(projectDir));
41
+ }
42
+ catch (e) {
43
+ return styleFsFailure(e);
44
+ }
45
+ let style;
46
+ try {
47
+ style = await loadStyle(projectDir);
48
+ }
49
+ catch (e) {
50
+ if (e instanceof StyleError) {
51
+ process.stderr.write(`style: ${withNext(e.message, `fix docs/style.yaml, then docsxai style ${shellQuote(projectDir)}`)}\n`);
52
+ return 1;
53
+ }
54
+ throw e;
55
+ }
56
+ if (!style) {
57
+ // Shouldn't happen after initStyleIfAbsent, but defensive.
58
+ process.stderr.write(`style: failed to initialise style.yaml in ${projectDir}\n`);
59
+ return 1;
60
+ }
61
+ // Always rewrite to ensure derived JSON stays in sync with YAML (idempotent).
62
+ let paths;
63
+ try {
64
+ paths = await writeStyle(projectDir, style);
65
+ }
66
+ catch (e) {
67
+ return styleFsFailure(e);
68
+ }
69
+ let hits = [];
70
+ if (check) {
71
+ hits = await scanWorkspaceForJargon(projectDir, style);
72
+ }
73
+ if (format === "json") {
74
+ process.stdout.write(JSON.stringify({ style, paths, created, jargonLeaks: check ? hits : undefined }, null, 2) +
75
+ "\n");
76
+ }
77
+ else {
78
+ process.stdout.write(`style: ${created ? "created" : "validated"} ${path.relative(projectDir, paths.yamlPath)}; rederived ${path.relative(projectDir, paths.jsonPath)}\n`);
79
+ if (check) {
80
+ process.stdout.write("\n");
81
+ process.stdout.write(formatJargonHitsText(hits));
82
+ }
83
+ }
84
+ return check && hits.length > 0 ? 1 : 0;
85
+ }
@@ -0,0 +1,18 @@
1
+ import { parseFlags } from "./cli-shared.js";
2
+ export interface CommandFlags {
3
+ /** Flags that take a value. A bare one is rejected by the command's own value check. */
4
+ value: readonly string[];
5
+ /** Flags that take no value. */
6
+ bool: readonly string[];
7
+ /** Flags a handler validates itself, because it words a specific error for a value or a bare use. */
8
+ loose?: readonly string[];
9
+ }
10
+ /** Every command that reads its argv through {@link parseCommandFlags}, with the flags in `--help`. */
11
+ export declare const COMMAND_FLAGS: Readonly<Record<string, CommandFlags>>;
12
+ type Parsed = Pick<ReturnType<typeof parseFlags>, "positionals" | "flags">;
13
+ /**
14
+ * Parse `args` for `label` (the key into {@link COMMAND_FLAGS} unless `spec` names another).
15
+ * Returns the parsed argv, or exit code 2 after the usage error.
16
+ */
17
+ export declare function parseCommandFlags(label: string, args: string[], spec?: string): Parsed | number;
18
+ export {};