@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.cjs CHANGED
@@ -36,9 +36,11 @@ node_path = __toESM(node_path);
36
36
  let zod = require("zod");
37
37
  let _cappa_client = require("@cappa/client");
38
38
  let _cappa_server = require("@cappa/server");
39
+ let node_http = require("node:http");
40
+ node_http = __toESM(node_http);
39
41
  let node_crypto = require("node:crypto");
40
42
  //#region package.json
41
- var version = "0.19.0";
43
+ var version = "0.20.0";
42
44
  //#endregion
43
45
  //#region src/utils/agentSkills.ts
44
46
  /**
@@ -851,7 +853,11 @@ const describeChanges = (screenshots, options = {}) => {
851
853
  const meta = screenshot.diffMeta;
852
854
  const parsed = interpretationSchema.safeParse(meta?.interpretation);
853
855
  const interpretation = parsed.success ? parsed.data : void 0;
856
+ const expectedRatio = screenshot.expectedPixelRatio ?? 1;
857
+ const actualRatio = screenshot.actualPixelRatio ?? 1;
858
+ const ratioChanged = expectedRatio !== actualRatio;
854
859
  const parts = [];
860
+ if (ratioChanged) parts.push(chalk.default.yellow(`${expectedRatio}× → ${actualRatio}×`));
855
861
  if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
856
862
  if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
857
863
  if (interpretation) {
@@ -860,6 +866,7 @@ const describeChanges = (screenshots, options = {}) => {
860
866
  }
861
867
  const suffix = parts.length > 0 ? ` ${chalk.default.dim("·")} ${parts.join(chalk.default.dim(" · "))}` : "";
862
868
  lines.push(`${chalk.default.bold(screenshot.name)}${suffix}`);
869
+ if (ratioChanged) lines.push(` ${chalk.default.yellow((0, _cappa_core.describePixelRatioMismatch)(expectedRatio, actualRatio))}`);
863
870
  if (interpretation?.summary) lines.push(` ${chalk.default.dim(interpretation.summary)}`);
864
871
  const regions = [...interpretation?.regions ?? []].sort((a, b) => b.percentage - a.percentage);
865
872
  if (maxRegions > 0 && regions.length > 0) {
@@ -931,6 +938,102 @@ async function connectToServer(options) {
931
938
  return engine;
932
939
  }
933
940
  //#endregion
941
+ //#region src/utils/loopback.ts
942
+ const IPV4_LOOPBACK = "127.0.0.1";
943
+ const IPV6_LOOPBACK = "::1";
944
+ /**
945
+ * Binds printed as `localhost`, and the loopback addresses each one leaves
946
+ * uncovered.
947
+ *
948
+ * `localhost` is not one address. Browsers try `::1` and `127.0.0.1` (RFC 6761,
949
+ * happy eyeballs), so a URL saying `localhost:3000` reaches whichever answers
950
+ * first — and if cappa holds only `127.0.0.1:3000` while a dev server holds
951
+ * `[::1]:3000`, the user's click lands in the dev server. The companions are
952
+ * the addresses cappa must also hold for the printed URL to mean cappa.
953
+ *
954
+ * `::` is dual-stack in Node (libuv clears `IPV6_V6ONLY`), so it covers both.
955
+ */
956
+ const LOCALHOST_BINDS = {
957
+ localhost: [IPV6_LOOPBACK],
958
+ [IPV4_LOOPBACK]: [IPV6_LOOPBACK],
959
+ [IPV6_LOOPBACK]: [IPV4_LOOPBACK],
960
+ "[::1]": [IPV4_LOOPBACK],
961
+ "0.0.0.0": [IPV6_LOOPBACK],
962
+ "::": [],
963
+ "[::]": []
964
+ };
965
+ /** Loopback addresses `localhost` may reach that binding `host` does not. */
966
+ const localhostCompanions = (host) => LOCALHOST_BINDS[host] ?? [];
967
+ /**
968
+ * The host to put in the URL a person is expected to click.
969
+ *
970
+ * `localhost` for every bind it reaches — loopback and wildcards, which no
971
+ * browser will open (`http://0.0.0.0:4801` locked users out of their own UI).
972
+ * Anything else is printed as given, with IPv6 literals bracketed. Note
973
+ * `127.0.0.2` is loopback but is *not* `localhost`, which resolves to
974
+ * `127.0.0.1` only.
975
+ */
976
+ const toDisplayHost = (host) => {
977
+ if (host in LOCALHOST_BINDS) return "localhost";
978
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
979
+ };
980
+ /**
981
+ * The address to hand to `listen`.
982
+ *
983
+ * `localhost` becomes `127.0.0.1`: Fastify binds every address `localhost`
984
+ * resolves to but silently drops the ones that fail, so a taken `[::1]:port`
985
+ * would go unnoticed — exactly the conflict the companions exist to catch.
986
+ * Brackets are URL syntax, not something `listen` resolves.
987
+ */
988
+ const toBindHost = (host) => {
989
+ if (host === "localhost") return IPV4_LOOPBACK;
990
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
991
+ };
992
+ /**
993
+ * The loopback family does not exist on this machine — IPv6 disabled, say —
994
+ * so nothing can be listening there and there is nothing to hold.
995
+ */
996
+ const FAMILY_UNAVAILABLE = /* @__PURE__ */ new Set(["EAFNOSUPPORT", "EADDRNOTAVAIL"]);
997
+ /**
998
+ * Listen on `host:port` and hand every request to `target`.
999
+ *
1000
+ * What Fastify does itself for its secondary `localhost` addresses, minus the
1001
+ * swallowed errors: `EADDRINUSE` is thrown so the caller can move to another
1002
+ * port. Resolves to `null` when the address family is unavailable.
1003
+ */
1004
+ async function bindCompanion(target, host, port) {
1005
+ const companion = node_http.default.createServer((req, res) => {
1006
+ target.emit("request", req, res);
1007
+ });
1008
+ companion.on("upgrade", (...args) => target.emit("upgrade", ...args));
1009
+ companion.timeout = target.timeout;
1010
+ companion.keepAliveTimeout = target.keepAliveTimeout;
1011
+ companion.requestTimeout = target.requestTimeout;
1012
+ companion.headersTimeout = target.headersTimeout;
1013
+ try {
1014
+ await new Promise((resolve, reject) => {
1015
+ companion.once("error", reject);
1016
+ companion.listen({
1017
+ host,
1018
+ port,
1019
+ ipv6Only: host.includes(":")
1020
+ }, () => {
1021
+ companion.off("error", reject);
1022
+ resolve();
1023
+ });
1024
+ });
1025
+ } catch (error) {
1026
+ if (FAMILY_UNAVAILABLE.has(error.code ?? "")) return null;
1027
+ throw error;
1028
+ }
1029
+ return companion;
1030
+ }
1031
+ /** Stop a companion and drop its open connections (SSE streams included). */
1032
+ const closeCompanion = (companion) => {
1033
+ companion.close(() => {});
1034
+ companion.closeAllConnections();
1035
+ };
1036
+ //#endregion
934
1037
  //#region src/utils/server.ts
