@cappa/cli 0.18.0 → 0.20.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,7 +1,7 @@
1
1
  import { getLogger, initLogger } from "@cappa/logger";
2
2
  import { Command, InvalidArgumentError } from "commander";
3
3
  import { configToEngineOptions, defaultConfig, getConfig } from "@cappa/config";
4
- import { LocalEngine, ScreenshotFileSystem, VERDICT_LABELS, clearJudgment, collectScreenshots, groupScreenshots, isVerdictLabel, normalizeChangeType, runAgentCheck, toSlimAgentReport, writeAgentVerdict } from "@cappa/core";
4
+ import { LocalEngine, ScreenshotFileSystem, VERDICT_LABELS, clearJudgment, collectScreenshots, describePixelRatioMismatch, groupScreenshots, isVerdictLabel, normalizeChangeType, removePlaywrightContainers, resolveContainerOptions, runAgentCheck, toSlimAgentReport, writeAgentVerdict } from "@cappa/core";
5
5
  import chalk from "chalk";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -10,9 +10,10 @@ import fsp from "node:fs/promises";
10
10
  import { z } from "zod";
11
11
  import { ProtocolMismatchError, createClient } from "@cappa/client";
12
12
  import { createServer, isLoopbackHost } from "@cappa/server";
13
+ import http from "node:http";
13
14
  import { randomBytes } from "node:crypto";
14
15
  //#region package.json
15
- var version = "0.18.0";
16
+ var version = "0.20.0";
16
17
  //#endregion
17
18
  //#region ../../node_modules/.pnpm/tsdown@0.23.0_@arethetypeswrong+core@0.18.5_oxc-resolver@11.24.2_tsx@4.23.1_typescript@7.0.2/node_modules/tsdown/esm-shims.js
18
19
  const getFilename = () => fileURLToPath(import.meta.url);
@@ -635,6 +636,37 @@ const filterScreenshots = (screenshots, filters) => {
635
636
  });
636
637
  };
637
638
  //#endregion
639
+ //#region src/commands/browser.ts
640
+ /**
641
+ * The container CLI to use: `--cli`, else the config's
642
+ * `playwright({ container: { cli } })`, else `CAPPA_CONTAINER_CLI`, else
643
+ * docker. A config that fails to load must not block cleanup.
644
+ */
645
+ const resolveCli = async (cli) => {
646
+ if (cli) return cli;
647
+ let container;
648
+ try {
649
+ container = (await getConfig()).browser?.provider?.options?.container;
650
+ } catch (error) {
651
+ getLogger().debug("Could not load the config:", error);
652
+ }
653
+ return resolveContainerOptions(container && container !== true ? container : true)?.cli ?? "docker";
654
+ };
655
+ /** `cappa browser down` — remove every Playwright container cappa started. */
656
+ const browserDown = async (options = {}) => {
657
+ const logger = getLogger();
658
+ const cli = await resolveCli(options.cli);
659
+ const removed = await removePlaywrightContainers({ cli });
660
+ if (removed.length === 0) {
661
+ logger.info("No Playwright containers to remove.");
662
+ return;
663
+ }
664
+ for (const name of removed) logger.success(`Removed ${name}`);
665
+ };
666
+ const registerBrowserCommand = (program) => {
667
+ program.command("browser").description("Manage the Playwright container (browser.provider container)").command("down").description("Remove every Playwright container cappa started").option("--cli <cli>", "container CLI to use (docker, podman, nerdctl)").action(browserDown);
668
+ };
669
+ //#endregion
638
670
  //#region src/utils/captureReport.ts
