@cappa/cli 0.19.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, removePlaywrightContainers, resolveContainerOptions, 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.19.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);
@@ -830,7 +831,11 @@ const describeChanges = (screenshots, options = {}) => {
830
831
  const meta = screenshot.diffMeta;
831
832
  const parsed = interpretationSchema.safeParse(meta?.interpretation);
832
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;
833
837
  const parts = [];
838
+ if (ratioChanged) parts.push(chalk.yellow(`${expectedRatio}× → ${actualRatio}×`));
834
839
  if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
835
840
  if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
836
841
  if (interpretation) {
@@ -839,6 +844,7 @@ const describeChanges = (screenshots, options = {}) => {
839
844
  }
840
845
  const suffix = parts.length > 0 ? ` ${chalk.dim("·")} ${parts.join(chalk.dim(" · "))}` : "";
841
846
  lines.push(`${chalk.bold(screenshot.name)}${suffix}`);
847
+ if (ratioChanged) lines.push(` ${chalk.yellow(describePixelRatioMismatch(expectedRatio, actualRatio))}`);
842
848
  if (interpretation?.summary) lines.push(` ${chalk.dim(interpretation.summary)}`);
843
849
  const regions = [...interpretation?.regions ?? []].sort((a, b) => b.percentage - a.percentage);
844
850
  if (maxRegions > 0 && regions.length > 0) {
@@ -910,6 +916,102 @@ async function connectToServer(options) {
910
916
  return engine;
911
917
  }
912
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
913
1015
  //#region src/utils/server.ts
914
1016
  const closeQuietly = async (name, closeable) => {
915
1017
  try {
@@ -956,22 +1058,100 @@ function registerShutdownHandlers(server, engine, exitFn = process.exit) {
956
1058
  * its process list, where anything on the box can read it.
957
1059
  */
958
1060
  const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
959
- /** Wildcard binds: addresses to listen on, never addresses to open. */
960
- const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
961
- "0.0.0.0",
962
- "::",
963
- "[::]"
964
- ]);
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
+ };
965
1079
  /**
966
- * The host to put in the URL a person is expected to click.
1080
+ * Listen on `port`, or the next free port above it.
967
1081
  *
968
- * A wildcard bind is the common way to expose the UI, and printing it verbatim
969
- * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
970
- * handed to a user who then cannot reach their own review UI. `localhost` is
971
- * reachable on every interface the wildcard covers, so it is the right thing to
972
- * show; a specific host is printed as given, because that one is meaningful.
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.
1090
+ *
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.
973
1096
  */
974
- 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
+ }
975
1155
  /**
976
1156
  * Build an engine, wrap it in a server, and start listening.
977
1157
  *
@@ -986,7 +1166,7 @@ const toDisplayHost = (host) => isLoopbackHost(host) || WILDCARD_HOSTS.has(host)
986
1166
  */
987
1167
  async function startServer(options) {
988
1168
  const logger = getLogger();
989
- const { config, host, port, readOnly, token, ui } = options;
1169
+ const { config, host, port, readOnly, token, ui, strictPort } = options;
990
1170
  const engine = new LocalEngine({
991
1171
  ...configToEngineOptions(config),
992
1172
  browserIdleTimeoutMs: config.review.browserIdleTimeout
@@ -1002,17 +1182,50 @@ async function startServer(options) {
1002
1182
  token
1003
1183
  });
1004
1184
  const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
1005
- await server.listen({
1006
- port,
1007
- host
1008
- });
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}` : "";
1009
1206
  return {
1010
1207
  server,
1011
1208
  engine,
1012
- url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
1209
+ port: boundPort,
1210
+ url: `http://${displayHost}:${boundPort}${query}`,
1013
1211
  unregisterShutdownHandlers
1014
1212
  };
1015
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
+ }
1016
1229
  //#endregion
1017
1230
  //#region src/commands/capture.ts
1018
1231
  async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
@@ -1534,12 +1747,13 @@ const review = async (options = {}) => {
1534
1747
  tokenWasGenerated = true;
1535
1748
  logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
1536
1749
  }
1537
- const { url } = await startServer({
1750
+ const { url } = await startServerOrExit({
1538
1751
  config,
1539
1752
  host,
1540
1753
  port,
1541
1754
  readOnly,
1542
1755
  token,
1756
+ strictPort: options.strictPort ?? false,
1543
1757
  ui: true
1544
1758
  });
1545
1759
  logger.success(`Review UI available at ${url}`);
@@ -1570,15 +1784,16 @@ const serve = async (options = {}) => {
1570
1784
  process.exit(1);
1571
1785
  return;
1572
1786
  }
1573
- const { url } = await startServer({
1787
+ const { url, port: boundPort } = await startServerOrExit({
1574
1788
  config,
1575
1789
  host,
1576
1790
  port,
1577
1791
  readOnly,
1578
1792
  token,
1793
+ strictPort: options.strictPort ?? false,
1579
1794
  ui
1580
1795
  });
1581
- 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"}`);
1582
1797
  if (ui) logger.info(`Review UI available at ${url}`);
1583
1798
  if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
1584
1799
  };
@@ -1612,8 +1827,8 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
1612
1827
  initLogger(logLevel)?.debug(`Log level set to: ${logLevel}`);
1613
1828
  });
1614
1829
  registerCaptureCommand(program);
1615
- 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);
1616
- 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);
1617
1832
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
1618
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);
1619
1834
  registerAgentCommand(program);