935
1038
  const closeQuietly = async (name, closeable) => {
936
1039
  try {
@@ -977,22 +1080,100 @@ function registerShutdownHandlers(server, engine, exitFn = process.exit) {
977
1080
  * its process list, where anything on the box can read it.
978
1081
  */
979
1082
  const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
980
- /** Wildcard binds: addresses to listen on, never addresses to open. */
981
- const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
982
- "0.0.0.0",
983
- "::",
984
- "[::]"
985
- ]);
1083
+ /** No port in the range `listenWithFallback` tried was free. */
1084
+ var PortInUseError = class extends Error {
1085
+ constructor(message, options) {
1086
+ super(message, options);
1087
+ this.name = "PortInUseError";
1088
+ }
1089
+ };
1090
+ const isAddressInUse = (error) => error?.code === "EADDRINUSE";
1091
+ /** A bind that failed with `EADDRINUSE`, and where. */
1092
+ var AddressTaken = class extends Error {
1093
+ host;
1094
+ error;
1095
+ constructor(host, error) {
1096
+ super(`${host} is in use`);
1097
+ this.host = host;
1098
+ this.error = error;
1099
+ }
1100
+ };
986
1101
  /**
987
- * The host to put in the URL a person is expected to click.
1102
+ * Listen on `port`, or the next free port above it.
988
1103
  *
989
- * A wildcard bind is the common way to expose the UI, and printing it verbatim
990
- * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
991
- * handed to a user who then cannot reach their own review UI. `localhost` is
992
- * reachable on every interface the wildcard covers, so it is the right thing to
993
- * show; a specific host is printed as given, because that one is meaningful.
1104
+ * Retries the real `listen` on `EADDRINUSE` rather than probing first (what
1105
+ * `get-port`/`detect-port` do): a probe frees the port again before the server
1106
+ * binds it, so two cappa processes started together can both "find" the same
1107
+ * port and one of them still crashes. Binding is the only atomic check.
1108
+ *
1109
+ * Companions are bound before the server, because a Fastify instance cannot
1110
+ * listen again once it has been closed: a companion that turns out to be taken
1111
+ * costs nothing to give back, a bound server does.
1112
+ *
1113
+ * Only `EADDRINUSE` moves on. `EACCES` (a privileged port) or a bad host would
1114
+ * fail identically on every port, so they surface as-is.
1115
+ *
1116
+ * Returns the port actually bound, read back from the server so `port: 0`
1117
+ * (OS-assigned) reports the real number too.
994
1118
  */
995
- const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDCARD_HOSTS.has(host) ? "localhost" : host;
1119
+ async function listenWithFallback(server, options) {
1120
+ const { host, port, strictPort = false, companions } = options;
1121
+ const attempts = strictPort || port === 0 ? 1 : Math.min(options.maxAttempts ?? 20, 65536 - port);
1122
+ const companionHosts = companions?.hosts ?? [];
1123
+ const bind = async (address, candidate) => {
1124
+ if (!companions) return null;
1125
+ try {
1126
+ return await bindCompanion(companions.target, address, candidate);
1127
+ } catch (error) {
1128
+ throw isAddressInUse(error) ? new AddressTaken(address, error) : error;
1129
+ }
1130
+ };
1131
+ for (let i = 0; i < attempts; i++) {
1132
+ const candidate = port + i;
1133
+ const held = [];
1134
+ try {
1135
+ if (candidate !== 0) for (const address of companionHosts) {
1136
+ const companion = await bind(address, candidate);
1137
+ if (companion) held.push({
1138
+ host: address,
1139
+ server: companion
1140
+ });
1141
+ }
1142
+ try {
1143
+ await server.listen({
1144
+ port: candidate,
1145
+ host
1146
+ });
1147
+ } catch (error) {
1148
+ throw isAddressInUse(error) ? new AddressTaken(host, error) : error;
1149
+ }
1150
+ const bound = server.addresses?.()[0]?.port ?? candidate;
1151
+ if (candidate === 0) for (const address of companionHosts) {
1152
+ const companion = await bind(address, bound).catch(() => null);
1153
+ if (companion) held.push({
1154
+ host: address,
1155
+ server: companion
1156
+ });
1157
+ }
1158
+ if (companions && held.length > 0) companions.target.once("close", () => {
1159
+ for (const companion of held) closeCompanion(companion.server);
1160
+ });
1161
+ return {
1162
+ port: bound,
1163
+ companions: held.map((c) => c.host)
1164
+ };
1165
+ } catch (error) {
1166
+ for (const companion of held) closeCompanion(companion.server);
1167
+ if (!(error instanceof AddressTaken)) throw error;
1168
+ options.onPortInUse?.(candidate, error.host);
1169
+ if (i === attempts - 1) {
1170
+ const where = attempts === 1 ? error.host : host;
1171
+ 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 });
1172
+ }
1173
+ }
1174
+ }
1175
+ throw new Error(`Could not listen on ${host}:${port}.`);
1176
+ }
996
1177
  /**
997
1178
  * Build an engine, wrap it in a server, and start listening.
998
1179
  *
@@ -1007,7 +1188,7 @@ const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDC
1007
1188
  */
