@cappa/core 0.15.0 → 0.16.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
@@ -9,6 +9,7 @@ import { compare } from "@blazediff/core-native";
9
9
  import { interpret } from "@blazediff/interpret-native";
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { chromium, firefox, webkit } from "playwright-core";
12
+ import { execFile, execFileSync, spawn } from "node:child_process";
12
13
  //#region \0rolldown/runtime.js
13
14
  var __defProp = Object.defineProperty;
14
15
  var __exportAll = (all, no_symbols) => {
@@ -975,6 +976,91 @@ const recordCaptureOrigins = async (outputDir, origins, knownNames) => {
975
976
  }
976
977
  };
977
978
  //#endregion
979
+ //#region src/webServer/unreachable.ts
980
+ /** The advice for a refused connection when the config has no `webServer`. */
981
+ const NO_WEB_SERVER_HINT = "Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.";
982
+ /**
983
+ * How a refused connection reads, across the places one surfaces: Node's
984
+ * sockets and `fetch` (`ECONNREFUSED`), Chromium (`net::ERR_CONNECTION_REFUSED`),
985
+ * Firefox (`NS_ERROR_CONNECTION_REFUSED`) and WebKit.
986
+ */
987
+ const REFUSED_PATTERN = /\bECONNREFUSED\b|\bERR_CONNECTION_REFUSED\b|\bNS_ERROR_CONNECTION_REFUSED\b|Could not connect to (?:the )?server|Connection refused/i;
988
+ const URL_PATTERN = /\bhttps?:\/\/[^\s"'`<>)\]]+/i;
989
+ const toOrigin = (url) => {
990
+ try {
991
+ return new URL(url.replace(/[.,;:!?]+$/, "")).origin;
992
+ } catch {
993
+ return;
994
+ }
995
+ };
996
+ /**
997
+ * Whether `error` — an `Error`, a plain object, or just a message string, as
998
+ * plugins report task failures — is a refused connection.
999
+ *
1000
+ * Walks `cause` and `AggregateError.errors`: Node's `fetch` says only
1001
+ * "fetch failed" and puts `ECONNREFUSED` on its cause, and a plugin that wraps
1002
+ * the error in a friendlier one keeps it there too.
1003
+ *
1004
+ * Works on any plugin's errors, third-party included, because it reads the
1005
+ * error rather than asking the plugin.
1006
+ */
1007
+ function findRefusedConnection(error) {
1008
+ let refused = false;
1009
+ let origin;
1010
+ let socketOrigin;
1011
+ const seen = /* @__PURE__ */ new Set();
1012
+ const visit = (value, depth) => {
1013
+ if (value === null || value === void 0 || depth > 8 || seen.has(value)) return;
1014
+ seen.add(value);
1015
+ if (typeof value === "string") {
1016
+ if (REFUSED_PATTERN.test(value)) refused = true;
1017
+ const url = value.match(URL_PATTERN)?.[0];
1018
+ origin ??= url ? toOrigin(url) : void 0;
1019
+ return;
1020
+ }
1021
+ if (typeof value !== "object") return;
1022
+ const record = value;
1023
+ if (record.code === "ECONNREFUSED") {
1024
+ refused = true;
1025
+ if (typeof record.address === "string" && record.port !== void 0) {
1026
+ const host = record.address.includes(":") ? `[${record.address}]` : record.address;
1027
+ socketOrigin ??= `http://${host}:${record.port}`;
1028
+ }
1029
+ }
1030
+ visit(record.message, depth + 1);
1031
+ visit(record.cause, depth + 1);
1032
+ if (Array.isArray(record.errors)) for (const inner of record.errors) visit(inner, depth + 1);
1033
+ };
1034
+ visit(error, 0);
1035
+ if (!refused) return;
1036
+ const resolved = origin ?? socketOrigin;
1037
+ return resolved ? { origin: resolved } : {};
1038
+ }
1039
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
1040
+ "localhost",
1041
+ "127.0.0.1",
1042
+ "[::1]",
1043
+ "0.0.0.0"
1044
+ ]);
1045
+ /**
1046
+ * Whether two origins name the same server.
1047
+ *
1048
+ * Loopback spellings are interchangeable: a plugin configured with
1049
+ * `localhost:6006` and a socket error reporting `127.0.0.1:6006` are the same
1050
+ * Storybook.
1051
+ */
1052
+ function sameServer(a, b) {
1053
+ try {
1054
+ const left = new URL(a);
1055
+ const right = new URL(b);
1056
+ const port = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
1057
+ if (port(left) !== port(right)) return false;
1058
+ return left.hostname === right.hostname || LOOPBACK_HOSTS.has(left.hostname) && LOOPBACK_HOSTS.has(right.hostname);
1059
+ } catch {
1060
+ return false;
1061
+ }
1062
+ }
1063
+ //#endregion
978
1064
  //#region src/runner/tasks.ts
