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