1008
1189
  async function startServer(options) {
1009
1190
  const logger = (0, _cappa_logger.getLogger)();
1010
- const { config, host, port, readOnly, token, ui } = options;
1191
+ const { config, host, port, readOnly, token, ui, strictPort } = options;
1011
1192
  const engine = new _cappa_core.LocalEngine({
1012
1193
  ...(0, _cappa_config.configToEngineOptions)(config),
1013
1194
  browserIdleTimeoutMs: config.review.browserIdleTimeout
@@ -1023,17 +1204,50 @@ async function startServer(options) {
1023
1204
  token
1024
1205
  });
1025
1206
  const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
1026
- await server.listen({
1027
- port,
1028
- host
1029
- });
1207
+ let boundPort;
1208
+ try {
1209
+ ({port: boundPort} = await listenWithFallback(server, {
1210
+ host: toBindHost(host),
1211
+ port,
1212
+ strictPort,
1213
+ onPortInUse: (taken, on) => logger.debug(`Port ${taken} is in use on ${on}.`),
1214
+ companions: server.server && {
1215
+ hosts: localhostCompanions(host),
1216
+ target: server.server
1217
+ }
1218
+ }));
1219
+ } catch (error) {
1220
+ unregisterShutdownHandlers();
1221
+ await closeQuietly("server", server);
1222
+ await closeQuietly("engine", engine);
1223
+ throw error;
1224
+ }
1225
+ if (boundPort !== port && port !== 0) logger.warn(`Port ${port} is in use, using ${boundPort} instead.`);
1226
+ const displayHost = toDisplayHost(host);
1227
+ const query = token ? `?token=${token}` : "";
1030
1228
  return {
1031
1229
  server,
1032
1230
  engine,
1033
- url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
1231
+ port: boundPort,
1232
+ url: `http://${displayHost}:${boundPort}${query}`,
1034
1233
  unregisterShutdownHandlers
1035
1234
  };
1036
1235
  }
1236
+ /**
1237
+ * `startServer` for a CLI command: a taken port is a one-line error and exit
1238
+ * code 1, not a stack trace. Anything else is a bug and keeps its stack.
1239
+ */
1240
+ async function startServerOrExit(options, exitFn = process.exit) {
1241
+ try {
1242
+ return await startServer(options);
1243
+ } catch (error) {
1244
+ if (error instanceof PortInUseError) {
1245
+ (0, _cappa_logger.getLogger)().error(error.message);
1246
+ exitFn(1);
1247
+ }
1248
+ throw error;
1249
+ }
1250
+ }
1037
1251
  //#endregion
1038
1252
  //#region src/commands/capture.ts
1039
1253
  async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
@@ -1555,12 +1769,13 @@ const review = async (options = {}) => {
1555
1769
  tokenWasGenerated = true;
1556
1770
  logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
1557
1771
  }
1558
- const { url } = await startServer({
1772
+ const { url } = await startServerOrExit({
1559
1773
  config,
1560
1774
  host,
1561
1775
  port,
1562
1776
  readOnly,
1563
1777
  token,
1778
+ strictPort: options.strictPort ?? false,
1564
1779
  ui: true
1565
1780
  });
1566
1781
  logger.success(`Review UI available at ${url}`);
@@ -1591,15 +1806,16 @@ const serve = async (options = {}) => {
1591
1806
  process.exit(1);
1592
1807
  return;
1593
1808
  }
1594
- const { url } = await startServer({
1809
+ const { url, port: boundPort } = await startServerOrExit({
1595
1810
  config,
1596
1811
  host,
1597
1812
  port,
1598
1813
  readOnly,
1599
1814
  token,
1815
+ strictPort: options.strictPort ?? false,
1600
1816
  ui
1601
1817
  });
1602
- logger.log(`cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1818
+ logger.log(`cappa serve listening host=${host} port=${boundPort} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1603
1819
  if (ui) logger.info(`Review UI available at ${url}`);
1604
1820
  if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
1605
1821
  };
@@ -1633,8 +1849,8 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
1633
1849
  (0, _cappa_logger.initLogger)(logLevel)?.debug(`Log level set to: ${logLevel}`);
1634
1850
  });
1635
1851
  registerCaptureCommand(program);
1636
- 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);
1637
- 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);
1852
+ 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);
1853
+ 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);
1638
1854
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
1639
1855
  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);
1640
1856
  registerAgentCommand(program);