@cappa/cli 0.12.0 → 0.13.1
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 +588 -349
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -2
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +584 -345
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -12
package/dist/index.mjs
CHANGED
|
@@ -1,175 +1,16 @@
|
|
|
1
1
|
import { getLogger, initLogger } from "@cappa/logger";
|
|
2
2
|
import { Command, InvalidArgumentError } from "commander";
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
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 {
|
|
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.
|
|
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.1";
|
|
173
14
|
//#endregion
|
|
174
15
|
//#region src/commands/approve.ts
|
|
175
16
|
const approve = async (options) => {
|
|
@@ -206,23 +47,36 @@ const filterScreenshots = (screenshots, filters) => {
|
|
|
206
47
|
});
|
|
207
48
|
};
|
|
208
49
|
//#endregion
|
|
209
|
-
//#region src/utils/
|
|
210
|
-
const listPngs = async (dir) => Array.fromAsync(await glob(path.resolve(dir, "**/*.png")));
|
|
50
|
+
//#region src/utils/describeChanges.ts
|
|
211
51
|
/**
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
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.
|
|
215
62
|
*/
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
+
});
|
|
226
80
|
const severityColor = (severity) => {
|
|
227
81
|
switch (severity) {
|
|
228
82
|
case "High": return chalk.red;
|
|
@@ -268,10 +122,11 @@ const describeChanges = (screenshots, options = {}) => {
|
|
|
268
122
|
const lines = [];
|
|
269
123
|
for (const screenshot of changed) {
|
|
270
124
|
const meta = screenshot.diffMeta;
|
|
271
|
-
const
|
|
125
|
+
const parsed = interpretationSchema.safeParse(meta?.interpretation);
|
|
126
|
+
const interpretation = parsed.success ? parsed.data : void 0;
|
|
272
127
|
const parts = [];
|
|
273
128
|
if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
|
|
274
|
-
if (meta) parts.push(`${meta.percentDifference.toFixed(2)}%`);
|
|
129
|
+
if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
|
|
275
130
|
if (interpretation) {
|
|
276
131
|
const { totalRegions } = interpretation;
|
|
277
132
|
parts.push(`${totalRegions} ${totalRegions === 1 ? "region" : "regions"}`);
|
|
@@ -300,29 +155,170 @@ const parseMaxRegions = (value) => {
|
|
|
300
155
|
return Number(value.trim());
|
|
301
156
|
};
|
|
302
157
|
//#endregion
|
|
303
|
-
//#region src/
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const { success } = result;
|
|
310
|
-
if (success === false) return true;
|
|
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";
|
|
311
164
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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);
|
|
315
213
|
}
|
|
316
|
-
return false;
|
|
317
214
|
};
|
|
318
|
-
|
|
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 } = {}) {
|
|
319
313
|
const logger = getLogger();
|
|
320
314
|
if (!config.onFail) return;
|
|
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;
|
|
321
317
|
const failingScreenshots = groupedScreenshots.filter((screenshot) => screenshot.category !== "passed").map((screenshot) => ({
|
|
322
318
|
...screenshot,
|
|
323
|
-
absoluteActualPath: "actualPath" in screenshot
|
|
324
|
-
absoluteExpectedPath: "expectedPath" in screenshot
|
|
325
|
-
absoluteDiffPath: "diffPath" in screenshot
|
|
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)
|
|
326
322
|
}));
|
|
327
323
|
if (failingScreenshots.length > 0) {
|
|
328
324
|
logger.debug(`Executing onFail callback with ${failingScreenshots.length} failing screenshot(s)`);
|
|
@@ -364,8 +360,10 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
|
|
|
364
360
|
const errorMsg = typeof result.error === "string" ? result.error : result.error instanceof Error ? result.error.message : String(result.error);
|
|
365
361
|
lines.push(` ${chalk.red("Error:")} ${errorMsg}`);
|
|
366
362
|
}
|
|
367
|
-
if (result.success === false)
|
|
368
|
-
|
|
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
|
+
}
|
|
369
367
|
if (!result.filepath && result.skipped !== true) lines.push(` ${chalk.red("Status:")} Failed (no filepath generated)`);
|
|
370
368
|
}
|
|
371
369
|
}
|
|
@@ -375,133 +373,339 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
|
|
|
375
373
|
}
|
|
376
374
|
return lines.join("\n");
|
|
377
375
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
function registerSignalHandlers(screenshotTool, exitFn = process.exit) {
|
|
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;
|
|
389
386
|
const handleSignal = async () => {
|
|
390
|
-
|
|
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
|
+
}
|
|
391
399
|
exitFn(130);
|
|
392
400
|
};
|
|
393
|
-
process.
|
|
394
|
-
process.
|
|
401
|
+
process.on("SIGINT", handleSignal);
|
|
402
|
+
process.on("SIGTERM", handleSignal);
|
|
395
403
|
return () => {
|
|
396
404
|
process.off("SIGINT", handleSignal);
|
|
397
405
|
process.off("SIGTERM", handleSignal);
|
|
398
406
|
};
|
|
399
407
|
}
|
|
400
|
-
|
|
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) {
|
|
401
415
|
const logger = getLogger();
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
retries: config.retries,
|
|
412
|
-
concurrency: config.concurrency,
|
|
413
|
-
logConsoleEvents: config.logConsoleEvents,
|
|
414
|
-
fullPage: config.screenshot?.fullPage ?? true,
|
|
415
|
-
viewport: config.screenshot?.viewport ?? {
|
|
416
|
-
width: 1920,
|
|
417
|
-
height: 1080
|
|
418
|
-
},
|
|
419
|
-
connectionTimeout: config.connectionTimeout
|
|
420
|
-
});
|
|
421
|
-
const unregisterSignalHandlers = registerSignalHandlers(screenshotTool);
|
|
422
|
-
let captureError;
|
|
423
|
-
let hasScreenshotFailure = false;
|
|
424
|
-
let anyTasksRan = false;
|
|
425
|
-
const failedScreenshots = [];
|
|
426
|
-
try {
|
|
427
|
-
await screenshotTool.init();
|
|
428
|
-
const plugins = config.plugins || [];
|
|
429
|
-
const pluginTasks = await Promise.all(plugins.map(async (plugin) => {
|
|
430
|
-
logger.debug(`Discovering tasks for plugin: ${plugin.name}`);
|
|
431
|
-
const tasks = await plugin.discover(screenshotTool);
|
|
432
|
-
logger.info(`Found ${tasks.length} tasks for ${plugin.name}`);
|
|
433
|
-
return {
|
|
434
|
-
plugin,
|
|
435
|
-
tasks
|
|
436
|
-
};
|
|
437
|
-
}));
|
|
438
|
-
if (options.filter) {
|
|
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;
|
|
439
425
|
logger.box({
|
|
440
426
|
title: "Filter Active",
|
|
441
|
-
message: `Only capturing tasks matching: ${chalk.cyan(
|
|
427
|
+
message: `Only capturing tasks matching: ${chalk.cyan(event.filter)}`
|
|
442
428
|
});
|
|
443
|
-
for (const entry of
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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"}`;
|
|
447
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}`);
|
|
473
|
+
}
|
|
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
|
+
}
|
|
491
|
+
}
|
|
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;
|
|
501
|
+
const handleSignal = async () => {
|
|
502
|
+
if (handling) {
|
|
503
|
+
exitFn(0);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
handling = true;
|
|
507
|
+
getLogger().info("Stopping watch…");
|
|
508
|
+
await stop();
|
|
509
|
+
exitFn(0);
|
|
510
|
+
};
|
|
511
|
+
process.on("SIGINT", handleSignal);
|
|
512
|
+
process.on("SIGTERM", handleSignal);
|
|
513
|
+
return () => {
|
|
514
|
+
process.off("SIGINT", handleSignal);
|
|
515
|
+
process.off("SIGTERM", handleSignal);
|
|
516
|
+
};
|
|
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?.();
|
|
448
538
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
completedTasks++;
|
|
463
|
-
logger.info(formatProgress(completedTasks, tasks.length, task.id));
|
|
464
|
-
if (didScreenshotFail(result)) {
|
|
465
|
-
pluginHasFailure = true;
|
|
466
|
-
hasScreenshotFailure = true;
|
|
467
|
-
failedScreenshots.push({
|
|
468
|
-
taskId: task.id,
|
|
469
|
-
taskUrl: task.url,
|
|
470
|
-
result,
|
|
471
|
-
pluginName: plugin.name
|
|
472
|
-
});
|
|
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;
|
|
473
552
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
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
|
+
}
|
|
478
559
|
}
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
560
|
+
});
|
|
561
|
+
try {
|
|
562
|
+
await engine.startWatch({ filter: options.filter });
|
|
563
|
+
await finished;
|
|
483
564
|
} finally {
|
|
565
|
+
unsubscribe();
|
|
484
566
|
unregisterSignalHandlers();
|
|
485
|
-
await screenshotTool.close();
|
|
486
567
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
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?.();
|
|
493
608
|
}
|
|
609
|
+
}
|
|
610
|
+
/** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */
|
|
611
|
+
const REMOTE_CANCEL_TIMEOUT_MS = 5e3;
|
|
612
|
+
const runCapture = async (options = {}) => {
|
|
613
|
+
const logger = getLogger();
|
|
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
|
+
}
|
|
625
|
+
const config = await getConfig();
|
|
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
|
|
651
|
+
});
|
|
494
652
|
const isCi = options.ci || process.env.CI === "true";
|
|
653
|
+
let detail;
|
|
495
654
|
let groupedScreenshots = [];
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
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);
|
|
670
|
+
try {
|
|
671
|
+
let run;
|
|
672
|
+
try {
|
|
673
|
+
run = await engine.startRun({
|
|
674
|
+
filter: options.filter,
|
|
675
|
+
clearActual: true
|
|
676
|
+
});
|
|
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;
|
|
683
|
+
}
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
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);
|
|
696
|
+
}
|
|
697
|
+
} finally {
|
|
698
|
+
unregisterSignalHandlers();
|
|
699
|
+
if (!options.watch) await engine.close();
|
|
500
700
|
}
|
|
501
|
-
if (
|
|
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 });
|
|
502
706
|
const duration = formatDuration(performance.now() - captureStart);
|
|
503
707
|
if (hasScreenshotFailure) {
|
|
504
|
-
const reportMessage = generateFailureReportMessage(
|
|
708
|
+
const reportMessage = generateFailureReportMessage(failures, deletedScreenshots);
|
|
505
709
|
logger.box({
|
|
506
710
|
title: "Failed Screenshots",
|
|
507
711
|
message: reportMessage
|
|
@@ -511,33 +715,28 @@ const runCapture = async (options = {}) => {
|
|
|
511
715
|
title: "Changed Screenshots",
|
|
512
716
|
message: changeLines.join("\n")
|
|
513
717
|
});
|
|
514
|
-
logger.
|
|
515
|
-
|
|
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
|
+
}
|
|
516
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
|
+
}
|
|
517
733
|
};
|
|
518
734
|
const registerCaptureCommand = (program) => {
|
|
519
|
-
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) => {
|
|
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) => {
|
|
520
736
|
await runCapture(options);
|
|
521
737
|
});
|
|
522
738
|
};
|
|
523
739
|
//#endregion
|
|
524
|
-
//#region src/features/config/default.ts
|
|
525
|
-
const defaultConfig = `import { defineConfig } from "@cappa/core";
|
|
526
|
-
|
|
527
|
-
export default defineConfig({
|
|
528
|
-
outputDir: "./screenshots",
|
|
529
|
-
retries: 3,
|
|
530
|
-
diff: {
|
|
531
|
-
threshold: 0.1,
|
|
532
|
-
includeAA: false,
|
|
533
|
-
fastBufferCheck: true,
|
|
534
|
-
maxDiffPixels: 0,
|
|
535
|
-
maxDiffPercentage: 0,
|
|
536
|
-
},
|
|
537
|
-
plugins: [],
|
|
538
|
-
});
|
|
539
|
-
`;
|
|
540
|
-
//#endregion
|
|
541
740
|
//#region src/commands/init.ts
|
|
542
741
|
const init = async () => {
|
|
543
742
|
const logger = getLogger();
|
|
@@ -566,34 +765,73 @@ const init = async () => {
|
|
|
566
765
|
};
|
|
567
766
|
//#endregion
|
|
568
767
|
//#region src/commands/review.ts
|
|
569
|
-
const review = async () => {
|
|
768
|
+
const review = async (options = {}) => {
|
|
570
769
|
const logger = getLogger();
|
|
571
770
|
const config = await getConfig();
|
|
572
|
-
const
|
|
573
|
-
const
|
|
574
|
-
const
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
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
|
|
588
788
|
});
|
|
589
|
-
logger.success(`Review UI available at
|
|
590
|
-
|
|
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.");
|
|
792
|
+
};
|
|
793
|
+
//#endregion
|
|
794
|
+
//#region src/commands/serve.ts
|
|
795
|
+
/**
|
|
796
|
+
* Host a capture engine for a remote `cappa capture --server`.
|
|
797
|
+
*
|
|
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.
|
|
803
|
+
*/
|
|
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;
|
|
816
|
+
}
|
|
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.");
|
|
591
828
|
};
|
|
592
829
|
//#endregion
|
|
593
830
|
//#region src/commands/status.ts
|
|
594
831
|
const status = async (options = {}) => {
|
|
595
832
|
const logger = getLogger();
|
|
596
|
-
const
|
|
833
|
+
const config = await getConfig();
|
|
834
|
+
const groupedScreenshots = await collectScreenshots(config.outputDir);
|
|
597
835
|
logger.debug("All screenshot information:", JSON.stringify(groupedScreenshots, null, 2));
|
|
598
836
|
logger.box({
|
|
599
837
|
title: "Screenshot Status",
|
|
@@ -618,7 +856,8 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
|
|
|
618
856
|
initLogger(logLevel)?.debug(`Log level set to: ${logLevel}`);
|
|
619
857
|
});
|
|
620
858
|
registerCaptureCommand(program);
|
|
621
|
-
program.command("review").description("
|
|
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);
|
|
622
861
|
program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
|
|
623
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);
|
|
624
863
|
program.command("init").description("Initialize Cappa in the current directory").action(init);
|