979
1065
  const isObject = (value) => typeof value === "object" && value !== null;
980
1066
  /**
@@ -1066,6 +1152,8 @@ var CaptureRunner = class {
1066
1152
  outputDir;
1067
1153
  fileSystem;
1068
1154
  now;
1155
+ prepare;
1156
+ explainUnreachable;
1069
1157
  listeners = /* @__PURE__ */ new Set();
1070
1158
  controller = new AbortController();
1071
1159
  seq = 0;
@@ -1095,6 +1183,8 @@ var CaptureRunner = class {
1095
1183
  this.fileSystem = options.fileSystem ?? options.screenshotTool.filesystem ?? new ScreenshotFileSystem(this.outputDir);
1096
1184
  this.id = options.id ?? randomUUID();
1097
1185
  this.now = options.now ?? (() => Date.now());
1186
+ this.prepare = options.prepare;
1187
+ this.explainUnreachable = options.explainUnreachable ?? (() => "Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.");
1098
1188
  }
1099
1189
  /** Subscribe to run events. Returns an unsubscribe function. */
1100
1190
  on(listener) {
@@ -1183,6 +1273,10 @@ var CaptureRunner = class {
1183
1273
  this.attachToolCaptureSink();
1184
1274
  try {
1185
1275
  try {
1276
+ if (this.prepare) {
1277
+ this.state = "discovering";
1278
+ await this.prepare((level, message) => this.log(level, message));
1279
+ }
1186
1280
  if (request.clearActual ?? true) {
1187
1281
  this.log("debug", `Cleaning output directory: ${this.outputDir}`);
1188
1282
  this.fileSystem.clearActual();
@@ -1190,7 +1284,8 @@ var CaptureRunner = class {
1190
1284
  }
1191
1285
  const pluginTasks = await this.discover(request);
1192
1286
  if (!this.controller.signal.aborted) await this.execute(pluginTasks);
1193
- } catch (error) {
1287
+ } catch (thrown) {
1288
+ const error = this.toUnreachableError(thrown) ?? thrown;
1194
1289
  this.error = error;
1195
1290
  this.state = "failed";
1196
1291
  this.finishedAt = this.now();
@@ -1368,6 +1463,7 @@ var CaptureRunner = class {
1368
1463
  }
1369
1464
  const durationMs = this.now() - taskStart;
1370
1465
  completedTasks++;
1466
+ result = this.explainTaskError(result);
1371
1467
  const failed = didScreenshotFail(result);
1372
1468
  const status = toTaskStatus(result);
1373
1469
  const typedResult = result;
@@ -1406,6 +1502,36 @@ var CaptureRunner = class {
1406
1502
  });
1407
1503
  }
1408
1504
  }
1505
+ /**
1506
+ * The message for a refused connection: where, and what to do about it.
1507
+ *
1508
+ * Identical for every task that hit the same server — no task id, no path —
1509
+ * so a report can collapse 300 of them into one line.
1510
+ */
1511
+ unreachableMessage(origin) {
1512
+ return `Cannot reach ${origin ?? "the app under test"}: connection refused. ${this.explainUnreachable(origin)}`;
1513
+ }
1514
+ toUnreachableError(error) {
1515
+ const refused = findRefusedConnection(error);
1516
+ if (!refused) return;
1517
+ return new Error(this.unreachableMessage(refused.origin), { cause: error });
1518
+ }
1519
+ /**
1520
+ * Replace a plugin's refused-connection error with the explained one.
1521
+ *
1522
+ * Reads the result rather than asking the plugin, so third-party plugins get
1523
+ * the same message without an API change.
1524
+ */
1525
+ explainTaskError(result) {
1526
+ const error = result?.error;
1527
+ if (error === void 0 || error === null) return result;
1528
+ const refused = findRefusedConnection(error);
1529
+ if (!refused) return result;
1530
+ return {
1531
+ ...result,
1532
+ error: this.unreachableMessage(refused.origin)
1533
+ };
1534
+ }
1409
1535
  async collectDeleted() {
1410
1536
  if (!this.anyTasksRan) return;
1411
1537
  try {
@@ -2338,6 +2464,404 @@ const collectScreenshots = async (outputDir) => {
2338
2464
  }));
2339
2465
  };
2340
2466
  //#endregion
2467
+ //#region src/webServer/process.ts
2468
+ /** Grace period between SIGTERM and SIGKILL. */
2469
+ const DEFAULT_KILL_GRACE_MS = 5e3;
2470
+ /** How long to wait for the kernel to reap a SIGKILLed group. */
2471
+ const SIGKILL_WAIT_MS = 2e3;
2472
+ const isWindows = process.platform === "win32";
2473
+ /**
2474
+ * The last part of a process's output, kept in memory.
2475
+ *
2476
+ * Bounded by bytes rather than lines: a dev server that prints one enormous
2477
+ * line is no reason to hold on to all of it, and the tail exists to explain a
2478
+ * failure, not to be a log.
2479
+ */
2480
+ var OutputTail = class {
2481
+ maxBytes;
2482
+ chunks = [];
2483
+ size = 0;
2484
+ constructor(maxBytes = 65536) {
2485
+ this.maxBytes = maxBytes;
2486
+ }
2487
+ push(chunk) {
2488
+ this.chunks.push(chunk);
2489
+ this.size += chunk.length;
2490
+ while (this.size > this.maxBytes && this.chunks.length > 1) this.size -= this.chunks.shift()?.length ?? 0;
2491
+ }
2492
+ /** The last `maxLines` non-empty lines. */
2493
+ lines(maxLines = 30) {
2494
+ return this.chunks.join("").split(/\r?\n/).filter((line) => line.trim() !== "").slice(-maxLines);
2495
+ }
2496
+ };
2497
+ /**
2498
+ * Process groups this process started and has not stopped yet.
2499
+ *
2500
+ * Exists for the one exit no `close()` covers: the process leaving without
2501
+ * shutting down. A server left running holds its port, and the next run would
2502
+ * silently *reuse* it — a stale build answering for the current one.
2503
+ */
2504
+ const liveProcesses = /* @__PURE__ */ new Set();
2505
+ let exitHookInstalled = false;
2506
+ const installExitHook = () => {
2507
+ if (exitHookInstalled) return;
2508
+ exitHookInstalled = true;
2509
+ process.on("exit", () => {
2510
+ for (const child of liveProcesses) killTreeNow(child);
2511
+ liveProcesses.clear();
2512
+ });
2513
+ };
2514
+ const killTreeNow = (child) => {
2515
+ if (child.pid === void 0) return;
2516
+ try {
2517
+ if (isWindows) execFileSync("taskkill", [
2518
+ "/pid",
2519
+ String(child.pid),
2520
+ "/T",
2521
+ "/F"
2522
+ ], { stdio: "ignore" });
2523
+ else process.kill(-child.pid, "SIGKILL");
2524
+ } catch {}
2525
+ };
2526
+ /**
2527
+ * Start `command` through a shell, as the leader of its own process group.
2528
+ *
2529
+ * A group, because the command is rarely the server itself: `pnpm storybook`
2530
+ * is pnpm, running a shell, running storybook, running workers. Killing only
2531
+ * the direct child would leave the rest holding the port.
2532
+ *
2533
+ * Output is buffered, never written anywhere unless `onOutput` asks for it —
2534
+ * `cappa capture --json` must stay a single clean document on stdout.
2535
+ */
2536
+ function spawnServerProcess(command, options) {
2537
+ const child = spawn(command, {
2538
+ cwd: options.cwd,
2539
+ env: {
2540
+ ...process.env,
2541
+ ...options.env
2542
+ },
2543
+ shell: true,
2544
+ detached: !isWindows,
2545
+ stdio: [
2546
+ "ignore",
2547
+ "pipe",
2548
+ "pipe"
2549
+ ],
2550
+ windowsHide: true
2551
+ });
2552
+ const output = new OutputTail();
2553
+ const onData = (data) => {
2554
+ const chunk = data.toString();
2555
+ output.push(chunk);
2556
+ options.onOutput?.(chunk);
2557
+ };
2558
+ child.stdout?.on("data", onData);
2559
+ child.stderr?.on("data", onData);
2560
+ liveProcesses.add(child);
2561
+ installExitHook();
2562
+ let exit;
2563
+ const exited = new Promise((resolve) => {
2564
+ const settle = (value) => {
2565
+ if (exit) return;
2566
+ exit = value;
2567
+ resolve(value);
2568
+ };
2569
+ child.once("exit", (code, signal) => settle({
2570
+ code,
2571
+ signal
2572
+ }));
2573
+ child.once("error", (error) => {
2574
+ output.push(`${error.message}\n`);
2575
+ settle({
2576
+ code: null,
2577
+ signal: null
2578
+ });
2579
+ });
2580
+ });
2581
+ let killing;
2582
+ return {
2583
+ get pid() {
2584
+ return child.pid;
2585
+ },
2586
+ exited,
2587
+ get exit() {
2588
+ return exit;
2589
+ },
2590
+ output,
2591
+ kill(graceMs = DEFAULT_KILL_GRACE_MS) {
2592
+ killing ??= killProcessTree(child, exited, graceMs).finally(() => {
2593
+ liveProcesses.delete(child);
2594
+ });
2595
+ return killing;
2596
+ }
2597
+ };
2598
+ }
2599
+ /** True while any process in the group led by `pid` is alive. */
2600
+ const groupAlive = (pid) => {
2601
+ try {
2602
+ process.kill(-pid, 0);
2603
+ return true;
2604
+ } catch (error) {
2605
+ return error.code === "EPERM";
2606
+ }
2607
+ };
2608
+ const delay = (ms) => new Promise((resolve) => {
2609
+ setTimeout(resolve, ms);
2610
+ });
2611
+ /**
2612
+ * SIGTERM the whole group, then SIGKILL whatever is left after `graceMs`.
2613
+ *
2614
+ * Waits on the group, not the child: the shell can exit at once while the
2615
+ * server it started is still shutting down — and still holding the port.
2616
+ */
2617
+ async function killProcessTree(child, exited, graceMs) {
2618
+ const pid = child.pid;
2619
+ if (pid === void 0) return;
2620
+ if (isWindows) {
2621
+ await new Promise((resolve) => {
2622
+ execFile("taskkill", [
2623
+ "/pid",
2624
+ String(pid),
2625
+ "/T",
2626
+ "/F"
2627
+ ], () => resolve());
2628
+ });
2629
+ await exited;
2630
+ return;
2631
+ }
2632
+ if (!groupAlive(pid)) return;
2633
+ try {
2634
+ process.kill(-pid, "SIGTERM");
2635
+ } catch {
2636
+ return;
2637
+ }
2638
+ const deadline = Date.now() + graceMs;
2639
+ while (groupAlive(pid) && Date.now() < deadline) await delay(50);
2640
+ if (groupAlive(pid)) {
2641
+ try {
2642
+ process.kill(-pid, "SIGKILL");
2643
+ } catch {}
2644
+ const killDeadline = Date.now() + SIGKILL_WAIT_MS;
2645
+ while (groupAlive(pid) && Date.now() < killDeadline) await delay(20);
2646
+ }
2647
+ await exited;
2648
+ }
2649
+ //#endregion
2650
+ //#region src/webServer/readiness.ts
2651
+ const PROBE_TIMEOUT_MS = 5e3;
2652
+ /** Delays between probes; the last one repeats. */
2653
+ const POLL_DELAYS_MS = [
2654
+ 100,
2655
+ 250,
2656
+ 500,
2657
+ 1e3
2658
+ ];
2659
+ /**
2660
+ * Whether `url` answers with a 2xx or 3xx status.
2661
+ *
2662
+ * Redirects are not followed: a dev server that redirects `/` to `/login` is
2663
+ * up, and following it would make readiness depend on a page cappa never asked
2664
+ * about.
2665
+ */
2666
+ async function isUrlReady(url, timeoutMs = PROBE_TIMEOUT_MS) {
2667
+ try {
2668
+ const response = await fetch(url, {
2669
+ redirect: "manual",
2670
+ signal: AbortSignal.timeout(Math.max(1, timeoutMs))
2671
+ });
2672
+ await response.body?.cancel().catch(() => {});
2673
+ return response.status >= 200 && response.status < 400;
2674
+ } catch {
2675
+ return false;
2676
+ }
2677
+ }
2678
+ /** Poll `url` until it is ready, the deadline passes, or `abort` settles. */
2679
+ async function waitForUrl(url, options) {
2680
+ const probe = options.probe ?? isUrlReady;
2681
+ const deadline = Date.now() + options.timeoutMs;
2682
+ let aborted = false;
2683
+ const abort = (options.abort ?? new Promise(() => {})).then(() => {
2684
+ aborted = true;
2685
+ }, () => {
2686
+ aborted = true;
2687
+ });
2688
+ for (let attempt = 0;; attempt++) {
2689
+ const remaining = deadline - Date.now();
2690
+ if (aborted) return "aborted";
2691
+ if (remaining <= 0) return "timeout";
2692
+ if (await probe(url, Math.min(remaining, PROBE_TIMEOUT_MS))) return "ready";
2693
+ const wait = Math.min(POLL_DELAYS_MS[Math.min(attempt, POLL_DELAYS_MS.length - 1)] ?? 1e3, Math.max(0, deadline - Date.now()));
2694
+ let timer;
2695
+ await Promise.race([new Promise((resolve) => {
2696
+ timer = setTimeout(resolve, wait);
2697
+ }), abort]);
2698
+ clearTimeout(timer);
2699
+ }
2700
+ }
2701
+ //#endregion
2702
+ //#region src/webServer/WebServerPool.ts
2703
+ /** A web server could not be started, or would not become ready. */
2704
+ var WebServerError = class extends Error {
2705
+ constructor(message) {
2706
+ super(message);
2707
+ this.name = "WebServerError";
2708
+ }
2709
+ };
2710
+ const describeExit = (exit) => exit.signal ? `signal ${exit.signal}` : exit.code === null ? "an error" : `code ${exit.code}`;
2711
+ const formatTail = (command, lines) => lines.length === 0 ? `\`${command}\` printed nothing.` : `Last output of \`${command}\`:\n${lines.map((line) => ` ${line}`).join("\n")}`;
2712
+ const seconds = (ms) => `${Math.round(ms / 100) / 10}s`;
2713
+ /**
2714
+ * The servers a config's `webServer` describes, started on demand.
2715
+ *
2716
+ * Lazy and restartable rather than started once: the owning engine calls
2717
+ * `ensure` before every run and `stop` when the browser goes idle, so a review
2718
+ * session that sits unused gives the port back, and the next capture starts —
2719
+ * and rebuilds — the app again, picking up whatever changed in between.
2720
+ *
2721
+ * Every `ensure` says which way it went, because "reusing a server" and
2722
+ * "started one" look identical in screenshots, and a stale build, another
2723
+ * branch or another project on the same port is otherwise very hard to spot.
2724
+ */
2725
+ var WebServerPool = class {
2726
+ entries;
2727
+ options;
2728
+ probe;
2729
+ /** Bumped by `stop`, so a start in flight knows it was cancelled. */
2730
+ generation = 0;
2731
+ constructor(options) {
2732
+ this.options = options;
2733
+ this.probe = options.probe ?? isUrlReady;
2734
+ this.entries = options.servers.map((config) => ({
2735
+ config,
2736
+ state: { kind: "idle" },
2737
+ starting: null
2738
+ }));
2739
+ }
2740
+ /** Whether the config has any `webServer` entry at all. */
2741
+ get configured() {
2742
+ return this.entries.length > 0;
2743
+ }
2744
+ /** Number of processes cappa started that are still running. */
2745
+ get running() {
2746
+ return this.entries.filter((entry) => entry.state.kind === "running" && !entry.state.process.exit).length;
2747
+ }
2748
+ /**
2749
+ * Make every server ready, in parallel, starting the ones that are not.
2750
+ *
2751
+ * All of them, even for a run that only captures one plugin's tasks: nothing
2752
+ * maps a plugin to a server, and guessing would start the wrong one.
2753
+ */
2754
+ async ensure(log = this.defaultLog) {
2755
+ if (this.entries.length === 0) return;
2756
+ const errors = (await Promise.allSettled(this.entries.map((entry) => this.ensureEntry(entry, log)))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2757
+ if (errors.length === 1) throw errors[0];
2758
+ if (errors.length > 1) throw new WebServerError(errors.map((error) => error instanceof Error ? error.message : error).join("\n\n"));
2759
+ }
2760
+ /**
2761
+ * Stop every server cappa started. A reused server is left alone — cappa did
2762
+ * not start it, so it is not cappa's to stop.
2763
+ */
2764
+ async stop() {
2765
+ this.generation += 1;
2766
+ await Promise.all(this.entries.map(async (entry) => {
2767
+ const state = entry.state;
2768
+ entry.state = { kind: "idle" };
2769
+ if (state.kind === "running") await state.process.kill(this.options.killGraceMs);
2770
+ }));
2771
+ }
2772
+ /**
2773
+ * What to tell the user about a connection refused at `origin`.
2774
+ *
2775
+ * Always an actionable sentence: the bare "ECONNREFUSED" it replaces is the
2776
+ * single most common capture failure, and says nothing about what to do.
2777
+ */
2778
+ explainUnreachable(origin) {
2779
+ if (this.entries.length === 0) return NO_WEB_SERVER_HINT;
2780
+ const matching = origin ? this.entries.find((entry) => sameServer(entry.config.url, origin)) : void 0;
2781
+ const crashed = matching?.state.kind === "exited" ? matching : this.entries.find((entry) => entry.state.kind === "exited");
2782
+ if (crashed && crashed.state.kind === "exited") return `The web server \`${crashed.config.command}\` exited with ${describeExit(crashed.state.exit)} during the run; it is started again on the next run.\n${formatTail(crashed.config.command, crashed.state.tail)}`;
2783
+ if (origin && !matching) return `No \`webServer\` entry serves ${origin} (configured: ${this.entries.map((entry) => entry.config.url).join(", ")}). Check that the plugin's URL matches \`webServer.url\`.`;
2784
+ return "The configured `webServer` was ready, but stopped accepting connections.";
2785
+ }
2786
+ defaultLog = (level, message) => {
2787
+ this.options.log?.(level, message);
2788
+ };
2789
+ ensureEntry(entry, log) {
2790
+ entry.starting ??= this.startEntry(entry, log).finally(() => {
2791
+ entry.starting = null;
2792
+ });
2793
+ return entry.starting;
2794
+ }
2795
+ async startEntry(entry, log) {
2796
+ const { command, url, timeout, cwd, env, reuseExistingServer } = entry.config;
2797
+ const previous = entry.state;
2798
+ if (previous.kind === "running" && !previous.process.exit) {
2799
+ log("info", `Using \`${command}\` at ${url}, started earlier by cappa`);
2800
+ return;
2801
+ }
2802
+ if (previous.kind === "exited") log("warn", `\`${command}\` exited with ${describeExit(previous.exit)} after the last run; starting it again`);
2803
+ if (await this.probe(url, Math.min(timeout, 5e3))) {
2804
+ if (reuseExistingServer) {
2805
+ entry.state = { kind: "reused" };
2806
+ log("info", `Reusing server at ${url} — \`${command}\` was not run`);
2807
+ return;
2808
+ }
2809
+ throw new WebServerError(`${url} is already in use, and \`webServer.reuseExistingServer\` is false. Stop whatever is serving it, or allow reusing it.`);
2810
+ }
2811
+ const generation = this.generation;
2812
+ const startedAt = Date.now();
2813
+ log("info", `Starting \`${command}\` — waiting up to ${seconds(timeout)} for ${url}`);
2814
+ const child = (this.options.spawn ?? spawnServerProcess)(command, {
2815
+ cwd,
2816
+ env,
2817
+ onOutput: this.options.onOutput ? (chunk) => this.options.onOutput?.(entry.config, chunk) : void 0
2818
+ });
2819
+ entry.state = {
2820
+ kind: "running",
2821
+ process: child
2822
+ };
2823
+ const result = await waitForUrl(url, {
2824
+ timeoutMs: timeout,
2825
+ abort: child.exited,
2826
+ probe: this.probe
2827
+ });
2828
+ if (generation !== this.generation) {
2829
+ await child.kill(this.options.killGraceMs);
2830
+ throw new WebServerError(`\`${command}\` was stopped before ${url} was ready.`);
2831
+ }
2832
+ if (result === "ready") {
2833
+ this.watchForCrash(entry, child);
2834
+ log("success", `Started \`${command}\` — ${url} ready in ${seconds(Date.now() - startedAt)}`);
2835
+ return;
2836
+ }
2837
+ entry.state = { kind: "idle" };
2838
+ if (result === "aborted") {
2839
+ const exit = await child.exited;
2840
+ throw new WebServerError(`\`${command}\` exited with ${describeExit(exit)} before ${url} was ready.\n${formatTail(command, child.output.lines())}`);
2841
+ }
2842
+ await child.kill(this.options.killGraceMs);
2843
+ throw new WebServerError(`Timed out after ${seconds(timeout)} waiting for \`${command}\` to serve ${url}. If it needs longer — a build step, say — raise \`webServer.timeout\`.\n${formatTail(command, child.output.lines())}`);
2844
+ }
2845
+ /**
2846
+ * Record a server that exits on its own, so the failures it causes can say
2847
+ * why and the next run starts it again. Deliberately no restart loop: a
2848
+ * server that keeps crashing should fail loudly, not flap.
2849
+ */
2850
+ watchForCrash(entry, child) {
2851
+ child.exited.then((exit) => {
2852
+ const state = entry.state;
2853
+ if (state.kind !== "running" || state.process !== child) return;
2854
+ entry.state = {
2855
+ kind: "exited",
2856
+ exit,
2857
+ tail: child.output.lines()
2858
+ };
2859
+ child.kill(this.options.killGraceMs);
2860
+ this.defaultLog("error", `\`${entry.config.command}\` exited with ${describeExit(exit)} while cappa was using it.`);
2861
+ });
2862
+ }
2863
+ };
2864
+ //#endregion
2341
2865
  //#region src/engine/RunStore.ts
2342
2866
  /**
2343
2867
  * In-memory registry of capture runs and their event history.
@@ -2503,6 +3027,7 @@ const isWatchInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.watc
2503
3027
  var WarmBrowser = class {
2504
3028
  createTool;
2505
3029
  idleTimeoutMs;
3030
+ onShutdown;
2506
3031
  tool = null;
2507
3032
  idleTimer = null;
2508
3033
  inUse = false;
@@ -2514,6 +3039,7 @@ var WarmBrowser = class {
2514
3039
  constructor(options) {
2515
3040
  this.createTool = options.create;
2516
3041
  this.idleTimeoutMs = options.idleTimeoutMs ?? 3e5;
3042
+ this.onShutdown = options.onShutdown;
2517
3043
  }
2518
3044
  /** True while a browser process is alive. */
2519
3045
  get isWarm() {
@@ -2585,7 +3111,11 @@ var WarmBrowser = class {
2585
3111
  const tool = this.tool;
2586
3112
  this.tool = null;
2587
3113
  this.inUse = false;
2588
- if (tool) await tool.close();
3114
+ try {
3115
+ if (tool) await tool.close();
3116
+ } finally {
3117
+ await this.onShutdown?.();
3118
+ }
2589
3119
  });
2590
3120
  }
2591
3121
  startIdleTimer() {
@@ -2610,7 +3140,11 @@ var WarmBrowser = class {
2610
3140
  if (this.inUse || this.closed || this.holds > 0) return;
2611
3141
  const tool = this.tool;
2612
3142
  this.tool = null;
2613
- if (tool) await tool.close();
3143
+ try {
3144
+ if (tool) await tool.close();
3145
+ } finally {
3146
+ await this.onShutdown?.();
3147
+ }
2614
3148
  });
2615
3149
  }