639
671
  const errorMessage = (error) => {
640
672
  if (typeof error === "string") return error;
@@ -799,7 +831,11 @@ const describeChanges = (screenshots, options = {}) => {
799
831
  const meta = screenshot.diffMeta;
800
832
  const parsed = interpretationSchema.safeParse(meta?.interpretation);
801
833
  const interpretation = parsed.success ? parsed.data : void 0;
834
+ const expectedRatio = screenshot.expectedPixelRatio ?? 1;
835
+ const actualRatio = screenshot.actualPixelRatio ?? 1;
836
+ const ratioChanged = expectedRatio !== actualRatio;
802
837
  const parts = [];
838
+ if (ratioChanged) parts.push(chalk.yellow(`${expectedRatio}× → ${actualRatio}×`));
803
839
  if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
804
840
  if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
805
841
  if (interpretation) {
@@ -808,6 +844,7 @@ const describeChanges = (screenshots, options = {}) => {
808
844
  }
809
845
  const suffix = parts.length > 0 ? ` ${chalk.dim("·")} ${parts.join(chalk.dim(" · "))}` : "";
810
846
  lines.push(`${chalk.bold(screenshot.name)}${suffix}`);
847
+ if (ratioChanged) lines.push(` ${chalk.yellow(describePixelRatioMismatch(expectedRatio, actualRatio))}`);
811
848
  if (interpretation?.summary) lines.push(` ${chalk.dim(interpretation.summary)}`);
812
849
  const regions = [...interpretation?.regions ?? []].sort((a, b) => b.percentage - a.percentage);
813
850
  if (maxRegions > 0 && regions.length > 0) {
@@ -879,6 +916,102 @@ async function connectToServer(options) {
879
916
  return engine;
880
917
  }
881
918
  //#endregion
919
+ //#region src/utils/loopback.ts
920
+ const IPV4_LOOPBACK = "127.0.0.1";
921
+ const IPV6_LOOPBACK = "::1";
922
+ /**
923
+ * Binds printed as `localhost`, and the loopback addresses each one leaves
924
+ * uncovered.
925
+ *
926
+ * `localhost` is not one address. Browsers try `::1` and `127.0.0.1` (RFC 6761,
927
+ * happy eyeballs), so a URL saying `localhost:3000` reaches whichever answers
928
+ * first — and if cappa holds only `127.0.0.1:3000` while a dev server holds
929
+ * `[::1]:3000`, the user's click lands in the dev server. The companions are
930
+ * the addresses cappa must also hold for the printed URL to mean cappa.
931
+ *
932
+ * `::` is dual-stack in Node (libuv clears `IPV6_V6ONLY`), so it covers both.
933
+ */
934
+ const LOCALHOST_BINDS = {
935
+ localhost: [IPV6_LOOPBACK],
936
+ [IPV4_LOOPBACK]: [IPV6_LOOPBACK],
937
+ [IPV6_LOOPBACK]: [IPV4_LOOPBACK],
938
+ "[::1]": [IPV4_LOOPBACK],
939
+ "0.0.0.0": [IPV6_LOOPBACK],
940
+ "::": [],
941
+ "[::]": []
942
+ };
943
+ /** Loopback addresses `localhost` may reach that binding `host` does not. */
944
+ const localhostCompanions = (host) => LOCALHOST_BINDS[host] ?? [];
945
+ /**
946
+ * The host to put in the URL a person is expected to click.
947
+ *
948
+ * `localhost` for every bind it reaches — loopback and wildcards, which no
949
+ * browser will open (`http://0.0.0.0:4801` locked users out of their own UI).
950
+ * Anything else is printed as given, with IPv6 literals bracketed. Note
951
+ * `127.0.0.2` is loopback but is *not* `localhost`, which resolves to
952
+ * `127.0.0.1` only.
953
+ */
954
+ const toDisplayHost = (host) => {
955
+ if (host in LOCALHOST_BINDS) return "localhost";
956
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
957
+ };
958
+ /**
959
+ * The address to hand to `listen`.
960
+ *
961
+ * `localhost` becomes `127.0.0.1`: Fastify binds every address `localhost`
962
+ * resolves to but silently drops the ones that fail, so a taken `[::1]:port`
963
+ * would go unnoticed — exactly the conflict the companions exist to catch.
964
+ * Brackets are URL syntax, not something `listen` resolves.
965
+ */
966
+ const toBindHost = (host) => {
967
+ if (host === "localhost") return IPV4_LOOPBACK;
968
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
969
+ };
970
+ /**
971
+ * The loopback family does not exist on this machine — IPv6 disabled, say —
972
+ * so nothing can be listening there and there is nothing to hold.
973
+ */
974
+ const FAMILY_UNAVAILABLE = /* @__PURE__ */ new Set(["EAFNOSUPPORT", "EADDRNOTAVAIL"]);
975
+ /**
976
+ * Listen on `host:port` and hand every request to `target`.
977
+ *
978
+ * What Fastify does itself for its secondary `localhost` addresses, minus the
979
+ * swallowed errors: `EADDRINUSE` is thrown so the caller can move to another
980
+ * port. Resolves to `null` when the address family is unavailable.
981
+ */
982
+ async function bindCompanion(target, host, port) {
983
+ const companion = http.createServer((req, res) => {
984
+ target.emit("request", req, res);
985
+ });
986
+ companion.on("upgrade", (...args) => target.emit("upgrade", ...args));
987
+ companion.timeout = target.timeout;
988
+ companion.keepAliveTimeout = target.keepAliveTimeout;
989
+ companion.requestTimeout = target.requestTimeout;
990
+ companion.headersTimeout = target.headersTimeout;
991
+ try {
992
+ await new Promise((resolve, reject) => {
993
+ companion.once("error", reject);
994
+ companion.listen({
995
+ host,
996
+ port,
997
+ ipv6Only: host.includes(":")
998
+ }, () => {
999
+ companion.off("error", reject);
1000
+ resolve();
1001
+ });
1002
+ });
1003
+ } catch (error) {
1004
+ if (FAMILY_UNAVAILABLE.has(error.code ?? "")) return null;
1005
+ throw error;
1006
+ }
1007
+ return companion;
1008
+ }
1009
+ /** Stop a companion and drop its open connections (SSE streams included). */
1010
+ const closeCompanion = (companion) => {
1011
+ companion.close(() => {});
1012
+ companion.closeAllConnections();
1013
+ };
1014
+ //#endregion
882
1015
  //#region src/utils/server.ts
883
1016
  const closeQuietly = async (name, closeable) => {
884
1017
  try {
@@ -925,22 +1058,100 @@ function registerShutdownHandlers(server, engine, exitFn = process.exit) {
925
1058
  * its process list, where anything on the box can read it.
926
1059
  */
927
1060
  const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
928
- /** Wildcard binds: addresses to listen on, never addresses to open. */
929
- const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
930
- "0.0.0.0",
931
- "::",
932
- "[::]"
933
- ]);
1061
+ /** No port in the range `listenWithFallback` tried was free. */
1062
+ var PortInUseError = class extends Error {
1063
+ constructor(message, options) {
1064
+ super(message, options);
1065
+ this.name = "PortInUseError";
1066
+ }
1067
+ };
1068
+ const isAddressInUse = (error) => error?.code === "EADDRINUSE";
1069
+ /** A bind that failed with `EADDRINUSE`, and where. */
1070
+ var AddressTaken = class extends Error {
1071
+ host;
1072
+ error;
1073
+ constructor(host, error) {
1074
+ super(`${host} is in use`);
1075
+ this.host = host;
1076
+ this.error = error;
1077
+ }
1078
+ };
934
1079
  /**
935
- * The host to put in the URL a person is expected to click.
1080
+ * Listen on `port`, or the next free port above it.
1081
+ *
1082
+ * Retries the real `listen` on `EADDRINUSE` rather than probing first (what
1083
+ * `get-port`/`detect-port` do): a probe frees the port again before the server
1084
+ * binds it, so two cappa processes started together can both "find" the same
1085
+ * port and one of them still crashes. Binding is the only atomic check.
1086
+ *
1087
+ * Companions are bound before the server, because a Fastify instance cannot
1088
+ * listen again once it has been closed: a companion that turns out to be taken
1089
+ * costs nothing to give back, a bound server does.
936
1090
  *
937
- * A wildcard bind is the common way to expose the UI, and printing it verbatim
938
- * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
939
- * handed to a user who then cannot reach their own review UI. `localhost` is
940
- * reachable on every interface the wildcard covers, so it is the right thing to
941
- * show; a specific host is printed as given, because that one is meaningful.
1091
+ * Only `EADDRINUSE` moves on. `EACCES` (a privileged port) or a bad host would
1092
+ * fail identically on every port, so they surface as-is.
1093
+ *
1094
+ * Returns the port actually bound, read back from the server so `port: 0`
1095
+ * (OS-assigned) reports the real number too.
942
1096
  */
943
- const toDisplayHost = (host) => isLoopbackHost(host) || WILDCARD_HOSTS.has(host) ? "localhost" : host;
1097
+ async function listenWithFallback(server, options) {
1098
+ const { host, port, strictPort = false, companions } = options;
1099
+ const attempts = strictPort || port === 0 ? 1 : Math.min(options.maxAttempts ?? 20, 65536 - port);
1100
+ const companionHosts = companions?.hosts ?? [];
1101
+ const bind = async (address, candidate) => {
1102
+ if (!companions) return null;
1103
+ try {
1104
+ return await bindCompanion(companions.target, address, candidate);
1105
+ } catch (error) {
1106
+ throw isAddressInUse(error) ? new AddressTaken(address, error) : error;
1107
+ }
1108
+ };
1109
+ for (let i = 0; i < attempts; i++) {
1110
+ const candidate = port + i;
1111
+ const held = [];
1112
+ try {
1113
+ if (candidate !== 0) for (const address of companionHosts) {
1114
+ const companion = await bind(address, candidate);
1115
+ if (companion) held.push({
1116
+ host: address,
1117
+ server: companion
1118
+ });
1119
+ }
1120
+ try {
1121
+ await server.listen({
1122
+ port: candidate,
1123
+ host
1124
+ });
1125
+ } catch (error) {
1126
+ throw isAddressInUse(error) ? new AddressTaken(host, error) : error;
1127
+ }
1128
+ const bound = server.addresses?.()[0]?.port ?? candidate;
1129
+ if (candidate === 0) for (const address of companionHosts) {
1130
+ const companion = await bind(address, bound).catch(() => null);
1131
+ if (companion) held.push({
1132
+ host: address,
1133
+ server: companion
1134
+ });
1135
+ }
1136
+ if (companions && held.length > 0) companions.target.once("close", () => {
1137
+ for (const companion of held) closeCompanion(companion.server);
1138
+ });
1139
+ return {
1140
+ port: bound,
1141
+ companions: held.map((c) => c.host)
1142
+ };
1143
+ } catch (error) {
1144
+ for (const companion of held) closeCompanion(companion.server);
1145
+ if (!(error instanceof AddressTaken)) throw error;
1146
+ options.onPortInUse?.(candidate, error.host);
1147
+ if (i === attempts - 1) {
1148
+ const where = attempts === 1 ? error.host : host;
1149
+ throw new PortInUseError(`${attempts === 1 ? `Port ${port}` : `Ports ${port}–${candidate}`} on ${where} ${attempts === 1 ? "is" : "are all"} in use. ${strictPort ? "Drop --strict-port to use the next free one, or pass --port <port>." : "Pass --port <port> to pick another."}`, { cause: error.error });
1150
+ }
1151
+ }
1152
+ }
1153
+ throw new Error(`Could not listen on ${host}:${port}.`);
1154
+ }
944
1155
  /**
945
1156
  * Build an engine, wrap it in a server, and start listening.
946
1157
  *
@@ -955,7 +1166,7 @@ const toDisplayHost = (host) => isLoopbackHost(host) || WILDCARD_HOSTS.has(host)
955
1166
  */
956
1167
  async function startServer(options) {
957
1168
  const logger = getLogger();
958
- const { config, host, port, readOnly, token, ui } = options;
1169
+ const { config, host, port, readOnly, token, ui, strictPort } = options;
959
1170
  const engine = new LocalEngine({
960
1171
  ...configToEngineOptions(config),
961
1172
  browserIdleTimeoutMs: config.review.browserIdleTimeout
@@ -971,17 +1182,50 @@ async function startServer(options) {
971
1182
  token
972
1183
  });
973
1184
  const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
974
- await server.listen({
975
- port,
976
- host
977
- });
1185
+ let boundPort;
1186
+ try {
1187
+ ({port: boundPort} = await listenWithFallback(server, {
1188
+ host: toBindHost(host),
1189
+ port,
1190
+ strictPort,
1191
+ onPortInUse: (taken, on) => logger.debug(`Port ${taken} is in use on ${on}.`),
1192
+ companions: server.server && {
1193
+ hosts: localhostCompanions(host),
1194
+ target: server.server
1195
+ }
1196
+ }));
1197
+ } catch (error) {
1198
+ unregisterShutdownHandlers();
1199
+ await closeQuietly("server", server);
1200
+ await closeQuietly("engine", engine);
1201
+ throw error;
1202
+ }
1203
+ if (boundPort !== port && port !== 0) logger.warn(`Port ${port} is in use, using ${boundPort} instead.`);
1204
+ const displayHost = toDisplayHost(host);
1205
+ const query = token ? `?token=${token}` : "";
978
1206
  return {
979
1207
  server,
980
1208
  engine,
981
- url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
1209
+ port: boundPort,
1210
+ url: `http://${displayHost}:${boundPort}${query}`,
982
1211
  unregisterShutdownHandlers
983
1212
  };
984
1213
  }
1214
+ /**
1215
+ * `startServer` for a CLI command: a taken port is a one-line error and exit
1216
+ * code 1, not a stack trace. Anything else is a bug and keeps its stack.
1217
+ */
1218
+ async function startServerOrExit(options, exitFn = process.exit) {
1219
+ try {
1220
+ return await startServer(options);
1221
+ } catch (error) {
1222
+ if (error instanceof PortInUseError) {
1223
+ getLogger().error(error.message);
1224
+ exitFn(1);
1225
+ }
1226
+ throw error;
1227
+ }
1228
+ }
985
1229
  //#endregion
986
1230
  //#region src/commands/capture.ts
987
1231
  async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
@@ -1503,12 +1747,13 @@ const review = async (options = {}) => {
1503
1747
  tokenWasGenerated = true;
1504
1748
  logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
1505
1749
  }
1506
- const { url } = await startServer({
1750
+ const { url } = await startServerOrExit({
1507
1751
  config,
1508
1752
  host,
1509
1753
  port,
1510
1754
  readOnly,
1511
1755
  token,
1756
+ strictPort: options.strictPort ?? false,
1512
1757
  ui: true
1513
1758
  });
1514
1759
  logger.success(`Review UI available at ${url}`);
@@ -1539,15 +1784,16 @@ const serve = async (options = {}) => {
1539
1784
  process.exit(1);
1540
1785
  return;
1541
1786
  }
1542
- const { url } = await startServer({
1787
+ const { url, port: boundPort } = await startServerOrExit({
1543
1788
  config,
1544
1789
  host,
1545
1790
  port,
1546
1791
  readOnly,
1547
1792
  token,
1793
+ strictPort: options.strictPort ?? false,
1548
1794
  ui
1549
1795
  });
1550
- logger.log(`cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1796
+ logger.log(`cappa serve listening host=${host} port=${boundPort} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1551
1797
  if (ui) logger.info(`Review UI available at ${url}`);
1552
1798
  if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
1553
1799
  };
@@ -1581,11 +1827,12 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
1581
1827
  initLogger(logLevel)?.debug(`Log level set to: ${logLevel}`);
1582
1828
  });
1583
1829
  registerCaptureCommand(program);
1584
- 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);
1585
- 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);
1830
+ program.command("review").description("Open the review and capture UI").option("-p, --port <port>", "port to listen on (the next free one if it is taken)", (v) => Number.parseInt(v, 10)).option("--strict-port", "exit if the port is taken instead of moving on").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);
1831
+ program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on (the next free one if it is taken)", (v) => Number.parseInt(v, 10)).option("--strict-port", "exit if the port is taken instead of moving on").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);
1586
1832
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
1587
1833
  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);
1588
1834
  registerAgentCommand(program);
1835
+ registerBrowserCommand(program);
1589
1836
  program.command("init").description("Initialize Cappa in the current directory").action(init);
1590
1837
  async function run() {
1591
1838
  await program.parseAsync();