@cappa/cli 0.12.0 → 0.13.0

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.
package/dist/index.cjs CHANGED
@@ -16,191 +16,32 @@ var __copyProps = (to, from, except, desc) => {
16
16
  }
17
17
  return to;
18
18
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
24
  let _cappa_logger = require("@cappa/logger");
25
25
  let commander = require("commander");
26
+ let _cappa_config = require("@cappa/config");
26
27
  let _cappa_core = require("@cappa/core");
27
- let node_fs = require("node:fs");
28
- node_fs = __toESM(node_fs);
29
28
  let node_path = require("node:path");
30
29
  node_path = __toESM(node_path);
31
- let jiti = require("jiti");
32
- let node_crypto = require("node:crypto");
33
- let node_fs_promises = require("node:fs/promises");
34
30
  let chalk = require("chalk");
35
31
  chalk = __toESM(chalk);
32
+ let zod = require("zod");
33
+ let _cappa_client = require("@cappa/client");
36
34
  let _cappa_server = require("@cappa/server");
35
+ let node_fs = require("node:fs");
36
+ node_fs = __toESM(node_fs);
37
+ let node_crypto = require("node:crypto");
37
38
  //#region package.json
38
- var version = "0.12.0";
39
- //#endregion
40
- //#region src/features/config/getPlugins.ts
41
- async function getPlugins(plugins) {
42
- if (!plugins) return [];
43
- const loadedPlugins = [];
44
- for (const plugin of plugins) if (typeof plugin === "function") {
45
- const pluginDef = plugin();
46
- loadedPlugins.push(pluginDef);
47
- } else loadedPlugins.push(plugin);
48
- return loadedPlugins;
49
- }
50
- function isPromise(value) {
51
- return value !== null && typeof value === "object" && "then" in value && typeof value.then === "function";
52
- }
53
- //#endregion
54
- //#region src/features/config/loadConfig.ts
55
- const tsLoader = async (configFile) => {
56
- return await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
57
- jsx: {
58
- runtime: "automatic",
59
- importSource: "@cappa/core"
60
- },
61
- sourceMaps: true
62
- }).import(configFile, { default: true });
63
- };
64
- async function loadConfig() {
65
- const configPath = node_path.default.resolve(process.cwd(), "cappa.config.ts");
66
- if (!node_fs.default.existsSync(configPath)) throw new Error("Config not found. Please create a cappa.config.ts file in the current directory.");
67
- try {
68
- const config = await tsLoader(configPath);
69
- if (!config) throw new Error("Config file is empty or does not export a valid configuration.");
70
- return {
71
- filepath: configPath,
72
- config
73
- };
74
- } catch (error) {
75
- throw new Error(`Failed to load config from ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
76
- }
77
- }
78
- //#endregion
79
- //#region src/features/config/getConfig.ts
80
- /**
81
- * Converting UserConfig to Config without a change in the object beside the JSON convert.
82
- */
83
- async function getConfig(loadResult) {
84
- const configData = (loadResult ?? await loadConfig())?.config;
85
- let cappaUserConfig = Promise.resolve(configData);
86
- const configEnv = {
87
- command: process.argv[2],
88
- mode: process.env.NODE_ENV || "development",
89
- env: process.env
90
- };
91
- if (typeof configData === "function") {
92
- const possiblePromise = configData(configEnv);
93
- if (isPromise(possiblePromise)) cappaUserConfig = possiblePromise;
94
- else cappaUserConfig = Promise.resolve(possiblePromise);
95
- }
96
- const userConfig = await cappaUserConfig;
97
- if (!userConfig || typeof userConfig === "function") throw new Error("Invalid configuration: no valid config found");
98
- const diffConfig = (() => {
99
- if (userConfig.diff?.type !== "gmsd") return {
100
- type: "pixel",
101
- threshold: userConfig.diff?.threshold ?? .1,
102
- includeAA: userConfig.diff?.includeAA ?? false,
103
- fastBufferCheck: userConfig.diff?.fastBufferCheck ?? true,
104
- maxDiffPixels: userConfig.diff?.maxDiffPixels ?? 0,
105
- maxDiffPercentage: userConfig.diff?.maxDiffPercentage ?? 0,
106
- interpret: userConfig.diff?.interpret ?? false
107
- };
108
- return {
109
- type: "gmsd",
110
- threshold: userConfig.diff.threshold ?? .1,
111
- downsample: userConfig.diff.downsample ?? 0,
112
- c: userConfig.diff.c ?? 170
113
- };
114
- })();
115
- const configWithDefaults = {
116
- outputDir: userConfig.outputDir || "./screenshots",
117
- retries: userConfig.retries || 2,
118
- concurrency: userConfig.concurrency || 1,
119
- logConsoleEvents: userConfig.logConsoleEvents ?? true,
120
- diff: diffConfig,
121
- plugins: userConfig.plugins ? await getPlugins(userConfig.plugins) : [],
122
- onFail: userConfig.onFail,
123
- screenshot: {
124
- fullPage: userConfig.screenshot?.fullPage ?? true,
125
- viewport: userConfig.screenshot?.viewport ?? {
126
- width: 1920,
127
- height: 1080
128
- }
129
- },
130
- review: {
131
- theme: userConfig.review?.theme ?? "light",
132
- port: userConfig.review?.port ?? 3e3
133
- },
134
- connectionTimeout: userConfig.connectionTimeout ?? 2e4
135
- };
136
- (0, _cappa_logger.getLogger)().debug("Configuration loaded:", JSON.stringify(configWithDefaults, null, 2));
137
- return configWithDefaults;
138
- }
139
- //#endregion
140
- //#region src/utils/groupScreenshots.ts
141
- const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScreenshots, outputDir) => {
142
- const screenshotRepresentations = [];
143
- const expectedByRelativePath = /* @__PURE__ */ new Map();
144
- for (const screenshot of expectedScreenshots) {
145
- const relativePath = node_path.default.relative(`${outputDir}/expected`, screenshot);
146
- expectedByRelativePath.set(relativePath, screenshot);
147
- }
148
- const diffByRelativePath = /* @__PURE__ */ new Map();
149
- for (const screenshot of diffScreenshots) {
150
- const relativePath = node_path.default.relative(`${outputDir}/diff`, screenshot);
151
- diffByRelativePath.set(relativePath, screenshot);
152
- }
153
- const actualRelativePaths = /* @__PURE__ */ new Set();
154
- for (const screenshot of actualScreenshots) {
155
- const relativePath = node_path.default.relative(`${outputDir}/actual`, screenshot);
156
- actualRelativePaths.add(relativePath);
157
- const name = relativePath.replace(".png", "");
158
- const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
159
- const expectedScreenshot = expectedByRelativePath.get(relativePath);
160
- const diffScreenshot = diffByRelativePath.get(relativePath);
161
- const diffMeta = diffScreenshot ? await (0, _cappa_core.readDiffMeta)(diffScreenshot) : void 0;
162
- screenshotRepresentations.push({
163
- id,
164
- name,
165
- category: buildCategory(expectedScreenshot, diffScreenshot),
166
- expectedPath: expectedScreenshot ? node_path.default.relative(outputDir, expectedScreenshot) : void 0,
167
- diffPath: diffScreenshot ? node_path.default.relative(outputDir, diffScreenshot) : void 0,
168
- actualPath: node_path.default.relative(outputDir, screenshot),
169
- ...diffMeta ? { diffMeta } : {}
170
- });
171
- }
172
- for (const expectedScreenshot of expectedScreenshots) {
173
- const relativePath = node_path.default.relative(`${outputDir}/expected`, expectedScreenshot);
174
- if (actualRelativePaths.has(relativePath)) continue;
175
- const name = relativePath.replace(".png", "");
176
- const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
177
- screenshotRepresentations.push({
178
- id,
179
- name,
180
- category: "deleted",
181
- expectedPath: node_path.default.relative(outputDir, expectedScreenshot)
182
- });
183
- }
184
- return screenshotRepresentations.sort((a, b) => {
185
- return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
186
- });
187
- };
188
- const buildCategory = (expectedScreenshot, diffScreenshot) => {
189
- if (expectedScreenshot && diffScreenshot) return "changed";
190
- if (expectedScreenshot) return "passed";
191
- return "new";
192
- };
193
- const CATEGORY_ORDER = {
194
- new: 0,
195
- deleted: 1,
196
- changed: 2,
197
- passed: 3
198
- };
39
+ var version = "0.13.0";
199
40
  //#endregion
200
41
  //#region src/commands/approve.ts
201
42
  const approve = async (options) => {
202
43
  const logger = (0, _cappa_logger.getLogger)();
203
- const config = await getConfig();
44
+ const config = await (0, _cappa_config.getConfig)();
204
45
  logger.start("Approving screenshots...");
205
46
  const fileSystem = new _cappa_core.ScreenshotFileSystem(config.outputDir);
206
47
  const [actualScreenshots, diffScreenshots, expectedScreenshots] = await Promise.all([
@@ -208,7 +49,7 @@ const approve = async (options) => {
208
49
  fileSystem.getDiffScreenshots(),
209
50
  fileSystem.getExpectedScreenshots()
210
51
  ]);
211
- let screenshotsToApprove = await groupScreenshots(actualScreenshots, expectedScreenshots, diffScreenshots, config.outputDir);
52
+ let screenshotsToApprove = await (0, _cappa_core.groupScreenshots)(actualScreenshots, expectedScreenshots, diffScreenshots, config.outputDir);
212
53
  const filters = options.filter?.map((filter) => filter.toLowerCase()) ?? [];
213
54
  if (filters.length > 0) {
214
55
  logger.debug(`Filtering actual screenshots by filter: ${filters.join(", ")}`);
@@ -232,23 +73,36 @@ const filterScreenshots = (screenshots, filters) => {
232
73
  });
233
74
  };
234
75
  //#endregion
235
- //#region src/utils/collectScreenshots.ts
236
- const listPngs = async (dir) => Array.fromAsync(await (0, node_fs_promises.glob)(node_path.default.resolve(dir, "**/*.png")));
76
+ //#region src/utils/describeChanges.ts
237
77
  /**
238
- * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and
239
- * group them into the screenshot representations used by the CLI commands
240
- * (including the diff metadata sidecar with the optional interpretation).
78
+ * The interpretation fields this reporter actually reads.
79
+ *
80
+ * The protocol carries `diffMeta.interpretation` opaquely — its shape belongs
81
+ * to `@blazediff/core-native` and pinning it in a versioned wire contract would
82
+ * make every diff-engine upgrade a breaking protocol change. So a remote engine
83
+ * hands this an `unknown`, and it narrows rather than trusts.
84
+ *
85
+ * Deliberately not the full `InterpretResult`: matching only what is rendered
86
+ * means a diff engine that adds or reshapes a field the reporter ignores does
87
+ * not silently cost the user their diff report.
241
88
  */
242
- const collectScreenshots = async (outputDir) => {
243
- const [actualScreenshots, expectedScreenshots, diffScreenshots] = await Promise.all([
244
- listPngs(node_path.default.resolve(outputDir, "actual")),
245
- listPngs(node_path.default.resolve(outputDir, "expected")),
246
- listPngs(node_path.default.resolve(outputDir, "diff"))
247
- ]);
248
- return groupScreenshots(actualScreenshots, expectedScreenshots, diffScreenshots, outputDir);
249
- };
250
- //#endregion
251
- //#region src/utils/describeChanges.ts
89
+ const regionSchema = zod.z.object({
90
+ bbox: zod.z.object({
91
+ x: zod.z.number(),
92
+ y: zod.z.number(),
93
+ width: zod.z.number(),
94
+ height: zod.z.number()
95
+ }),
96
+ percentage: zod.z.number(),
97
+ position: zod.z.string(),
98
+ changeType: zod.z.string()
99
+ });
100
+ const interpretationSchema = zod.z.object({
101
+ severity: zod.z.string(),
102
+ totalRegions: zod.z.number(),
103
+ summary: zod.z.string().optional(),
104
+ regions: zod.z.array(regionSchema).catch([]).optional()
105
+ });
252
106
  const severityColor = (severity) => {
253
107
  switch (severity) {
254
108
  case "High": return chalk.default.red;
@@ -294,10 +148,11 @@ const describeChanges = (screenshots, options = {}) => {
294
148
  const lines = [];
295
149
  for (const screenshot of changed) {
296
150
  const meta = screenshot.diffMeta;
297
- const interpretation = meta?.interpretation;
151
+ const parsed = interpretationSchema.safeParse(meta?.interpretation);
152
+ const interpretation = parsed.success ? parsed.data : void 0;
298
153
  const parts = [];
299
154
  if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
300
- if (meta) parts.push(`${meta.percentDifference.toFixed(2)}%`);
155
+ if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
301
156
  if (interpretation) {
302
157
  const { totalRegions } = interpretation;
303
158
  parts.push(`${totalRegions} ${totalRegions === 1 ? "region" : "regions"}`);
@@ -326,29 +181,170 @@ const parseMaxRegions = (value) => {
326
181
  return Number(value.trim());
327
182
  };
328
183
  //#endregion
329
- //#region src/commands/capture.ts
330
- const isObject = (value) => typeof value === "object" && value !== null;
331
- const didScreenshotFail = (result) => {
332
- if (!isObject(result)) return false;
333
- if ("error" in result && result.error != null) return true;
334
- if ("success" in result) {
335
- const { success } = result;
336
- if (success === false) return true;
184
+ //#region src/utils/remoteEngine.ts
185
+ /** A pre-flight failure, already phrased for the user. */
186
+ var RemoteServerError = class extends Error {
187
+ constructor(message) {
188
+ super(message);
189
+ this.name = "RemoteServerError";
190
+ }
191
+ };
192
+ /**
193
+ * The host already has a run in flight.
194
+ *
195
+ * Duck-typed rather than `instanceof`: `@cappa/client` ships dual ESM/CJS
196
+ * builds, so the CLI can hold a different copy of the class than the one that
197
+ * threw — the same hazard the client documents for its own 404 check.
198
+ */
199
+ const isRunInProgress = (error) => typeof error === "object" && error !== null && error.status === 409;
200
+ const isAuthFailure = (error) => typeof error === "object" && error !== null && error.status === 401;
201
+ const isProtocolMismatch = (error) => error instanceof _cappa_client.ProtocolMismatchError || typeof error === "object" && error !== null && error.name === "ProtocolMismatchError";
202
+ /**
203
+ * Build a remote engine and prove the host is usable before capturing anything.
204
+ *
205
+ * One request to `/api/health` turns four different failures — unreachable
206
+ * host, wrong token, protocol skew, and a host that cannot capture — into four
207
+ * distinct messages, up front. The client performs the version handshake on its
208
+ * first call anyway; doing it here is what makes the failure legible rather
209
+ * than arriving mid-run with half a report already printed.
210
+ */
211
+ async function connectToServer(options) {
212
+ const engine = (0, _cappa_client.createClient)({
213
+ baseUrl: options.server,
214
+ token: options.token
215
+ });
216
+ let health;
217
+ try {
218
+ health = await engine.health();
219
+ } catch (error) {
220
+ await engine.close();
221
+ if (isAuthFailure(error)) throw new RemoteServerError(`${options.server} rejected the access token. Pass --token <token>, or set CAPPA_TOKEN.`);
222
+ if (isProtocolMismatch(error)) throw new RemoteServerError(`${options.server} speaks protocol version ${error.actual}, this CLI expects ${error.expected}. Upgrade whichever is older.`);
223
+ const reason = error instanceof Error ? error.message : String(error);
224
+ throw new RemoteServerError(`Could not reach a cappa server at ${options.server}: ${reason}`);
337
225
  }
338
- if ("filepath" in result) {
339
- const { filepath, skipped } = result;
340
- if (!filepath && skipped !== true) return true;
226
+ if (!health.capabilities.capture) {
227
+ await engine.close();
228
+ throw new RemoteServerError(`${options.server} is running read-only and cannot capture. Restart it without --read-only.`);
229
+ }
230
+ return engine;
231
+ }
232
+ //#endregion
233
+ //#region src/utils/server.ts
234
+ const closeQuietly = async (name, closeable) => {
235
+ try {
236
+ await closeable.close();
237
+ } catch (error) {
238
+ (0, _cappa_logger.getLogger)().debug(`Error closing ${name} during shutdown:`, error);
341
239
  }
342
- return false;
343
240
  };
344
- async function executeOnFailCallback(config, groupedScreenshots) {
241
+ /**
242
+ * Shut a running server down cleanly on Ctrl-C or SIGTERM.
243
+ *
244
+ * Order matters: the HTTP server closes first so no new run can be started
245
+ * mid-teardown, then the engine, which aborts an active run and closes the
246
+ * browser. Without that last step a killed server can leave an orphaned
247
+ * Chromium behind.
248
+ *
249
+ * The second signal exits immediately — if the first shutdown is wedged on a
250
+ * capture that will not stop, the user should not have to reach for `kill -9`.
251
+ */
252
+ function registerShutdownHandlers(server, engine, exitFn = process.exit) {
253
+ let shuttingDown = false;
254
+ const handleSignal = async () => {
255
+ if (shuttingDown) {
256
+ exitFn(130);
257
+ return;
258
+ }
259
+ shuttingDown = true;
260
+ (0, _cappa_logger.getLogger)().info("Shutting down…");
261
+ await closeQuietly("server", server);
262
+ await closeQuietly("engine", engine);
263
+ exitFn(130);
264
+ };
265
+ process.on("SIGINT", handleSignal);
266
+ process.on("SIGTERM", handleSignal);
267
+ return () => {
268
+ process.off("SIGINT", handleSignal);
269
+ process.off("SIGTERM", handleSignal);
270
+ };
271
+ }
272
+ /**
273
+ * Read the access token from the flag, falling back to `CAPPA_TOKEN`.
274
+ *
275
+ * The environment fallback exists so a CI job does not have to put the token in
276
+ * its process list, where anything on the box can read it.
277
+ */
278
+ const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
279
+ /** Wildcard binds: addresses to listen on, never addresses to open. */
280
+ const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
281
+ "0.0.0.0",
282
+ "::",
283
+ "[::]"
284
+ ]);
285
+ /**
286
+ * The host to put in the URL a person is expected to click.
287
+ *
288
+ * A wildcard bind is the common way to expose the UI, and printing it verbatim
289
+ * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
290
+ * handed to a user who then cannot reach their own review UI. `localhost` is
291
+ * reachable on every interface the wildcard covers, so it is the right thing to
292
+ * show; a specific host is printed as given, because that one is meaningful.
293
+ */
294
+ const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDCARD_HOSTS.has(host) ? "localhost" : host;
295
+ /**
296
+ * Build an engine, wrap it in a server, and start listening.
297
+ *
298
+ * Shared by `review` and `serve`, which differ only in how they resolve a token
299
+ * and what they print afterwards — everything from the engine to the bound
300
+ * socket is the same, and was duplicated before `serve` existed.
301
+ *
302
+ * The token is taken as already-resolved: the two commands have deliberately
303
+ * different policies (`review` generates one off loopback for the human reading
304
+ * the URL it prints, `serve` refuses to start without one), and folding that
305
+ * decision in here would hide it.
306
+ */
307
+ async function startServer(options) {
308
+ const logger = (0, _cappa_logger.getLogger)();
309
+ const { config, host, port, readOnly, token, ui } = options;
310
+ const engine = new _cappa_core.LocalEngine({
311
+ ...(0, _cappa_config.configToEngineOptions)(config),
312
+ browserIdleTimeoutMs: config.review.browserIdleTimeout
313
+ });
314
+ const server = await (0, _cappa_server.createServer)({
315
+ engine,
316
+ isProd: true,
317
+ ui,
318
+ outputDir: node_path.default.resolve(config.outputDir),
319
+ logger: logger.level >= 4,
320
+ theme: config.review.theme,
321
+ readOnly,
322
+ token
323
+ });
324
+ const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
325
+ await server.listen({
326
+ port,
327
+ host
328
+ });
329
+ return {
330
+ server,
331
+ engine,
332
+ url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
333
+ unregisterShutdownHandlers
334
+ };
335
+ }
336
+ //#endregion
337
+ //#region src/commands/capture.ts
338
+ async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
345
339
  const logger = (0, _cappa_logger.getLogger)();
346
340
  if (!config.onFail) return;
341
+ if (remote && groupedScreenshots.length > 0) logger.warn("Capturing against a remote server: onFail receives relative paths only, because the screenshot files live on the host rather than this machine.");
342
+ const resolveLocal = (relative) => !remote && relative ? node_path.default.resolve(config.outputDir, relative) : void 0;
347
343
  const failingScreenshots = groupedScreenshots.filter((screenshot) => screenshot.category !== "passed").map((screenshot) => ({
348
344
  ...screenshot,
349
- absoluteActualPath: "actualPath" in screenshot && screenshot.actualPath ? node_path.default.resolve(config.outputDir, screenshot.actualPath) : void 0,
350
- absoluteExpectedPath: "expectedPath" in screenshot && screenshot.expectedPath ? node_path.default.resolve(config.outputDir, screenshot.expectedPath) : void 0,
351
- absoluteDiffPath: "diffPath" in screenshot && screenshot.diffPath ? node_path.default.resolve(config.outputDir, screenshot.diffPath) : void 0
345
+ absoluteActualPath: resolveLocal("actualPath" in screenshot ? screenshot.actualPath : void 0),
346
+ absoluteExpectedPath: resolveLocal("expectedPath" in screenshot ? screenshot.expectedPath : void 0),
347
+ absoluteDiffPath: resolveLocal("diffPath" in screenshot ? screenshot.diffPath : void 0)
352
348
  }));
353
349
  if (failingScreenshots.length > 0) {
354
350
  logger.debug(`Executing onFail callback with ${failingScreenshots.length} failing screenshot(s)`);
@@ -390,8 +386,10 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
390
386
  const errorMsg = typeof result.error === "string" ? result.error : result.error instanceof Error ? result.error.message : String(result.error);
391
387
  lines.push(` ${chalk.default.red("Error:")} ${errorMsg}`);
392
388
  }
393
- if (result.success === false) if (result.isNew) lines.push(` ${chalk.default.yellow("Status:")} New screenshot (no baseline — run 'cappa approve' to accept)`);
394
- else lines.push(` ${chalk.default.red("Status:")} Failed (comparison failed)`);
389
+ if (result.success === false) {
390
+ if (result.isNew) lines.push(` ${chalk.default.yellow("Status:")} New screenshot (no baseline — run 'cappa approve' to accept)`);
391
+ else lines.push(` ${chalk.default.red("Status:")} Failed (comparison failed)`);
392
+ }
395
393
  if (!result.filepath && result.skipped !== true) lines.push(` ${chalk.default.red("Status:")} Failed (no filepath generated)`);
396
394
  }
397
395
  }
@@ -401,133 +399,339 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
401
399
  }
402
400
  return lines.join("\n");
403
401
  }
404
- async function getDeletedScreenshots(outputDir) {
405
- const actualDir = node_path.default.resolve(outputDir, "actual");
406
- const expectedDir = node_path.default.resolve(outputDir, "expected");
407
- const [actualFiles, expectedFiles] = await Promise.all([Array.fromAsync((0, node_fs_promises.glob)(node_path.default.join(actualDir, "**/*.png"))), Array.fromAsync((0, node_fs_promises.glob)(node_path.default.join(expectedDir, "**/*.png")))]);
408
- const actualRelative = new Set(actualFiles.map((p) => node_path.default.relative(actualDir, p)));
409
- return expectedFiles.map((p) => node_path.default.relative(expectedDir, p)).filter((rel) => !actualRelative.has(rel));
410
- }
411
- function filterTasks(tasks, filter) {
412
- return tasks.filter((task) => node_path.default.matchesGlob(task.id, filter));
413
- }
414
- function registerSignalHandlers(screenshotTool, exitFn = process.exit) {
402
+ const supportsWatch = (engine) => typeof engine.startWatch === "function" && typeof engine.stopWatch === "function" && typeof engine.subscribeWatch === "function";
403
+ /**
404
+ * Close `closeable` and exit 130 on SIGINT/SIGTERM.
405
+ *
406
+ * Typed structurally rather than against a concrete class so it can be handed
407
+ * whatever owns the browser — that is the engine now, and a remote engine
408
+ * later, neither of which the CLI should have to special-case here.
409
+ */
410
+ function registerSignalHandlers(closeable, exitFn = process.exit, onSignal) {
411
+ let handling = false;
415
412
  const handleSignal = async () => {
416
- await screenshotTool.close();
413
+ if (handling) {
414
+ (0, _cappa_logger.getLogger)().warn("Interrupted again — exiting now. The remote run may still be going.");
415
+ exitFn(130);
416
+ return;
417
+ }
418
+ handling = true;
419
+ try {
420
+ await onSignal?.();
421
+ await closeable.close();
422
+ } catch (error) {
423
+ (0, _cappa_logger.getLogger)().debug("Error during shutdown:", error);
424
+ }
417
425
  exitFn(130);
418
426
  };
419
- process.once("SIGINT", handleSignal);
420
- process.once("SIGTERM", handleSignal);
427
+ process.on("SIGINT", handleSignal);
428
+ process.on("SIGTERM", handleSignal);
421
429
  return () => {
422
430
  process.off("SIGINT", handleSignal);
423
431
  process.off("SIGTERM", handleSignal);
424
432
  };
425
433
  }
426
- const runCapture = async (options = {}) => {
434
+ /**
435
+ * Render a runner event to the terminal.
436
+ *
437
+ * All terminal presentation lives here — the runner itself is silent — so the
438
+ * server can consume the exact same event stream without inheriting CLI output.
439
+ */
440
+ function renderRunEvent(event) {
427
441
  const logger = (0, _cappa_logger.getLogger)();
428
- const captureStart = performance.now();
429
- const config = await getConfig();
430
- logger.debug(`Cleaning output directory: ${config.outputDir}`);
431
- const fileSystem = new _cappa_core.ScreenshotFileSystem(config.outputDir);
432
- fileSystem.clearActual();
433
- fileSystem.clearDiff();
434
- const screenshotTool = new _cappa_core.ScreenshotTool({
435
- outputDir: config.outputDir,
436
- diff: config.diff,
437
- retries: config.retries,
438
- concurrency: config.concurrency,
439
- logConsoleEvents: config.logConsoleEvents,
440
- fullPage: config.screenshot?.fullPage ?? true,
441
- viewport: config.screenshot?.viewport ?? {
442
- width: 1920,
443
- height: 1080
444
- },
445
- connectionTimeout: config.connectionTimeout
446
- });
447
- const unregisterSignalHandlers = registerSignalHandlers(screenshotTool);
448
- let captureError;
449
- let hasScreenshotFailure = false;
450
- let anyTasksRan = false;
451
- const failedScreenshots = [];
452
- try {
453
- await screenshotTool.init();
454
- const plugins = config.plugins || [];
455
- const pluginTasks = await Promise.all(plugins.map(async (plugin) => {
456
- logger.debug(`Discovering tasks for plugin: ${plugin.name}`);
457
- const tasks = await plugin.discover(screenshotTool);
458
- logger.info(`Found ${tasks.length} tasks for ${plugin.name}`);
459
- return {
460
- plugin,
461
- tasks
462
- };
463
- }));
464
- if (options.filter) {
442
+ switch (event.type) {
443
+ case "log":
444
+ logger[event.level](event.message, ...event.args);
445
+ break;
446
+ case "discover:plugin":
447
+ logger.info(`Found ${event.taskCount} tasks for ${event.plugin}`);
448
+ break;
449
+ case "filter:applied":
450
+ if (event.filter === void 0) break;
465
451
  logger.box({
466
452
  title: "Filter Active",
467
- message: `Only capturing tasks matching: ${chalk.default.cyan(options.filter)}`
453
+ message: `Only capturing tasks matching: ${chalk.default.cyan(event.filter)}`
468
454
  });
469
- for (const entry of pluginTasks) {
470
- const before = entry.tasks.length;
471
- entry.tasks = filterTasks(entry.tasks, options.filter);
472
- logger.info(`${entry.plugin.name}: ${entry.tasks.length}/${before} tasks match filter`);
455
+ for (const entry of event.plugins) logger.info(`${entry.plugin}: ${entry.after}/${entry.before} tasks match filter`);
456
+ break;
457
+ case "task:start":
458
+ logger.debug(`Executing task: ${event.taskId}`);
459
+ break;
460
+ case "task:complete":
461
+ logger.info(formatProgress(event.completed, event.total, event.taskId));
462
+ break;
463
+ case "plugin:complete":
464
+ if (event.failed) logger.error(`Plugin ${event.plugin} completed with failures: ${event.resultCount} results`);
465
+ else logger.success(`Plugin ${event.plugin} completed: ${event.resultCount} results`);
466
+ break;
467
+ case "run:error": logger.error("Error during plugin execution:", event.error.message);
468
+ }
469
+ }
470
+ /**
471
+ * One line for a settled batch of changes.
472
+ *
473
+ * Terse on purpose: this is the inner loop of somebody fixing a regression, and
474
+ * a paragraph per save is noise. It still says *why* the iteration is the size
475
+ * it is, because "3 tasks" and "everything" have very different causes.
476
+ */
477
+ function describeWatchChange(event) {
478
+ const files = event.files.length === 1 ? event.files[0] ?? "" : `${event.files.length} files`;
479
+ const what = (() => {
480
+ switch (event.scope) {
481
+ case "tasks": {
482
+ const count = event.taskIds?.length ?? 0;
483
+ return `${count} task${count === 1 ? "" : "s"}`;
473
484
  }
485
+ case "plugins": return "every task of the affected plugin(s)";
486
+ case "all": return "everything";
487
+ default: return "nothing";
488
+ }
489
+ })();
490
+ return `${chalk.default.cyan("↻")} ${what} · ${files} changed`;
491
+ }
492
+ /** The one-line result of a watch iteration. */
493
+ function summarizeRunDetail(detail, duration) {
494
+ if (!detail) return `Run finished in ${duration}`;
495
+ const failures = detail.failures.length + detail.deletedScreenshots.length;
496
+ const captured = `${detail.completedTasks}/${detail.totalTasks} captured`;
497
+ if (failures > 0) return chalk.default.yellow(`${captured}, ${failures} to review — ${duration}`);
498
+ return chalk.default.green(`${captured}, all passing — ${duration}`);
499
+ }
500
+ /**
501
+ * A watch iteration's run output.
502
+ *
503
+ * Only what changed: a passing task in watch mode is the absence of news, and
504
+ * printing every one of them buries the two lines that matter.
505
+ */
506
+ function renderWatchRunEvent(event) {
507
+ const logger = (0, _cappa_logger.getLogger)();
508
+ switch (event.type) {
509
+ case "log":
510
+ if (event.level === "warn" || event.level === "error") logger[event.level](event.message, ...event.args);
511
+ break;
512
+ case "task:complete":
513
+ if (event.status !== "passed" && event.status !== "skipped") logger.info(` ${chalk.default.dim(event.status)} ${event.taskId}`);
514
+ break;
515
+ case "run:error": logger.error("Error during plugin execution:", event.error.message);
516
+ }
517
+ }
518
+ /**
519
+ * Stop watching and exit 0 on SIGINT/SIGTERM.
520
+ *
521
+ * Zero, not 130: quitting a watch session is how it is meant to end, and a
522
+ * non-zero exit would make `cappa capture --watch` fail every shell script and
523
+ * task runner that wraps it.
524
+ */
525
+ function registerWatchSignalHandlers(stop, exitFn = process.exit) {
526
+ let handling = false;
527
+ const handleSignal = async () => {
528
+ if (handling) {
529
+ exitFn(0);
530
+ return;
531
+ }
532
+ handling = true;
533
+ (0, _cappa_logger.getLogger)().info("Stopping watch…");
534
+ await stop();
535
+ exitFn(0);
536
+ };
537
+ process.on("SIGINT", handleSignal);
538
+ process.on("SIGTERM", handleSignal);
539
+ return () => {
540
+ process.off("SIGINT", handleSignal);
541
+ process.off("SIGTERM", handleSignal);
542
+ };
543
+ }
544
+ /**
545
+ * Watch for changes and re-capture, until interrupted.
546
+ *
547
+ * Resolves only when a signal stops the session, so the caller keeps the
548
+ * process — and the warm browser — alive for as long as the user is editing.
549
+ */
550
+ async function watchCapture(engine, options = {}, exitFn = process.exit) {
551
+ const logger = (0, _cappa_logger.getLogger)();
552
+ let release;
553
+ const finished = new Promise((resolve) => {
554
+ release = resolve;
555
+ });
556
+ const stop = async () => {
557
+ try {
558
+ await engine.stopWatch();
559
+ await engine.close();
560
+ } catch (error) {
561
+ logger.debug("Error stopping the watch session:", error);
562
+ } finally {
563
+ release?.();
474
564
  }
475
- for (const { plugin, tasks } of pluginTasks) {
476
- if (tasks.length === 0) continue;
477
- anyTasksRan = true;
478
- let pluginHasFailure = false;
479
- logger.debug(`Processing ${tasks.length} tasks with concurrency ${screenshotTool.concurrency}`);
480
- let completedTasks = 0;
481
- const pageContexts = /* @__PURE__ */ new Map();
482
- const results = await (0, _cappa_core.mapWithConcurrency)(screenshotTool.concurrency, tasks, async (task, workerIndex) => {
483
- const page = screenshotTool.getPageFromPool(workerIndex);
484
- if (!pageContexts.has(workerIndex) && plugin.initPage) pageContexts.set(workerIndex, await plugin.initPage(page, screenshotTool));
485
- const context = pageContexts.get(workerIndex);
486
- logger.debug(`Executing task: ${task.id}`);
487
- const result = await plugin.execute(task, page, screenshotTool, context);
488
- completedTasks++;
489
- logger.info(formatProgress(completedTasks, tasks.length, task.id));
490
- if (didScreenshotFail(result)) {
491
- pluginHasFailure = true;
492
- hasScreenshotFailure = true;
493
- failedScreenshots.push({
494
- taskId: task.id,
495
- taskUrl: task.url,
496
- result,
497
- pluginName: plugin.name
498
- });
565
+ };
566
+ const unregisterSignalHandlers = registerWatchSignalHandlers(stop, exitFn);
567
+ let rendering = Promise.resolve();
568
+ const unsubscribe = engine.subscribeWatch((event) => {
569
+ switch (event.type) {
570
+ case "watch:start":
571
+ logger.info(`Watching ${event.paths.join(", ")}${event.filter ? ` (filter: ${event.filter})` : ""} — press Ctrl-C to stop.`);
572
+ break;
573
+ case "watch:change": {
574
+ logger.info(describeWatchChange(event));
575
+ if (event.error) {
576
+ logger.warn(`Could not start a run: ${event.error}`);
577
+ break;
499
578
  }
500
- return result;
501
- });
502
- if (pluginHasFailure) logger.error(`Plugin ${plugin.name} completed with failures: ${results.length} results`);
503
- else logger.success(`Plugin ${plugin.name} completed: ${results.length} results`);
579
+ const runId = event.runId;
580
+ if (runId) rendering = rendering.then(() => renderWatchIteration(engine, runId).catch((error) => {
581
+ logger.error("Error rendering the run:", error);
582
+ }));
583
+ break;
584
+ }
504
585
  }
505
- } catch (error) {
506
- logger.error("Error during plugin execution:", error);
507
- captureError = error;
508
- throw error;
586
+ });
587
+ try {
588
+ await engine.startWatch({ filter: options.filter });
589
+ await finished;
509
590
  } finally {
591
+ unsubscribe();
510
592
  unregisterSignalHandlers();
511
- await screenshotTool.close();
512
593
  }
513
- let deletedScreenshots = [];
514
- if (anyTasksRan) try {
515
- deletedScreenshots = await getDeletedScreenshots(config.outputDir);
516
- if (deletedScreenshots.length > 0) hasScreenshotFailure = true;
517
- } catch (err) {
518
- logger.warn("Could not check for deleted screenshots:", err);
594
+ }
595
+ async function renderWatchIteration(engine, runId) {
596
+ const logger = (0, _cappa_logger.getLogger)();
597
+ const start = performance.now();
598
+ await renderRunToCompletion(engine, runId, renderWatchRunEvent);
599
+ const detail = await engine.getRun(runId);
600
+ const duration = formatDuration(performance.now() - start);
601
+ logger.info(summarizeRunDetail(detail, duration));
602
+ }
603
+ /**
604
+ * Rebuild a throwable error from the run's serialized one.
605
+ *
606
+ * The engine flattens the error a plugin threw so it can cross a network
607
+ * boundary, but `capture` has always failed by letting that error escape — the
608
+ * stack is the only debugging signal for a plugin that blew up. Reinstating
609
+ * name, message and stack keeps that output intact.
610
+ */
611
+ function toThrowable(error) {
612
+ const rebuilt = new Error(error.message);
613
+ rebuilt.name = error.name;
614
+ if (error.stack) rebuilt.stack = error.stack;
615
+ return rebuilt;
616
+ }
617
+ /**
618
+ * Subscribe to a run, render every event, and resolve when it terminates.
619
+ *
620
+ * Events buffered between `startRun` and this subscription are replayed
621
+ * synchronously, so nothing emitted during start-up is lost.
622
+ */
623
+ async function renderRunToCompletion(engine, runId, onEvent) {
624
+ let unsubscribe;
625
+ try {
626
+ await new Promise((resolve) => {
627
+ unsubscribe = engine.subscribeRun(runId, (event) => {
628
+ onEvent(event);
629
+ if (event.type === "run:complete" || event.type === "run:error") resolve();
630
+ });
631
+ });
632
+ } finally {
633
+ unsubscribe?.();
634
+ }
635
+ }
636
+ /** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */
637
+ const REMOTE_CANCEL_TIMEOUT_MS = 5e3;
638
+ const runCapture = async (options = {}) => {
639
+ const logger = (0, _cappa_logger.getLogger)();
640
+ const captureStart = performance.now();
641
+ if (options.watch && options.server) {
642
+ logger.error("--watch cannot be combined with --server: a remote host cannot see the files on this machine.");
643
+ process.exit(1);
644
+ return;
645
+ }
646
+ if (options.watch && options.ci) {
647
+ logger.error("--watch cannot be combined with --ci: CI captures once and exits.");
648
+ process.exit(1);
649
+ return;
519
650
  }
651
+ const config = await (0, _cappa_config.getConfig)();
652
+ const remote = options.server !== void 0;
653
+ let engine;
654
+ if (options.token && !options.server) {
655
+ logger.error("--token only applies with --server.");
656
+ process.exit(1);
657
+ return;
658
+ }
659
+ if (options.server) {
660
+ logger.info(`Capturing on ${options.server}, which uses its own cappa.config.ts. Local capture settings do not apply.`);
661
+ try {
662
+ engine = await connectToServer({
663
+ server: options.server,
664
+ token: resolveToken(options.token)
665
+ });
666
+ } catch (error) {
667
+ if (error instanceof RemoteServerError) {
668
+ logger.error(error.message);
669
+ process.exit(1);
670
+ return;
671
+ }
672
+ throw error;
673
+ }
674
+ } else engine = new _cappa_core.LocalEngine({
675
+ ...(0, _cappa_config.configToEngineOptions)(config),
676
+ browserIdleTimeoutMs: options.watch ? config.review?.browserIdleTimeout : 0
677
+ });
520
678
  const isCi = options.ci || process.env.CI === "true";
679
+ let detail;
521
680
  let groupedScreenshots = [];
522
- if (!captureError && (isCi || hasScreenshotFailure)) try {
523
- groupedScreenshots = await collectScreenshots(config.outputDir);
524
- } catch (err) {
525
- logger.warn("Could not collect screenshot results:", err);
681
+ let activeRunId;
682
+ let runCompleted;
683
+ const cancelRemoteRun = async () => {
684
+ if (!remote || !activeRunId) return;
685
+ logger.info("Cancelling the remote run…");
686
+ try {
687
+ await engine.cancelRun(activeRunId);
688
+ await Promise.race([runCompleted?.catch(() => void 0) ?? Promise.resolve(), new Promise((resolve) => {
689
+ setTimeout(resolve, REMOTE_CANCEL_TIMEOUT_MS).unref?.();
690
+ })]);
691
+ } catch (error) {
692
+ logger.debug("Error cancelling the remote run:", error);
693
+ }
694
+ };
695
+ const unregisterSignalHandlers = registerSignalHandlers(engine, process.exit, cancelRemoteRun);
696
+ try {
697
+ let run;
698
+ try {
699
+ run = await engine.startRun({
700
+ filter: options.filter,
701
+ clearActual: true
702
+ });
703
+ } catch (error) {
704
+ if (isRunInProgress(error)) {
705
+ const active = error.activeRunId ? ` (run ${error.activeRunId})` : "";
706
+ logger.error(`${options.server} is already running a capture${active}. Wait for it to finish, or cancel it, and try again.`);
707
+ process.exit(1);
708
+ return;
709
+ }
710
+ throw error;
711
+ }
712
+ activeRunId = run.id;
713
+ runCompleted = renderRunToCompletion(engine, run.id, renderRunEvent);
714
+ await runCompleted;
715
+ detail = await engine.getRun(run.id);
716
+ const failedDuringRun = detail?.error !== void 0;
717
+ const hasFailure = (detail?.failures.length ?? 0) > 0 || (detail?.deletedScreenshots.length ?? 0) > 0;
718
+ if (!failedDuringRun && (isCi || hasFailure)) try {
719
+ groupedScreenshots = await engine.listScreenshots();
720
+ } catch (err) {
721
+ logger.warn("Could not collect screenshot results:", err);
722
+ }
723
+ } finally {
724
+ unregisterSignalHandlers();
725
+ if (!options.watch) await engine.close();
526
726
  }
527
- if (!captureError && isCi) await executeOnFailCallback(config, groupedScreenshots);
727
+ if (detail?.error) throw toThrowable(detail.error);
728
+ const failures = detail?.failures ?? [];
729
+ const deletedScreenshots = detail?.deletedScreenshots ?? [];
730
+ const hasScreenshotFailure = failures.length > 0 || deletedScreenshots.length > 0;
731
+ if (isCi) await executeOnFailCallback(config, groupedScreenshots, { remote });
528
732
  const duration = formatDuration(performance.now() - captureStart);
529
733
  if (hasScreenshotFailure) {
530
- const reportMessage = generateFailureReportMessage(failedScreenshots, deletedScreenshots);
734
+ const reportMessage = generateFailureReportMessage(failures, deletedScreenshots);
531
735
  logger.box({
532
736
  title: "Failed Screenshots",
533
737
  message: reportMessage
@@ -537,33 +741,28 @@ const runCapture = async (options = {}) => {
537
741
  title: "Changed Screenshots",
538
742
  message: changeLines.join("\n")
539
743
  });
540
- logger.error(`One or more screenshots failed in ${duration}. See report above for details.`);
541
- process.exit(1);
744
+ if (options.watch) logger.warn(`One or more screenshots failed in ${duration}.`);
745
+ else {
746
+ logger.error(`One or more screenshots failed in ${duration}. See report above for details.`);
747
+ process.exit(1);
748
+ }
542
749
  } else logger.success(`All plugins completed successfully in ${duration}`);
750
+ if (options.watch) {
751
+ if (!supportsWatch(engine)) {
752
+ logger.error("This engine cannot watch files.");
753
+ await engine.close();
754
+ process.exit(1);
755
+ return;
756
+ }
757
+ await watchCapture(engine, { filter: options.filter });
758
+ }
543
759
  };
544
760
  const registerCaptureCommand = (program) => {
545
- program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).action(async (options) => {
761
+ program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).option("--server <url>", "capture against a `cappa serve` host instead of a local browser").option("--token <token>", "access token for --server (falls back to CAPPA_TOKEN)").option("-w, --watch", "capture once, then re-capture affected tasks whenever files change").action(async (options) => {
546
762
  await runCapture(options);
547
763
  });
548
764
  };
549
765
  //#endregion
550
- //#region src/features/config/default.ts
551
- const defaultConfig = `import { defineConfig } from "@cappa/core";
552
-
553
- export default defineConfig({
554
- outputDir: "./screenshots",
555
- retries: 3,
556
- diff: {
557
- threshold: 0.1,
558
- includeAA: false,
559
- fastBufferCheck: true,
560
- maxDiffPixels: 0,
561
- maxDiffPercentage: 0,
562
- },
563
- plugins: [],
564
- });
565
- `;
566
- //#endregion
567
766
  //#region src/commands/init.ts
568
767
  const init = async () => {
569
768
  const logger = (0, _cappa_logger.getLogger)();
@@ -571,7 +770,7 @@ const init = async () => {
571
770
  const packageJsonPath = node_path.default.resolve(process.cwd(), "package.json");
572
771
  if (node_fs.default.existsSync(configPath)) logger.warn("cappa.config.ts already exists, skipping...");
573
772
  else {
574
- node_fs.default.writeFileSync(configPath, defaultConfig);
773
+ node_fs.default.writeFileSync(configPath, _cappa_config.defaultConfig);
575
774
  logger.success("Created cappa.config.ts");
576
775
  }
577
776
  if (node_fs.default.existsSync(packageJsonPath)) try {
@@ -592,34 +791,73 @@ const init = async () => {
592
791
  };
593
792
  //#endregion
594
793
  //#region src/commands/review.ts
595
- const review = async () => {
794
+ const review = async (options = {}) => {
596
795
  const logger = (0, _cappa_logger.getLogger)();
597
- const config = await getConfig();
598
- const actualScreenshotsPromise = (0, node_fs_promises.glob)(node_path.default.resolve(config.outputDir, "actual", "**/*.png"));
599
- const expectedScreenshotsPromise = (0, node_fs_promises.glob)(node_path.default.resolve(config.outputDir, "expected", "**/*.png"));
600
- const diffScreenshotsPromise = (0, node_fs_promises.glob)(node_path.default.resolve(config.outputDir, "diff", "**/*.png"));
601
- const [actualScreenshots, expectedScreenshots, diffScreenshots] = await Promise.all([
602
- actualScreenshotsPromise,
603
- expectedScreenshotsPromise,
604
- diffScreenshotsPromise
605
- ]);
606
- const groupedScreenshots = await groupScreenshots(await Array.fromAsync(actualScreenshots), await Array.fromAsync(expectedScreenshots), await Array.fromAsync(diffScreenshots), config.outputDir);
607
- const server = await (0, _cappa_server.createServer)({
608
- isProd: true,
609
- outputDir: node_path.default.resolve(config.outputDir),
610
- screenshots: groupedScreenshots,
611
- logger: (0, _cappa_logger.getLogger)().level >= 4,
612
- theme: config.review.theme,
613
- diff: config.diff
796
+ const config = await (0, _cappa_config.getConfig)();
797
+ const host = options.host ?? "127.0.0.1";
798
+ const port = options.port ?? config.review.port;
799
+ const readOnly = options.readOnly ?? false;
800
+ let token = resolveToken(options.token);
801
+ let tokenWasGenerated = false;
802
+ if (!token && !(0, _cappa_server.isLoopbackHost)(host) && !readOnly) {
803
+ token = (0, node_crypto.randomBytes)(24).toString("base64url");
804
+ tokenWasGenerated = true;
805
+ logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
806
+ }
807
+ const { url } = await startServer({
808
+ config,
809
+ host,
810
+ port,
811
+ readOnly,
812
+ token,
813
+ ui: true
814
+ });
815
+ logger.success(`Review UI available at ${url}`);
816
+ if (tokenWasGenerated && logger.level < 3) logger.warn(`Review UI available at ${url}`);
817
+ if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
818
+ };
819
+ //#endregion
820
+ //#region src/commands/serve.ts
821
+ /**
822
+ * Host a capture engine for a remote `cappa capture --server`.
823
+ *
824
+ * `review` minus the assumption that a person is about to open a browser. The
825
+ * one deliberate divergence is the token: `review` generates one off loopback
826
+ * because a human is reading the URL it prints, and `serve` has no such reader —
827
+ * generating one here would produce a daemon nobody can authenticate against.
828
+ * So off loopback it is required, and the command refuses to start without one.
829
+ */
830
+ const serve = async (options = {}) => {
831
+ const logger = (0, _cappa_logger.getLogger)();
832
+ const config = await (0, _cappa_config.getConfig)();
833
+ const host = options.host ?? "127.0.0.1";
834
+ const port = options.port ?? config.review.port;
835
+ const readOnly = options.readOnly ?? false;
836
+ const ui = options.ui ?? true;
837
+ const token = resolveToken(options.token);
838
+ if (!token && !(0, _cappa_server.isLoopbackHost)(host) && !readOnly) {
839
+ logger.error(`Binding to ${host} exposes capture control beyond this machine, so an access token is required. Pass --token <token>, or set CAPPA_TOKEN to keep it out of the process list.`);
840
+ process.exit(1);
841
+ return;
842
+ }
843
+ const { url } = await startServer({
844
+ config,
845
+ host,
846
+ port,
847
+ readOnly,
848
+ token,
849
+ ui
614
850
  });
615
- logger.success(`Review UI available at http://localhost:${config.review.port}`);
616
- await server.listen({ port: config.review.port });
851
+ logger.log(`cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
852
+ if (ui) logger.info(`Review UI available at ${url}`);
853
+ if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
617
854
  };
618
855
  //#endregion
619
856
  //#region src/commands/status.ts
620
857
  const status = async (options = {}) => {
621
858
  const logger = (0, _cappa_logger.getLogger)();
622
- const groupedScreenshots = await collectScreenshots((await getConfig()).outputDir);
859
+ const config = await (0, _cappa_config.getConfig)();
860
+ const groupedScreenshots = await (0, _cappa_core.collectScreenshots)(config.outputDir);
623
861
  logger.debug("All screenshot information:", JSON.stringify(groupedScreenshots, null, 2));
624
862
  logger.box({
625
863
  title: "Screenshot Status",
@@ -644,7 +882,8 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
644
882
  (0, _cappa_logger.initLogger)(logLevel)?.debug(`Log level set to: ${logLevel}`);
645
883
  });
646
884
  registerCaptureCommand(program);
647
- program.command("review").description("Review screenshots").action(review);
885
+ program.command("review").description("Open the review and capture UI").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve the UI without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").action(review);
886
+ program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").option("--no-ui", "serve the API only, without the review UI").action(serve);
648
887
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
649
888
  program.command("status").description("Get status of screenshots").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).action(status);
650
889
  program.command("init").description("Initialize Cappa in the current directory").action(init);