2616
3150
  serialize(work) {
@@ -2974,6 +3508,28 @@ const toRelative = (cwd, changedPath) => {
2974
3508
  };
2975
3509
  //#endregion
2976
3510
  //#region src/engine/LocalEngine.ts
3511
+ const defaultLog = (level, message) => {
3512
+ try {
3513
+ getLogger()[level](message);
3514
+ } catch {}
3515
+ };
3516
+ /**
3517
+ * Stream a web server's output live at debug level. Buffered regardless: the
3518
+ * tail is what explains a server that failed to start.
3519
+ *
3520
+ * To stderr, never stdout — `capture --json` owns stdout.
3521
+ */
3522
+ const streamOutputAtDebug = (server, chunk) => {
3523
+ let level = 0;
3524
+ try {
3525
+ level = getLogger().level;
3526
+ } catch {
3527
+ return;
3528
+ }
3529
+ if (level < 4) return;
3530
+ const prefix = `[webServer ${server.url}] `;
3531
+ process.stderr.write(chunk.split(/(?<=\n)/).map((line) => prefix + line).join(""));
3532
+ };
2977
3533
  /**
2978
3534
  * `CaptureEngine` backed by an in-process Playwright browser.
2979
3535
  *
@@ -2991,6 +3547,7 @@ var LocalEngine = class {
2991
3547
  fileSystem;
2992
3548
  browser;
2993
3549
  runs;
3550
+ webServers;
2994
3551
  /**
2995
3552
  * Set synchronously the moment a run is claimed, before any `await`, so two
2996
3553
  * concurrent `startRun` calls cannot both pass the check and then fight over
@@ -3018,9 +3575,16 @@ var LocalEngine = class {
3018
3575
  this.plugins = options.plugins;
3019
3576
  this.fileSystem = new ScreenshotFileSystem(options.outputDir);
3020
3577
  this.runs = new RunStore(options.runStore);
3578
+ this.webServers = new WebServerPool({
3579
+ servers: options.webServer ?? [],
3580
+ log: defaultLog,
3581
+ onOutput: streamOutputAtDebug,
3582
+ ...options.webServerPool
3583
+ });
3021
3584
  this.browser = new WarmBrowser({
3022
3585
  create: options.createScreenshotTool ?? (() => this.buildTool()),
3023
- idleTimeoutMs: options.browserIdleTimeoutMs
3586
+ idleTimeoutMs: options.browserIdleTimeoutMs,
3587
+ onShutdown: () => this.webServers.stop()
3024
3588
  });
3025
3589
  }
3026
3590
  buildTool() {
@@ -3070,7 +3634,9 @@ var LocalEngine = class {
3070
3634
  screenshotTool: await this.browser.acquire(),
3071
3635
  plugins: this.plugins,
3072
3636
  outputDir: this.options.outputDir,
3073
- fileSystem: this.fileSystem
3637
+ fileSystem: this.fileSystem,
3638
+ prepare: (log) => this.webServers.ensure(log),
3639
+ explainUnreachable: (origin) => this.webServers.explainUnreachable(origin)
3074
3640
  });
3075
3641
  const finish = () => {
3076
3642
  if (this.activeRunId !== runner.id) return;
@@ -3208,7 +3774,11 @@ var LocalEngine = class {
3208
3774
  this.closed = true;
3209
3775
  await this.endWatch("engine-closed");
3210
3776
  (this.activeRunId ? this.runs.getRunner(this.activeRunId) : void 0)?.abort();
3211
- await this.browser.close();
3777
+ try {
3778
+ await this.browser.close();
3779
+ } finally {
3780
+ await this.webServers.stop();
3781
+ }
3212
3782
  }
3213
3783
  async endWatch(reason) {
3214
3784
  const session = this.watchSession;
@@ -3281,6 +3851,7 @@ var LocalEngine = class {
3281
3851
  async discoverTargets() {
3282
3852
  const tool = await this.browser.acquire();
3283
3853
  try {
3854
+ await this.webServers.ensure();
3284
3855
  const discovered = await Promise.all(this.plugins.map(async (plugin) => {
3285
3856
  const tasks = await plugin.discover(tool);
3286
3857
  return {
@@ -4009,6 +4580,35 @@ const writeAgentVerdict = async (outputDir, name, input) => {
4009
4580
  return verdictPath;
4010
4581
  };
4011
4582
  //#endregion
4012
- export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CaptureRunner, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_MAX_TASKS, ENGINE_ERROR_CODES, FsScreenshotStore, JUDGED_LABELS, JUDGE_MODES, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, RunInProgressError, RunStore, SUB_PERCEPTUAL_PERCENT, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, agentDir, agentReportPath, attachConsoleLogging, buildHeadline, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, deriveVerdict, didScreenshotFail, filterTasks, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isJudgedLabel, isRunInProgressError, isUnknownTargetsError, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, readAgentReport, readCaptureManifest, readDiffMeta, recordCaptureOrigins, renderJudgmentTiles, renderOverview, runAgentCheck, sanitizeScreenshotFilename, selectTasks, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, writeAgentVerdict };
4583
+ //#region src/webServer/resolve.ts
4584
+ const DEFAULT_WEB_SERVER_TIMEOUT_MS = 6e4;
4585
+ const isHttpUrl = (value) => URL.canParse(value) && ["http:", "https:"].includes(new URL(value).protocol);
4586
+ /**
4587
+ * Normalise `webServer` to a list with every default applied.
4588
+ *
4589
+ * A relative `cwd` resolves against `configDir` — the directory of
4590
+ * `cappa.config.ts` — not the process's working directory, so the same config
4591
+ * works whether cappa runs from the repository root or from inside the package
4592
+ * (`pnpm -F visual-tests cappa capture`).
4593
+ */
4594
+ function resolveWebServerConfig(webServer, configDir, env = process.env) {
4595
+ if (webServer === void 0) return [];
4596
+ return (Array.isArray(webServer) ? webServer : [webServer]).map((entry, index) => {
4597
+ const where = Array.isArray(webServer) ? `webServer[${index}]` : "webServer";
4598
+ if (typeof entry?.command !== "string" || entry.command.trim() === "") throw new Error(`Invalid configuration: ${where}.command is required.`);
4599
+ if (typeof entry.url !== "string" || !isHttpUrl(entry.url)) throw new Error(`Invalid configuration: ${where}.url must be an absolute URL, e.g. "http://localhost:6006".`);
4600
+ if (entry.timeout !== void 0 && !(Number.isFinite(entry.timeout) && entry.timeout > 0)) throw new Error(`Invalid configuration: ${where}.timeout must be a positive number of milliseconds.`);
4601
+ return {
4602
+ command: entry.command,
4603
+ url: entry.url,
4604
+ reuseExistingServer: entry.reuseExistingServer ?? !env.CI,
4605
+ timeout: entry.timeout ?? 6e4,
4606
+ cwd: path.resolve(configDir, entry.cwd ?? "."),
4607
+ env: entry.env ?? {}
4608
+ };
4609
+ });
4610
+ }
4611
+ //#endregion
4612
+ export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CaptureRunner, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_KILL_GRACE_MS, DEFAULT_MAX_TASKS, DEFAULT_WEB_SERVER_TIMEOUT_MS, ENGINE_ERROR_CODES, FsScreenshotStore, JUDGED_LABELS, JUDGE_MODES, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, NO_WEB_SERVER_HINT, OutputTail, RunInProgressError, RunStore, SUB_PERCEPTUAL_PERCENT, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, buildHeadline, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, deriveVerdict, didScreenshotFail, filterTasks, findRefusedConnection, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isJudgedLabel, isRunInProgressError, isUnknownTargetsError, isUrlReady, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, readAgentReport, readCaptureManifest, readDiffMeta, recordCaptureOrigins, renderJudgmentTiles, renderOverview, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, writeAgentVerdict };
4013
4613
 
4014
4614
  //# sourceMappingURL=index.mjs.map