@cappa/core 0.12.4 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,9 +4,23 @@ import { getLogger } from "@cappa/logger";
4
4
  import fsp, { glob, open, readFile, writeFile } from "node:fs/promises";
5
5
  import sharp from "sharp";
6
6
  import os from "node:os";
7
- import path from "node:path";
8
- import { compare, interpret } from "@blazediff/core-native";
7
+ import path, { relative } from "node:path";
8
+ import { compare } from "@blazediff/core-native";
9
+ import { interpret } from "@blazediff/interpret-native";
10
+ import { createHash, randomUUID } from "node:crypto";
9
11
  import { chromium, firefox, webkit } from "playwright-core";
12
+ //#region \0rolldown/runtime.js
13
+ var __defProp = Object.defineProperty;
14
+ var __exportAll = (all, no_symbols) => {
15
+ let target = {};
16
+ for (var name in all) __defProp(target, name, {
17
+ get: all[name],
18
+ enumerable: true
19
+ });
20
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
21
+ return target;
22
+ };
23
+ //#endregion
10
24
  //#region src/features/png/util.ts
11
25
  const pngSignature = Buffer.from([
12
26
  137,
@@ -371,7 +385,8 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
371
385
  const percentDifference = nativeResult.diffPercentage;
372
386
  let interpretation;
373
387
  if (wantInterpret && !nativeResult.match) try {
374
- interpretation = await interpret(p1, p2, {
388
+ interpretation = await interpret(p1, p2, void 0, {
389
+ source: "pixel",
375
390
  threshold: options.threshold,
376
391
  antialiasing: options.includeAA ?? false
377
392
  });
@@ -463,7 +478,63 @@ async function mapWithConcurrency(concurrency, items, fn) {
463
478
  return results;
464
479
  }
465
480
  //#endregion
481
+ //#region src/paths.ts
482
+ /**
483
+ * Screenshot filenames are not a trusted input.
484
+ *
485
+ * A name is whatever a plugin chose, and a plugin may derive it from something
486
+ * it does not control either: `@cappa/plugin-storybook` reads
487
+ * `parameters.cappa.variants[].filename` out of the browser, so the string
488
+ * originates in story-author code. Every name eventually lands in
489
+ * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and
490
+ * `../`, so without a guard a single story could write a PNG anywhere the
491
+ * process can write.
492
+ *
493
+ * Two layers live here: `sanitizeScreenshotFilename` turns a name into a
494
+ * relative path that cannot escape (used where a bad name should degrade rather
495
+ * than fail a run), and `resolveInside` is the hard backstop at the write sink.
496
+ */
497
+ /**
498
+ * Whether `target` resolves to something strictly inside `base`.
499
+ *
500
+ * Note this is deliberately stricter than a `startsWith("..")` check on the
501
+ * relative path, which also rejects legitimate names such as `..foo.png`.
502
+ */
503
+ function isPathInside(base, target) {
504
+ const relative = path.relative(base, target);
505
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
506
+ }
507
+ /**
508
+ * Resolve `filename` inside `base`, rejecting absolute paths and any name that
509
+ * escapes `base`.
510
+ *
511
+ * @param label - The bucket name used in the error message (`actual`, `diff`, …)
512
+ */
513
+ function resolveInside(base, filename, label) {
514
+ const resolved = path.resolve(base, filename);
515
+ if (path.isAbsolute(filename) || !isPathInside(base, resolved)) throw new Error(`Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`);
516
+ return resolved;
517
+ }
518
+ /**
519
+ * Turn a screenshot filename into a relative path that stays inside its bucket.
520
+ *
521
+ * Path separators are kept — they are how plugins express folders — but
522
+ * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are
523
+ * normalised to `/`, and a Windows drive prefix is removed. Returns an empty
524
+ * string when nothing usable is left, which callers treat as "no name given".
525
+ */
526
+ function sanitizeScreenshotFilename(filename) {
527
+ const segments = filename.replace(/\\/g, "/").split("/").map((segment) => segment.replace(/\0/g, "").trim()).filter((segment) => segment !== "" && segment !== "." && segment !== "..");
528
+ if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) segments.shift();
529
+ return segments.join("/");
530
+ }
531
+ //#endregion
466
532
  //#region src/filesystem.ts
533
+ var filesystem_exports = /* @__PURE__ */ __exportAll({
534
+ ScreenshotFileSystem: () => ScreenshotFileSystem,
535
+ readDiffMeta: () => readDiffMeta,
536
+ toDiffMetaPath: () => toDiffMetaPath
537
+ });
467
538
  const APPROVE_SCREENSHOTS_CONCURRENCY = 8;
468
539
  /**
469
540
  * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
@@ -525,9 +596,8 @@ var ScreenshotFileSystem = class {
525
596
  */
526
597
  async approveFromActualPath(actualFilePath) {
527
598
  const actualAbsolute = this.resolveActualPath(actualFilePath);
528
- const relativePath = path.relative(this.actual, actualAbsolute);
529
- if (relativePath.startsWith("..")) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
530
- return this.approveRelative(relativePath);
599
+ if (!isPathInside(this.actual, actualAbsolute)) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
600
+ return this.approveRelative(path.relative(this.actual, actualAbsolute));
531
601
  }
532
602
  /**
533
603
  * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).
@@ -659,22 +729,33 @@ var ScreenshotFileSystem = class {
659
729
  return this.diff;
660
730
  }
661
731
  /**
732
+ * Resolve a screenshot filename inside one of the buckets.
733
+ *
734
+ * This is the single sink every read and write funnels through, so it is also
735
+ * where an untrusted filename is stopped: plugin-supplied names (Storybook
736
+ * variant filenames come straight from story code) must never escape the
737
+ * bucket they belong to.
738
+ */
739
+ resolveBucketPath(directory, filename) {
740
+ return resolveInside(this[directory], filename, directory);
741
+ }
742
+ /**
662
743
  * Get the path to an actual screenshot file
663
744
  */
664
745
  getActualFilePath(filename) {
665
- return path.resolve(this.actual, filename);
746
+ return this.resolveBucketPath("actual", filename);
666
747
  }
667
748
  /**
668
749
  * Get the path to an expected screenshot file
669
750
  */
670
751
  getExpectedFilePath(filename) {
671
- return path.resolve(this.expected, filename);
752
+ return this.resolveBucketPath("expected", filename);
672
753
  }
673
754
  /**
674
755
  * Get the path to a diff screenshot file
675
756
  */
676
757
  getDiffFilePath(filename) {
677
- return path.resolve(this.diff, filename);
758
+ return this.resolveBucketPath("diff", filename);
678
759
  }
679
760
  /**
680
761
  * Write a file to the actual directory
@@ -739,9 +820,544 @@ var ScreenshotFileSystem = class {
739
820
  return path.resolve(this.actual, filePath);
740
821
  }
741
822
  getRelativePath(directory, filePath) {
742
- const relativePath = path.relative(this[directory], filePath);
743
- if (relativePath.startsWith("..")) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
744
- return relativePath;
823
+ if (!isPathInside(this[directory], filePath)) throw new Error(`Cannot resolve relative path outside of ${directory} directory: ${filePath}`);
824
+ return path.relative(this[directory], filePath);
825
+ }
826
+ };
827
+ //#endregion
828
+ //#region src/screenshots/manifest.ts
829
+ /**
830
+ * Maps a screenshot back to the capture task that produced it.
831
+ *
832
+ * Nothing on disk carries this. A screenshot's name comes from the filename a
833
+ * plugin chose (`example/button/primary`), while the task id comes from the
834
+ * plugin's own addressing scheme (`example-button--primary` for Storybook) —
835
+ * and there is no rule connecting the two. Without a record written at capture
836
+ * time, "re-capture this one screenshot" has no task to ask for, which is
837
+ * exactly how the review UI's re-capture button came to send a name the engine
838
+ * had never heard of.
839
+ *
840
+ * Kept beside `actual/` and `expected/` rather than inside them so it is never
841
+ * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is
842
+ * configured with `serveDotFiles: false`) will not serve it.
843
+ */
844
+ const MANIFEST_FILENAME = ".cappa-manifest.json";
845
+ /** Bumped only if the on-disk shape changes incompatibly. */
846
+ const MANIFEST_VERSION = 1;
847
+ const emptyManifest = () => ({
848
+ version: 1,
849
+ screenshots: {}
850
+ });
851
+ const manifestPath = (outputDir) => path.resolve(outputDir, MANIFEST_FILENAME);
852
+ /**
853
+ * The key a capture filename is recorded under.
854
+ *
855
+ * Must match the `name` `groupScreenshots` derives, or a lookup silently
856
+ * misses: the relative path with its `.png` dropped, and separators normalised
857
+ * so a manifest written on Windows is readable on Linux.
858
+ */
859
+ const toManifestKey = (filename) => filename.split(path.sep).join("/").replace(/\.png$/i, "");
860
+ const isOrigin = (value) => typeof value === "object" && value !== null && typeof value.taskId === "string" && typeof value.plugin === "string";
861
+ /**
862
+ * Read the manifest, or an empty one.
863
+ *
864
+ * Never throws: the manifest is an optimisation, and a missing, truncated or
865
+ * hand-edited file must degrade to "we do not know where this came from"
866
+ * rather than break the screenshot index every command depends on.
867
+ */
868
+ const readCaptureManifest = async (outputDir) => {
869
+ try {
870
+ const raw = await fsp.readFile(manifestPath(outputDir), "utf8");
871
+ const parsed = JSON.parse(raw);
872
+ if (typeof parsed !== "object" || parsed === null || parsed.version !== 1) return emptyManifest();
873
+ const screenshots = parsed.screenshots;
874
+ if (typeof screenshots !== "object" || screenshots === null) return emptyManifest();
875
+ const entries = Object.entries(screenshots).filter(([, origin]) => isOrigin(origin));
876
+ return {
877
+ version: 1,
878
+ screenshots: Object.fromEntries(entries)
879
+ };
880
+ } catch {
881
+ return emptyManifest();
882
+ }
883
+ };
884
+ /**
885
+ * Merge freshly captured origins into whatever the manifest already holds.
886
+ *
887
+ * A run only captures the tasks it was asked for, so existing entries have to
888
+ * survive — otherwise re-capturing one screenshot would strip every other
889
+ * screenshot's origin and disable the button that started it.
890
+ *
891
+ * `knownNames`, when given, is the set of screenshots that currently exist;
892
+ * entries outside it are dropped so renames and deletions do not accumulate
893
+ * forever. New origins are always kept, whether or not they appear in it.
894
+ */
895
+ const mergeCaptureManifest = (existing, origins, knownNames) => {
896
+ const keep = knownNames ? new Set(knownNames) : void 0;
897
+ const merged = {};
898
+ for (const [name, origin] of Object.entries(existing.screenshots)) if (!keep || keep.has(name)) merged[name] = origin;
899
+ for (const [name, origin] of Object.entries(origins)) merged[name] = origin;
900
+ return {
901
+ version: 1,
902
+ screenshots: merged
903
+ };
904
+ };
905
+ /**
906
+ * Persist `origins`, merged over what is already recorded.
907
+ *
908
+ * Best-effort by design: a read-only or full disk must not turn a successful
909
+ * capture run into a failed one, so a write failure is reported to the caller
910
+ * as `false` rather than thrown.
911
+ */
912
+ const recordCaptureOrigins = async (outputDir, origins, knownNames) => {
913
+ try {
914
+ const merged = mergeCaptureManifest(await readCaptureManifest(outputDir), origins, knownNames);
915
+ await fsp.mkdir(path.resolve(outputDir), { recursive: true });
916
+ await fsp.writeFile(manifestPath(outputDir), `${JSON.stringify(merged, null, 2)}\n`, "utf8");
917
+ return true;
918
+ } catch {
919
+ return false;
920
+ }
921
+ };
922
+ //#endregion
923
+ //#region src/runner/tasks.ts
924
+ const isObject = (value) => typeof value === "object" && value !== null;
925
+ /**
926
+ * Decide whether a plugin's `execute` result represents a failed screenshot.
927
+ *
928
+ * Plugins return loosely-shaped objects, so this inspects the three signals that
929
+ * matter: an explicit `error`, an explicit `success: false`, or a missing
930
+ * `filepath` on a task that was not skipped.
931
+ */
932
+ const didScreenshotFail = (result) => {
933
+ if (!isObject(result)) return false;
934
+ if ("error" in result && result.error != null) return true;
935
+ if ("success" in result) {
936
+ const { success } = result;
937
+ if (success === false) return true;
938
+ }
939
+ if ("filepath" in result) {
940
+ const { filepath, skipped } = result;
941
+ if (!filepath && skipped !== true) return true;
942
+ }
943
+ return false;
944
+ };
945
+ /**
946
+ * Map a plugin result onto the status shown in the UI.
947
+ *
948
+ * Mirrors the screenshot categories: a capture with no baseline is `new`, a
949
+ * failing comparison is `changed`, and anything `didScreenshotFail` flags for
950
+ * another reason is `failed`.
951
+ */
952
+ const toTaskStatus = (result) => {
953
+ if (!isObject(result)) return "passed";
954
+ const typed = result;
955
+ if (typed.skipped === true) return "skipped";
956
+ if ("error" in typed && typed.error != null) return "failed";
957
+ if (typed.isNew === true) return "new";
958
+ if (typed.success === false) return "changed";
959
+ if (didScreenshotFail(typed)) return "failed";
960
+ return "passed";
961
+ };
962
+ /** Restrict `tasks` to those whose id matches the glob `filter`. */
963
+ function filterTasks(tasks, filter) {
964
+ return tasks.filter((task) => path.matchesGlob(task.id, filter));
965
+ }
966
+ /** Restrict `tasks` to an explicit set of ids. */
967
+ function selectTasks(tasks, taskIds) {
968
+ const wanted = new Set(taskIds);
969
+ return tasks.filter((task) => wanted.has(task.id));
970
+ }
971
+ /**
972
+ * Baselines in `expected/` that have no counterpart in `actual/` — screenshots
973
+ * that existed when the baseline was approved but were not captured this run.
974
+ */
975
+ async function getDeletedScreenshots(outputDir) {
976
+ const actualDir = path.resolve(outputDir, "actual");
977
+ const expectedDir = path.resolve(outputDir, "expected");
978
+ const [actualFiles, expectedFiles] = await Promise.all([Array.fromAsync(glob(path.join(actualDir, "**/*.png"))), Array.fromAsync(glob(path.join(expectedDir, "**/*.png")))]);
979
+ const actualRelative = new Set(actualFiles.map((p) => path.relative(actualDir, p)));
980
+ return expectedFiles.map((p) => path.relative(expectedDir, p)).filter((rel) => !actualRelative.has(rel));
981
+ }
982
+ //#endregion
983
+ //#region src/runner/types.ts
984
+ const toSerializedError = (error) => {
985
+ if (error instanceof Error) return {
986
+ name: error.name,
987
+ message: error.message,
988
+ stack: error.stack
989
+ };
990
+ return {
991
+ name: "Error",
992
+ message: String(error)
993
+ };
994
+ };
995
+ //#endregion
996
+ //#region src/runner/CaptureRunner.ts
997
+ /**
998
+ * Orchestrates a single capture run: discover → filter → execute, emitting
999
+ * typed events as it goes.
1000
+ *
1001
+ * Deliberately free of any presentation or process concerns — no logger calls,
1002
+ * no `chalk`, no `process.exit`. Consumers render the events however they like:
1003
+ * the CLI writes them to the terminal, the server streams them over SSE.
1004
+ *
1005
+ * One instance represents one run. Create a new one per run.
1006
+ */
1007
+ var CaptureRunner = class {
1008
+ id;
1009
+ screenshotTool;
1010
+ plugins;
1011
+ outputDir;
1012
+ fileSystem;
1013
+ now;
1014
+ listeners = /* @__PURE__ */ new Set();
1015
+ controller = new AbortController();
1016
+ seq = 0;
1017
+ state = "idle";
1018
+ request = {};
1019
+ startedAt = 0;
1020
+ finishedAt;
1021
+ error;
1022
+ anyTasksRan = false;
1023
+ deletedScreenshots = [];
1024
+ taskRecords = /* @__PURE__ */ new Map();
1025
+ failures = [];
1026
+ started = false;
1027
+ /**
1028
+ * Which task currently owns each pooled page.
1029
+ *
1030
+ * Tasks run concurrently, one per page, so the page is what disambiguates
1031
+ * the capture sink's reports. Populated only while a task is executing.
1032
+ */
1033
+ taskByPage = /* @__PURE__ */ new Map();
1034
+ /** Screenshot name → the task that captured it, for the capture manifest. */
1035
+ capturedOrigins = /* @__PURE__ */ new Map();
1036
+ constructor(options) {
1037
+ this.screenshotTool = options.screenshotTool;
1038
+ this.plugins = options.plugins;
1039
+ this.outputDir = options.outputDir ?? options.screenshotTool.outputDir;
1040
+ this.fileSystem = options.fileSystem ?? options.screenshotTool.filesystem ?? new ScreenshotFileSystem(this.outputDir);
1041
+ this.id = options.id ?? randomUUID();
1042
+ this.now = options.now ?? (() => Date.now());
1043
+ }
1044
+ /** Subscribe to run events. Returns an unsubscribe function. */
1045
+ on(listener) {
1046
+ this.listeners.add(listener);
1047
+ return () => {
1048
+ this.listeners.delete(listener);
1049
+ };
1050
+ }
1051
+ get signal() {
1052
+ return this.controller.signal;
1053
+ }
1054
+ /**
1055
+ * Request cancellation. In-flight tasks finish (Playwright gives us no safe
1056
+ * mid-screenshot abort), but no further tasks are started.
1057
+ */
1058
+ abort() {
1059
+ if (this.state === "completed" || this.state === "failed") return;
1060
+ this.controller.abort();
1061
+ }
1062
+ getSummary() {
1063
+ const tasks = [...this.taskRecords.values()];
1064
+ const completedTasks = tasks.filter((task) => task.status !== "pending" && task.status !== "running").length;
1065
+ return {
1066
+ id: this.id,
1067
+ state: this.state,
1068
+ request: this.request,
1069
+ startedAt: this.startedAt,
1070
+ finishedAt: this.finishedAt,
1071
+ durationMs: this.finishedAt === void 0 ? void 0 : this.finishedAt - this.startedAt,
1072
+ totalTasks: tasks.length,
1073
+ completedTasks,
1074
+ failedTasks: this.failures.length,
1075
+ deletedScreenshots: this.deletedScreenshots,
1076
+ anyTasksRan: this.anyTasksRan,
1077
+ error: this.error === void 0 ? void 0 : toSerializedError(this.error)
1078
+ };
1079
+ }
1080
+ getDetail() {
1081
+ return {
1082
+ ...this.getSummary(),
1083
+ tasks: [...this.taskRecords.values()],
1084
+ failures: [...this.failures]
1085
+ };
1086
+ }
1087
+ /**
1088
+ * Whether the run produced at least one failing screenshot or detected a
1089
+ * deleted baseline — the condition the CLI exits non-zero on.
1090
+ */
1091
+ get hasScreenshotFailure() {
1092
+ return this.failures.length > 0 || this.deletedScreenshots.length > 0;
1093
+ }
1094
+ emit(event) {
1095
+ this.seq += 1;
1096
+ const full = {
1097
+ ...event,
1098
+ seq: this.seq,
1099
+ runId: this.id,
1100
+ at: this.now()
1101
+ };
1102
+ for (const listener of this.listeners) try {
1103
+ listener(full);
1104
+ } catch {}
1105
+ }
1106
+ log(level, message, ...args) {
1107
+ this.emit({
1108
+ type: "log",
1109
+ level,
1110
+ message,
1111
+ args
1112
+ });
1113
+ }
1114
+ /**
1115
+ * Run the capture. Resolves with the final detail; rejects if a plugin threw,
1116
+ * after emitting `run:error`.
1117
+ */
1118
+ async run(request = {}) {
1119
+ if (this.started) throw new Error(`Run ${this.id} has already been started`);
1120
+ this.started = true;
1121
+ this.request = request;
1122
+ this.startedAt = this.now();
1123
+ this.emit({
1124
+ type: "run:start",
1125
+ request
1126
+ });
1127
+ this.attachToolLogSink();
1128
+ this.attachToolCaptureSink();
1129
+ try {
1130
+ try {
1131
+ if (request.clearActual ?? true) {
1132
+ this.log("debug", `Cleaning output directory: ${this.outputDir}`);
1133
+ this.fileSystem.clearActual();
1134
+ this.fileSystem.clearDiff();
1135
+ }
1136
+ const pluginTasks = await this.discover(request);
1137
+ if (!this.controller.signal.aborted) await this.execute(pluginTasks);
1138
+ } catch (error) {
1139
+ this.error = error;
1140
+ this.state = "failed";
1141
+ this.finishedAt = this.now();
1142
+ this.emit({
1143
+ type: "run:error",
1144
+ error: toSerializedError(error)
1145
+ });
1146
+ throw error;
1147
+ }
1148
+ await this.collectDeleted();
1149
+ await this.persistCaptureOrigins();
1150
+ this.finishedAt = this.now();
1151
+ this.state = this.controller.signal.aborted ? "cancelled" : "completed";
1152
+ if (this.state === "cancelled") this.emit({ type: "run:cancelled" });
1153
+ const summary = this.getSummary();
1154
+ this.emit({
1155
+ type: "run:complete",
1156
+ summary
1157
+ });
1158
+ return this.getDetail();
1159
+ } finally {
1160
+ this.detachToolLogSink();
1161
+ this.detachToolCaptureSink();
1162
+ await this.persistCaptureOrigins();
1163
+ }
1164
+ }
1165
+ /**
1166
+ * Route `ScreenshotTool`'s log output through this run's events.
1167
+ *
1168
+ * Guarded rather than called outright: tests inject minimal stand-ins for the
1169
+ * tool, and a fake without the method should not fail a run.
1170
+ */
1171
+ attachToolLogSink() {
1172
+ this.screenshotTool.setLogSink?.((level, message, ...args) => {
1173
+ this.log(level, message, ...args);
1174
+ });
1175
+ }
1176
+ detachToolLogSink() {
1177
+ this.screenshotTool.setLogSink?.(null);
1178
+ }
1179
+ /**
1180
+ * Record which task produces which screenshot file.
1181
+ *
1182
+ * Guarded like the log sink: tests inject minimal tool stand-ins, and one
1183
+ * without the method must not fail a run — it only loses the manifest.
1184
+ */
1185
+ attachToolCaptureSink() {
1186
+ this.screenshotTool.setCaptureSink?.((page, filename) => {
1187
+ const origin = this.taskByPage.get(page);
1188
+ if (origin) this.capturedOrigins.set(toManifestKey(filename), origin);
1189
+ });
1190
+ }
1191
+ detachToolCaptureSink() {
1192
+ this.screenshotTool.setCaptureSink?.(null);
1193
+ this.taskByPage.clear();
1194
+ }
1195
+ /**
1196
+ * Write what this run learned about screenshot origins.
1197
+ *
1198
+ * Idempotent, because it is called once on the happy path and again from
1199
+ * `run`'s `finally` for the paths that never reach it. Existing entries are
1200
+ * preserved and only names that no longer exist on disk are dropped, so a
1201
+ * run of one task does not erase every other screenshot's origin.
1202
+ */
1203
+ async persistCaptureOrigins() {
1204
+ if (this.capturedOrigins.size === 0) return;
1205
+ const origins = Object.fromEntries(this.capturedOrigins);
1206
+ this.capturedOrigins.clear();
1207
+ let knownNames;
1208
+ try {
1209
+ const [actual, expected] = await Promise.all([this.fileSystem.getActualScreenshots(), this.fileSystem.getExpectedScreenshots()]);
1210
+ knownNames = [...actual.map((file) => toManifestKey(relative(this.fileSystem.getActualDir(), file))), ...expected.map((file) => toManifestKey(relative(this.fileSystem.getExpectedDir(), file)))];
1211
+ } catch {
1212
+ knownNames = void 0;
1213
+ }
1214
+ if (!await recordCaptureOrigins(this.outputDir, origins, knownNames)) this.log("debug", "Could not write the capture manifest; re-capturing a single screenshot may be unavailable.");
1215
+ }
1216
+ async discover(request) {
1217
+ this.state = "discovering";
1218
+ const wanted = request.plugins ? new Set(request.plugins) : void 0;
1219
+ const plugins = wanted ? this.plugins.filter((plugin) => wanted.has(plugin.name)) : this.plugins;
1220
+ this.emit({
1221
+ type: "discover:start",
1222
+ plugins: plugins.map((plugin) => plugin.name)
1223
+ });
1224
+ const pluginTasks = await Promise.all(plugins.map(async (plugin) => {
1225
+ this.log("debug", `Discovering tasks for plugin: ${plugin.name}`);
1226
+ const tasks = await plugin.discover(this.screenshotTool);
1227
+ this.emit({
1228
+ type: "discover:plugin",
1229
+ plugin: plugin.name,
1230
+ taskCount: tasks.length
1231
+ });
1232
+ return {
1233
+ plugin,
1234
+ tasks
1235
+ };
1236
+ }));
1237
+ const targets = pluginTasks.flatMap(({ plugin, tasks }) => tasks.map((task) => ({
1238
+ id: task.id,
1239
+ url: task.url,
1240
+ plugin: plugin.name
1241
+ })));
1242
+ this.emit({
1243
+ type: "discover:complete",
1244
+ targets,
1245
+ totalTasks: targets.length
1246
+ });
1247
+ if (request.filter === void 0 && request.taskIds === void 0) return pluginTasks;
1248
+ const applied = [];
1249
+ for (const entry of pluginTasks) {
1250
+ const before = entry.tasks.length;
1251
+ let tasks = entry.tasks;
1252
+ if (request.filter !== void 0) tasks = filterTasks(tasks, request.filter);
1253
+ if (request.taskIds !== void 0) tasks = selectTasks(tasks, request.taskIds);
1254
+ entry.tasks = tasks;
1255
+ applied.push({
1256
+ plugin: entry.plugin.name,
1257
+ before,
1258
+ after: tasks.length
1259
+ });
1260
+ }
1261
+ this.emit({
1262
+ type: "filter:applied",
1263
+ filter: request.filter,
1264
+ taskIds: request.taskIds,
1265
+ plugins: applied
1266
+ });
1267
+ return pluginTasks;
1268
+ }
1269
+ async execute(pluginTasks) {
1270
+ this.state = "running";
1271
+ for (const { plugin, tasks } of pluginTasks) {
1272
+ if (tasks.length === 0) continue;
1273
+ if (this.controller.signal.aborted) return;
1274
+ this.anyTasksRan = true;
1275
+ let pluginHasFailure = false;
1276
+ for (const task of tasks) this.taskRecords.set(task.id, {
1277
+ id: task.id,
1278
+ url: task.url,
1279
+ plugin: plugin.name,
1280
+ status: "pending"
1281
+ });
1282
+ this.emit({
1283
+ type: "plugin:start",
1284
+ plugin: plugin.name,
1285
+ taskCount: tasks.length
1286
+ });
1287
+ this.log("debug", `Processing ${tasks.length} tasks with concurrency ${this.screenshotTool.concurrency}`);
1288
+ let completedTasks = 0;
1289
+ const pageContexts = /* @__PURE__ */ new Map();
1290
+ const results = await mapWithConcurrency(this.screenshotTool.concurrency, tasks, async (task, workerIndex) => {
1291
+ if (this.controller.signal.aborted) return;
1292
+ const page = this.screenshotTool.getPageFromPool(workerIndex);
1293
+ if (!pageContexts.has(workerIndex) && plugin.initPage) pageContexts.set(workerIndex, await plugin.initPage(page, this.screenshotTool));
1294
+ const context = pageContexts.get(workerIndex);
1295
+ const record = this.taskRecords.get(task.id);
1296
+ if (record) record.status = "running";
1297
+ this.emit({
1298
+ type: "task:start",
1299
+ plugin: plugin.name,
1300
+ taskId: task.id,
1301
+ url: task.url
1302
+ });
1303
+ const taskStart = this.now();
1304
+ this.taskByPage.set(page, {
1305
+ taskId: task.id,
1306
+ plugin: plugin.name
1307
+ });
1308
+ let result;
1309
+ try {
1310
+ result = await plugin.execute(task, page, this.screenshotTool, context);
1311
+ } finally {
1312
+ this.taskByPage.delete(page);
1313
+ }
1314
+ const durationMs = this.now() - taskStart;
1315
+ completedTasks++;
1316
+ const failed = didScreenshotFail(result);
1317
+ const status = toTaskStatus(result);
1318
+ const typedResult = result;
1319
+ if (record) {
1320
+ record.status = status;
1321
+ record.durationMs = durationMs;
1322
+ record.result = typedResult;
1323
+ }
1324
+ if (failed) {
1325
+ pluginHasFailure = true;
1326
+ this.failures.push({
1327
+ taskId: task.id,
1328
+ taskUrl: task.url,
1329
+ result: typedResult ?? {},
1330
+ pluginName: plugin.name
1331
+ });
1332
+ }
1333
+ this.emit({
1334
+ type: "task:complete",
1335
+ plugin: plugin.name,
1336
+ taskId: task.id,
1337
+ url: task.url,
1338
+ status,
1339
+ completed: completedTasks,
1340
+ total: tasks.length,
1341
+ durationMs,
1342
+ result: typedResult
1343
+ });
1344
+ return result;
1345
+ });
1346
+ this.emit({
1347
+ type: "plugin:complete",
1348
+ plugin: plugin.name,
1349
+ resultCount: results.length,
1350
+ failed: pluginHasFailure
1351
+ });
1352
+ }
1353
+ }
1354
+ async collectDeleted() {
1355
+ if (!this.anyTasksRan) return;
1356
+ try {
1357
+ this.deletedScreenshots = await getDeletedScreenshots(this.outputDir);
1358
+ } catch (error) {
1359
+ this.log("warn", "Could not check for deleted screenshots:", error);
1360
+ }
745
1361
  }
746
1362
  };
747
1363
  //#endregion
@@ -760,6 +1376,15 @@ const defaultGMSDDiffConfig = {
760
1376
  downsample: 0,
761
1377
  c: 170
762
1378
  };
1379
+ const LOG_SINK_LEVELS = [
1380
+ "debug",
1381
+ "info",
1382
+ "warn",
1383
+ "error",
1384
+ "success"
1385
+ ];
1386
+ /** A logger-shaped object that forwards every call to `sink`. */
1387
+ const toSinkLogger = (sink) => Object.fromEntries(LOG_SINK_LEVELS.map((level) => [level, (message, ...args) => sink(level, String(message), ...args)]));
763
1388
  var ScreenshotTool = class {
764
1389
  browserType;
765
1390
  headless;
@@ -773,11 +1398,23 @@ var ScreenshotTool = class {
773
1398
  contexts = [];
774
1399
  pages = [];
775
1400
  diff;
1401
+ /**
1402
+ * Where this tool's own output goes.
1403
+ *
1404
+ * Normally the global logger. While a `CaptureRunner` owns the tool it is
1405
+ * swapped for a shim that forwards into the run's event stream instead — see
1406
+ * `setLogSink`.
1407
+ */
776
1408
  logger;
777
1409
  retries;
778
1410
  filesystem;
779
1411
  logConsoleEvents;
780
1412
  connectionTimeout;
1413
+ defaultUserAgent = "";
1414
+ /** The real logger, kept so `setLogSink(null)` restores the same instance. */
1415
+ baseLogger;
1416
+ /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
1417
+ captureSink = null;
781
1418
  constructor(options) {
782
1419
  this.browserType = options.browserType || "chromium";
783
1420
  this.headless = options.headless !== false;
@@ -791,10 +1428,40 @@ var ScreenshotTool = class {
791
1428
  this.concurrency = Math.max(1, options.concurrency || 1);
792
1429
  this.logConsoleEvents = options.logConsoleEvents ?? true;
793
1430
  this.connectionTimeout = options.connectionTimeout ?? 2e4;
794
- this.logger = getLogger();
1431
+ this.baseLogger = getLogger();
1432
+ this.logger = this.baseLogger;
795
1433
  this.retries = options.retries || 2;
796
1434
  this.filesystem = new ScreenshotFileSystem(this.outputDir);
797
1435
  }
1436
+ /**
1437
+ * Send this tool's own log output to `sink` instead of the global logger.
1438
+ *
1439
+ * `ScreenshotTool` writes lines a user expects to see — "Screenshot saved",
1440
+ * "Screenshot passed visual comparison", the retry warnings — straight to the
1441
+ * logger. That is fine in-process and useless over a network: with the
1442
+ * browser on another machine those lines would stay in the *host's* terminal
1443
+ * while the client showed a run with no commentary. A `CaptureRunner` installs
1444
+ * a sink for the duration of a run so they travel as `log` events instead.
1445
+ *
1446
+ * Pass `null` to restore the real logger.
1447
+ */
1448
+ setLogSink(sink) {
1449
+ this.logger = sink ? toSinkLogger(sink) : this.baseLogger;
1450
+ }
1451
+ /**
1452
+ * Report every screenshot this tool writes to `sink`.
1453
+ *
1454
+ * A `CaptureRunner` installs one for the duration of a run so it can record
1455
+ * which task produced which file. Nothing else can know: a plugin picks the
1456
+ * filename inside `execute` and is free to derive it from the task however
1457
+ * it likes, so the only reliable observation point is the write itself —
1458
+ * which also catches variants, whose filenames the plugin never states.
1459
+ *
1460
+ * Pass `null` to stop reporting.
1461
+ */
1462
+ setCaptureSink(sink) {
1463
+ this.captureSink = sink;
1464
+ }
798
1465
  resolveDiffOptions(diff) {
799
1466
  if (diff?.type === "gmsd") return {
800
1467
  ...defaultGMSDDiffConfig,
@@ -834,13 +1501,22 @@ var ScreenshotTool = class {
834
1501
  if (!browser) throw new Error("Something went wrong with starting the browser.");
835
1502
  this.browser = browser;
836
1503
  const tempCtx = await browser.newContext();
837
- const defaultUserAgent = await (await tempCtx.newPage()).evaluate(() => navigator.userAgent);
1504
+ const tempPage = await tempCtx.newPage();
1505
+ this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
838
1506
  await tempCtx.close();
1507
+ await this.createContexts();
1508
+ }
1509
+ /**
1510
+ * Create the pool of browser contexts and pages.
1511
+ */
1512
+ async createContexts() {
1513
+ const browser = this.browser;
1514
+ if (!browser) throw new Error("Browser not initialized");
839
1515
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
840
1516
  const context = await browser.newContext({
841
1517
  reducedMotion: "reduce",
842
1518
  deviceScaleFactor: 2,
843
- userAgent: `${defaultUserAgent} CappaStorybook`,
1519
+ userAgent: `${this.defaultUserAgent} CappaStorybook`,
844
1520
  viewport: this.viewport
845
1521
  });
846
1522
  return {
@@ -854,12 +1530,57 @@ var ScreenshotTool = class {
854
1530
  this.page = this.pages[0] ?? null;
855
1531
  }
856
1532
  /**
1533
+ * Closes every context and page, leaving the browser process running.
1534
+ */
1535
+ async closeContexts() {
1536
+ for (const context of this.contexts) await context.close();
1537
+ this.contexts = [];
1538
+ this.pages = [];
1539
+ this.context = null;
1540
+ this.page = null;
1541
+ }
1542
+ /**
1543
+ * Throw away the current contexts and build a fresh pool on the same browser.
1544
+ *
1545
+ * A long-lived process that keeps the browser warm between capture runs must
1546
+ * call this first: contexts accumulate cookies, storage and scroll position,
1547
+ * and a screenshot taken against leaked state is not the screenshot the CLI
1548
+ * would have taken with a fresh browser.
1549
+ */
1550
+ async recycleContexts() {
1551
+ if (!this.browser) throw new Error("Browser not initialized");
1552
+ await this.closeContexts();
1553
+ await this.createContexts();
1554
+ }
1555
+ /**
857
1556
  * Closes browser
858
1557
  * If not closed, the process will not exit
1558
+ *
1559
+ * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is
1560
+ * delivered to the whole foreground process group, Chromium included, so by
1561
+ * the time a signal handler gets here every context can already be dead and
1562
+ * closing one throws `Failed to find context with id …`. Letting that escape
1563
+ * turns a clean shutdown into an uncaught exception, which is the one thing
1564
+ * teardown must never do.
859
1565
  */
860
1566
  async close() {
861
- for (const context of this.contexts) await context.close();
862
- if (this.browser) await this.browser.close();
1567
+ try {
1568
+ await this.closeContexts();
1569
+ } catch (error) {
1570
+ getLogger().debug("Error closing browser contexts:", error);
1571
+ this.contexts = [];
1572
+ this.pages = [];
1573
+ this.context = null;
1574
+ this.page = null;
1575
+ }
1576
+ if (this.browser) {
1577
+ try {
1578
+ await this.browser.close();
1579
+ } catch (error) {
1580
+ getLogger().debug("Error closing the browser:", error);
1581
+ }
1582
+ this.browser = null;
1583
+ }
863
1584
  }
864
1585
  /**
865
1586
  * Navigates to a URL with "domcontentloaded" waitUntil
@@ -1032,8 +1753,21 @@ var ScreenshotTool = class {
1032
1753
  passed: false
1033
1754
  };
1034
1755
  }
1756
+ /**
1757
+ * Resolve the filename a variant is written under.
1758
+ *
1759
+ * An explicit `variant.filename` wins, but it is sanitized first: for
1760
+ * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,
1761
+ * so it is story-author input and could otherwise carry `../` or an absolute
1762
+ * path into the write sink. A name left empty by sanitization falls back to
1763
+ * the derived one.
1764
+ */
1035
1765
  getVariantFilename(filename, variant) {
1036
- if (variant.filename) return variant.filename;
1766
+ if (variant.filename) {
1767
+ const safeFilename = sanitizeScreenshotFilename(variant.filename);
1768
+ if (safeFilename !== variant.filename) this.logger.warn(`Variant filename "${variant.filename}" is not a valid screenshot path, using "${safeFilename || "the derived name"}" instead`);
1769
+ if (safeFilename) return safeFilename;
1770
+ }
1037
1771
  const parsed = path.parse(filename);
1038
1772
  const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
1039
1773
  const ext = parsed.ext || ".png";
@@ -1068,6 +1802,9 @@ var ScreenshotTool = class {
1068
1802
  }
1069
1803
  const duration = Math.round(performance.now() - start);
1070
1804
  this.logger.debug(`${filename} captured in ${duration}ms`);
1805
+ try {
1806
+ this.captureSink?.(page, filename);
1807
+ } catch {}
1071
1808
  return result;
1072
1809
  }
1073
1810
  async capture(page, filename, options, extras = {}) {
@@ -1191,7 +1928,7 @@ var ScreenshotTool = class {
1191
1928
  baseResult.diffImagePath = baseCaptureResult.diffImagePath;
1192
1929
  baseResult.skipped = baseCaptureResult.skipped;
1193
1930
  for (const variant of variants) {
1194
- const variantFilename = variant.filename || this.getVariantFilename(baseFilename, variant);
1931
+ const variantFilename = this.getVariantFilename(baseFilename, variant);
1195
1932
  const variantOptions = {
1196
1933
  ...baseOptions,
1197
1934
  ...variant.options
@@ -1249,6 +1986,1132 @@ var ScreenshotTool = class {
1249
1986
  }
1250
1987
  };
1251
1988
  //#endregion
1252
- export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, mapWithConcurrency, readDiffMeta, toDiffMetaPath };
1989
+ //#region src/screenshots/groupScreenshots.ts
1990
+ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScreenshots, outputDir) => {
1991
+ const screenshotRepresentations = [];
1992
+ const expectedByRelativePath = /* @__PURE__ */ new Map();
1993
+ for (const screenshot of expectedScreenshots) {
1994
+ const relativePath = path.relative(`${outputDir}/expected`, screenshot);
1995
+ expectedByRelativePath.set(relativePath, screenshot);
1996
+ }
1997
+ const diffByRelativePath = /* @__PURE__ */ new Map();
1998
+ for (const screenshot of diffScreenshots) {
1999
+ const relativePath = path.relative(`${outputDir}/diff`, screenshot);
2000
+ diffByRelativePath.set(relativePath, screenshot);
2001
+ }
2002
+ const actualRelativePaths = /* @__PURE__ */ new Set();
2003
+ for (const screenshot of actualScreenshots) {
2004
+ const relativePath = path.relative(`${outputDir}/actual`, screenshot);
2005
+ actualRelativePaths.add(relativePath);
2006
+ const name = relativePath.replace(".png", "");
2007
+ const id = createHash("sha256").update(relativePath).digest("hex");
2008
+ const expectedScreenshot = expectedByRelativePath.get(relativePath);
2009
+ const diffScreenshot = diffByRelativePath.get(relativePath);
2010
+ const diffMeta = diffScreenshot ? await readDiffMeta(diffScreenshot) : void 0;
2011
+ screenshotRepresentations.push({
2012
+ id,
2013
+ name,
2014
+ category: buildCategory(expectedScreenshot, diffScreenshot),
2015
+ expectedPath: expectedScreenshot ? path.relative(outputDir, expectedScreenshot) : void 0,
2016
+ diffPath: diffScreenshot ? path.relative(outputDir, diffScreenshot) : void 0,
2017
+ actualPath: path.relative(outputDir, screenshot),
2018
+ ...diffMeta ? { diffMeta } : {}
2019
+ });
2020
+ }
2021
+ for (const expectedScreenshot of expectedScreenshots) {
2022
+ const relativePath = path.relative(`${outputDir}/expected`, expectedScreenshot);
2023
+ if (actualRelativePaths.has(relativePath)) continue;
2024
+ const name = relativePath.replace(".png", "");
2025
+ const id = createHash("sha256").update(relativePath).digest("hex");
2026
+ screenshotRepresentations.push({
2027
+ id,
2028
+ name,
2029
+ category: "deleted",
2030
+ expectedPath: path.relative(outputDir, expectedScreenshot)
2031
+ });
2032
+ }
2033
+ return screenshotRepresentations.sort((a, b) => {
2034
+ return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
2035
+ });
2036
+ };
2037
+ const buildCategory = (expectedScreenshot, diffScreenshot) => {
2038
+ if (expectedScreenshot && diffScreenshot) return "changed";
2039
+ if (expectedScreenshot) return "passed";
2040
+ return "new";
2041
+ };
2042
+ const CATEGORY_ORDER = {
2043
+ new: 0,
2044
+ deleted: 1,
2045
+ changed: 2,
2046
+ passed: 3
2047
+ };
2048
+ //#endregion
2049
+ //#region src/screenshots/collectScreenshots.ts
2050
+ const listPngs = async (dir) => Array.fromAsync(await glob(path.resolve(dir, "**/*.png")));
2051
+ /**
2052
+ * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and
2053
+ * group them into the screenshot representations used by the CLI commands
2054
+ * (including the diff metadata sidecar with the optional interpretation).
2055
+ *
2056
+ * The capture manifest is folded in here so every consumer — the CLI, the
2057
+ * server, the review UI — sees the same `taskId`, and so a screenshot captured
2058
+ * before manifests existed simply has none rather than a wrong one.
2059
+ */
2060
+ const collectScreenshots = async (outputDir) => {
2061
+ const [actualScreenshots, expectedScreenshots, diffScreenshots, manifest] = await Promise.all([
2062
+ listPngs(path.resolve(outputDir, "actual")),
2063
+ listPngs(path.resolve(outputDir, "expected")),
2064
+ listPngs(path.resolve(outputDir, "diff")),
2065
+ readCaptureManifest(outputDir)
2066
+ ]);
2067
+ return (await groupScreenshots(actualScreenshots, expectedScreenshots, diffScreenshots, outputDir)).map((screenshot) => {
2068
+ const origin = manifest.screenshots[screenshot.name];
2069
+ return origin ? {
2070
+ ...screenshot,
2071
+ taskId: origin.taskId,
2072
+ plugin: origin.plugin
2073
+ } : screenshot;
2074
+ });
2075
+ };
2076
+ //#endregion
2077
+ //#region src/engine/RunStore.ts
2078
+ /**
2079
+ * In-memory registry of capture runs and their event history.
2080
+ *
2081
+ * The event buffer is what lets an SSE client reconnect without losing
2082
+ * anything: subscribers replay from the last `seq` they saw before live
2083
+ * delivery starts.
2084
+ */
2085
+ var RunStore = class {
2086
+ maxEventsPerRun;
2087
+ maxRuns;
2088
+ runs = /* @__PURE__ */ new Map();
2089
+ /** Insertion order, oldest first — the eviction queue. */
2090
+ order = [];
2091
+ constructor(options = {}) {
2092
+ this.maxEventsPerRun = options.maxEventsPerRun ?? 5e3;
2093
+ this.maxRuns = options.maxRuns ?? 20;
2094
+ }
2095
+ /** Register a runner and start buffering its events. */
2096
+ add(runner) {
2097
+ const entry = {
2098
+ id: runner.id,
2099
+ runner,
2100
+ events: [],
2101
+ dropped: 0,
2102
+ listeners: /* @__PURE__ */ new Set()
2103
+ };
2104
+ this.runs.set(runner.id, entry);
2105
+ this.order.push(runner.id);
2106
+ this.evictOldRuns();
2107
+ runner.on((event) => {
2108
+ entry.events.push(event);
2109
+ if (entry.events.length > this.maxEventsPerRun) {
2110
+ entry.dropped += entry.events.length - this.maxEventsPerRun;
2111
+ entry.events.splice(0, entry.events.length - this.maxEventsPerRun);
2112
+ }
2113
+ for (const listener of entry.listeners) try {
2114
+ listener(event);
2115
+ } catch {}
2116
+ });
2117
+ }
2118
+ /**
2119
+ * Freeze the final detail of a finished run so it stays queryable after the
2120
+ * runner is discarded.
2121
+ */
2122
+ finalize(runId) {
2123
+ const entry = this.runs.get(runId);
2124
+ if (entry) entry.finalDetail = entry.runner.getDetail();
2125
+ }
2126
+ get(runId) {
2127
+ const entry = this.runs.get(runId);
2128
+ if (!entry) return;
2129
+ return entry.finalDetail ?? entry.runner.getDetail();
2130
+ }
2131
+ getRunner(runId) {
2132
+ return this.runs.get(runId)?.runner;
2133
+ }
2134
+ /** Newest first. */
2135
+ list() {
2136
+ return [...this.order].reverse().map((id) => {
2137
+ const entry = this.runs.get(id);
2138
+ if (!entry) return;
2139
+ return entry.finalDetail ?? entry.runner.getSummary();
2140
+ }).filter((summary) => summary !== void 0);
2141
+ }
2142
+ /**
2143
+ * Subscribe to a run, replaying buffered events first.
2144
+ *
2145
+ * Replay is synchronous, so a subscriber cannot miss events that arrive
2146
+ * between the buffer read and the listener being registered.
2147
+ */
2148
+ subscribe(runId, onEvent, options = {}) {
2149
+ const entry = this.runs.get(runId);
2150
+ if (!entry) return () => {};
2151
+ const sinceSeq = options.sinceSeq ?? 0;
2152
+ for (const event of entry.events) if (event.seq > sinceSeq) onEvent(event);
2153
+ entry.listeners.add(onEvent);
2154
+ return () => {
2155
+ entry.listeners.delete(onEvent);
2156
+ };
2157
+ }
2158
+ /** How many events were dropped from a run's buffer (0 when none were). */
2159
+ droppedEvents(runId) {
2160
+ return this.runs.get(runId)?.dropped ?? 0;
2161
+ }
2162
+ evictOldRuns() {
2163
+ while (this.order.length > this.maxRuns) {
2164
+ const oldest = this.order.shift();
2165
+ if (oldest !== void 0) this.runs.delete(oldest);
2166
+ }
2167
+ }
2168
+ };
2169
+ //#endregion
2170
+ //#region src/engine/types.ts
2171
+ /**
2172
+ * Stable discriminators for engine errors.
2173
+ *
2174
+ * These exist because `instanceof` is not reliable across the package
2175
+ * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the
2176
+ * CLI binary) and an ESM one (the server) each load their own copy of these
2177
+ * classes: an error thrown by one is not an `instanceof` the other's class,
2178
+ * and the check silently fails — turning a 409 into a 500. Callers must use
2179
+ * the guards below rather than `instanceof`.
2180
+ */
2181
+ const ENGINE_ERROR_CODES = {
2182
+ runInProgress: "CAPPA_RUN_IN_PROGRESS",
2183
+ unknownTargets: "CAPPA_UNKNOWN_TARGETS",
2184
+ watchInProgress: "CAPPA_WATCH_IN_PROGRESS"
2185
+ };
2186
+ /** Thrown by `startRun` when the engine is already running something. */
2187
+ var RunInProgressError = class extends Error {
2188
+ code = ENGINE_ERROR_CODES.runInProgress;
2189
+ activeRunId;
2190
+ constructor(activeRunId) {
2191
+ super(`A capture run is already in progress (${activeRunId})`);
2192
+ this.name = "RunInProgressError";
2193
+ this.activeRunId = activeRunId;
2194
+ }
2195
+ };
2196
+ /** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */
2197
+ var UnknownTargetsError = class extends Error {
2198
+ code = ENGINE_ERROR_CODES.unknownTargets;
2199
+ taskIds;
2200
+ constructor(taskIds) {
2201
+ super(`Unknown task ids: ${taskIds.join(", ")}`);
2202
+ this.name = "UnknownTargetsError";
2203
+ this.taskIds = taskIds;
2204
+ }
2205
+ };
2206
+ /** Thrown by `startWatch` when a watch session is already running. */
2207
+ var WatchInProgressError = class extends Error {
2208
+ code = ENGINE_ERROR_CODES.watchInProgress;
2209
+ constructor() {
2210
+ super("A watch session is already running");
2211
+ this.name = "WatchInProgressError";
2212
+ }
2213
+ };
2214
+ const hasCode = (error, code) => error instanceof Error && error.code === code;
2215
+ /**
2216
+ * Identity-independent check for `RunInProgressError`.
2217
+ *
2218
+ * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.
2219
+ */
2220
+ const isRunInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.runInProgress);
2221
+ /** Identity-independent check for `UnknownTargetsError`. */
2222
+ const isUnknownTargetsError = (error) => hasCode(error, ENGINE_ERROR_CODES.unknownTargets);
2223
+ /** Identity-independent check for `WatchInProgressError`. */
2224
+ const isWatchInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.watchInProgress);
2225
+ //#endregion
2226
+ //#region src/engine/WarmBrowser.ts
2227
+ /**
2228
+ * Keeps a Playwright browser alive between capture runs.
2229
+ *
2230
+ * Interactively, a cold Chromium start on every "Capture" click is the
2231
+ * difference between a snappy tool and a sluggish one — but a browser left
2232
+ * running forever is a memory leak, so it is evicted after an idle period.
2233
+ *
2234
+ * Contexts are recycled on every acquire after the first, because a warm
2235
+ * browser's pages carry cookies, storage and scroll position from the previous
2236
+ * run and a screenshot taken against leaked state is not the screenshot the CLI
2237
+ * would have taken.
2238
+ */
2239
+ var WarmBrowser = class {
2240
+ createTool;
2241
+ idleTimeoutMs;
2242
+ tool = null;
2243
+ idleTimer = null;
2244
+ inUse = false;
2245
+ closed = false;
2246
+ /** Outstanding `hold()` leases. While any is held, eviction is suspended. */
2247
+ holds = 0;
2248
+ /** Serializes acquire/close so concurrent callers cannot race the browser. */
2249
+ pending = Promise.resolve();
2250
+ constructor(options) {
2251
+ this.createTool = options.create;
2252
+ this.idleTimeoutMs = options.idleTimeoutMs ?? 3e5;
2253
+ }
2254
+ /** True while a browser process is alive. */
2255
+ get isWarm() {
2256
+ return this.tool !== null;
2257
+ }
2258
+ /**
2259
+ * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.
2260
+ * Always pair with `release()`.
2261
+ */
2262
+ async acquire() {
2263
+ return this.serialize(async () => {
2264
+ if (this.closed) throw new Error("WarmBrowser has been closed");
2265
+ this.cancelIdleTimer();
2266
+ this.inUse = true;
2267
+ if (this.tool) {
2268
+ await this.tool.recycleContexts();
2269
+ return this.tool;
2270
+ }
2271
+ const tool = this.createTool();
2272
+ await tool.init();
2273
+ this.tool = tool;
2274
+ return tool;
2275
+ });
2276
+ }
2277
+ /**
2278
+ * Hand the browser back. It stays warm until the idle timeout elapses.
2279
+ */
2280
+ release() {
2281
+ this.inUse = false;
2282
+ if (this.closed || !this.tool) return;
2283
+ if (this.holds > 0) {
2284
+ this.cancelIdleTimer();
2285
+ return;
2286
+ }
2287
+ if (this.idleTimeoutMs <= 0) {
2288
+ this.close();
2289
+ return;
2290
+ }
2291
+ this.startIdleTimer();
2292
+ }
2293
+ /**
2294
+ * Suspend idle eviction until the returned function is called.
2295
+ *
2296
+ * Held by an active watch session. Without it, `WarmBrowser` closes the
2297
+ * browser between saves during a coffee break and the next save pays full
2298
+ * start-up — which is the entire premise of watch mode, defeated by its own
2299
+ * idle handling.
2300
+ */
2301
+ hold() {
2302
+ this.holds += 1;
2303
+ this.cancelIdleTimer();
2304
+ let released = false;
2305
+ return () => {
2306
+ if (released) return;
2307
+ released = true;
2308
+ this.holds -= 1;
2309
+ if (this.holds === 0 && !this.inUse) this.release();
2310
+ };
2311
+ }
2312
+ /** True while at least one lease suspends idle eviction. */
2313
+ get isHeld() {
2314
+ return this.holds > 0;
2315
+ }
2316
+ /** Shut the browser down now. Safe to call repeatedly. */
2317
+ async close() {
2318
+ this.closed = true;
2319
+ this.cancelIdleTimer();
2320
+ await this.serialize(async () => {
2321
+ const tool = this.tool;
2322
+ this.tool = null;
2323
+ this.inUse = false;
2324
+ if (tool) await tool.close();
2325
+ });
2326
+ }
2327
+ startIdleTimer() {
2328
+ this.cancelIdleTimer();
2329
+ const timer = setTimeout(() => {
2330
+ this.idleTimer = null;
2331
+ if (this.inUse || this.closed || this.holds > 0 || !this.tool) return;
2332
+ this.evict();
2333
+ }, this.idleTimeoutMs);
2334
+ if (typeof timer.unref === "function") timer.unref();
2335
+ this.idleTimer = timer;
2336
+ }
2337
+ cancelIdleTimer() {
2338
+ if (this.idleTimer !== null) {
2339
+ clearTimeout(this.idleTimer);
2340
+ this.idleTimer = null;
2341
+ }
2342
+ }
2343
+ /** Shut the browser down but stay usable — the next acquire starts cold. */
2344
+ async evict() {
2345
+ await this.serialize(async () => {
2346
+ if (this.inUse || this.closed || this.holds > 0) return;
2347
+ const tool = this.tool;
2348
+ this.tool = null;
2349
+ if (tool) await tool.close();
2350
+ });
2351
+ }
2352
+ serialize(work) {
2353
+ const next = this.pending.then(work, work);
2354
+ this.pending = next.then(() => void 0, () => void 0);
2355
+ return next;
2356
+ }
2357
+ };
2358
+ //#endregion
2359
+ //#region src/engine/WatchSession.ts
2360
+ /**
2361
+ * Directories no watch should ever descend into.
2362
+ *
2363
+ * `outputDir` is not here because it is not a fixed name — the engine passes it
2364
+ * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs
2365
+ * into it, every write is a change, and the session would trigger itself
2366
+ * forever.
2367
+ */
2368
+ const DEFAULT_IGNORED_DIRS = /* @__PURE__ */ new Set([
2369
+ ".git",
2370
+ ".cache",
2371
+ ".next",
2372
+ ".nuxt",
2373
+ ".output",
2374
+ ".parcel-cache",
2375
+ ".svelte-kit",
2376
+ ".turbo",
2377
+ ".vercel",
2378
+ "build",
2379
+ "coverage",
2380
+ "dist",
2381
+ "node_modules",
2382
+ "storybook-static"
2383
+ ]);
2384
+ /** Watch-mode defaults, exported so the CLI and docs can quote one source. */
2385
+ const DEFAULT_DEBOUNCE_MS = 300;
2386
+ const DEFAULT_MAX_TASKS = 200;
2387
+ /** How long `start()` waits for the initial filesystem scan before giving up on it. */
2388
+ const READY_TIMEOUT_MS = 1e4;
2389
+ /**
2390
+ * chokidar, loaded on first use.
2391
+ *
2392
+ * Imported lazily so that requiring `@cappa/core` — which the CLI does for
2393
+ * every command, and a plugin does just to get types — never starts a file
2394
+ * watcher's dependency tree for a process that will not watch anything.
2395
+ */
2396
+ const defaultCreateWatcher = async (roots, options) => {
2397
+ const { watch } = await import("chokidar");
2398
+ return watch(roots, {
2399
+ cwd: options.cwd,
2400
+ ignoreInitial: true,
2401
+ ignored: (candidate) => options.ignored(candidate)
2402
+ });
2403
+ };
2404
+ /**
2405
+ * Re-captures affected tasks when files change.
2406
+ *
2407
+ * A scheduler for runs, deliberately not a second orchestrator: every iteration
2408
+ * goes through the engine's ordinary `startRun`, so watch-triggered captures
2409
+ * emit the same events, land in the same run store and honour the same
2410
+ * one-run-at-a-time rule as a capture somebody clicked.
2411
+ *
2412
+ * Two behaviours matter more than they look:
2413
+ *
2414
+ * - **`clearActual` is always false.** Clearing on every save would delete the
2415
+ * diffs the user is looking at for tasks they did not touch.
2416
+ * - **Changes during a run are queued, never rejected.** The engine's single-run
2417
+ * rule stays intact, and the user gets the run they expect rather than a
2418
+ * conflict error they did not cause.
2419
+ */
2420
+ var WatchSession = class {
2421
+ options;
2422
+ cwd;
2423
+ roots;
2424
+ ignoredRoots;
2425
+ debounceMs;
2426
+ maxTasks;
2427
+ now;
2428
+ watcher = null;
2429
+ pending = /* @__PURE__ */ new Set();
2430
+ timer = null;
2431
+ draining = false;
2432
+ stopped = false;
2433
+ startedAt;
2434
+ lastChange;
2435
+ constructor(options) {
2436
+ this.options = options;
2437
+ this.cwd = options.cwd ?? process.cwd();
2438
+ this.debounceMs = options.debounceMs ?? 300;
2439
+ this.maxTasks = options.maxTasks ?? 200;
2440
+ this.now = options.now ?? (() => Date.now());
2441
+ this.roots = resolveRoots(options.paths, options.plugins);
2442
+ this.ignoredRoots = (options.ignoredPaths ?? []).map((entry) => path.resolve(this.cwd, entry));
2443
+ }
2444
+ /** Begin watching. Resolves once the initial scan has settled. */
2445
+ async start() {
2446
+ if (this.watcher) return this.getStatus();
2447
+ const watcher = await (this.options.createWatcher ?? defaultCreateWatcher)(this.roots, {
2448
+ cwd: this.cwd,
2449
+ ignored: (candidate) => this.isIgnored(candidate)
2450
+ });
2451
+ if (this.stopped) {
2452
+ await watcher.close();
2453
+ return this.getStatus();
2454
+ }
2455
+ this.watcher = watcher;
2456
+ watcher.on("all", (event, changedPath) => {
2457
+ if (event !== "add" && event !== "change" && event !== "unlink") return;
2458
+ this.onFileChanged(changedPath);
2459
+ });
2460
+ watcher.on("error", () => {});
2461
+ await this.waitForReady(watcher);
2462
+ this.startedAt = this.now();
2463
+ this.emit({
2464
+ type: "watch:start",
2465
+ paths: this.roots,
2466
+ filter: this.options.filter,
2467
+ debounceMs: this.debounceMs
2468
+ });
2469
+ return this.getStatus();
2470
+ }
2471
+ /**
2472
+ * Stop watching.
2473
+ *
2474
+ * Deliberately does not cancel a run already in flight: that run is the
2475
+ * answer to a save the user made, and killing it half-way leaves `actual/`
2476
+ * holding a partial capture.
2477
+ */
2478
+ async stop(reason = "requested") {
2479
+ if (this.stopped) return;
2480
+ this.stopped = true;
2481
+ if (this.timer) {
2482
+ clearTimeout(this.timer);
2483
+ this.timer = null;
2484
+ }
2485
+ this.pending.clear();
2486
+ const watcher = this.watcher;
2487
+ this.watcher = null;
2488
+ try {
2489
+ await watcher?.close();
2490
+ } finally {
2491
+ this.emit({
2492
+ type: "watch:stop",
2493
+ reason
2494
+ });
2495
+ }
2496
+ }
2497
+ getStatus() {
2498
+ return {
2499
+ active: this.watcher !== null && !this.stopped,
2500
+ paths: this.roots,
2501
+ filter: this.options.filter,
2502
+ debounceMs: this.debounceMs,
2503
+ startedAt: this.startedAt,
2504
+ lastChange: this.lastChange
2505
+ };
2506
+ }
2507
+ emit(event) {
2508
+ this.options.emit?.(event);
2509
+ }
2510
+ async waitForReady(watcher) {
2511
+ await new Promise((resolve) => {
2512
+ let settled = false;
2513
+ const finish = () => {
2514
+ if (settled) return;
2515
+ settled = true;
2516
+ clearTimeout(timer);
2517
+ resolve();
2518
+ };
2519
+ const timer = setTimeout(finish, READY_TIMEOUT_MS);
2520
+ timer.unref?.();
2521
+ watcher.on("ready", finish);
2522
+ watcher.on("error", finish);
2523
+ });
2524
+ }
2525
+ onFileChanged(changedPath) {
2526
+ if (this.stopped) return;
2527
+ this.pending.add(toRelative(this.cwd, changedPath));
2528
+ if (this.timer) clearTimeout(this.timer);
2529
+ const timer = setTimeout(() => {
2530
+ this.timer = null;
2531
+ this.drain();
2532
+ }, this.debounceMs);
2533
+ timer.unref?.();
2534
+ this.timer = timer;
2535
+ }
2536
+ /**
2537
+ * Capture for everything pending, one batch at a time.
2538
+ *
2539
+ * The loop re-reads `pending` after each iteration, which is what turns a
2540
+ * save arriving mid-run into the next iteration rather than into a `409`.
2541
+ */
2542
+ async drain() {
2543
+ if (this.draining) return;
2544
+ this.draining = true;
2545
+ try {
2546
+ while (this.pending.size > 0 && !this.stopped) {
2547
+ const files = [...this.pending].sort();
2548
+ this.pending.clear();
2549
+ await this.captureFor(files);
2550
+ }
2551
+ } finally {
2552
+ this.draining = false;
2553
+ }
2554
+ }
2555
+ async captureFor(files) {
2556
+ const resolution = await this.resolveFiles(files);
2557
+ if (resolution.scope === "none") {
2558
+ this.record({
2559
+ files,
2560
+ scope: "none",
2561
+ taskIds: [],
2562
+ at: this.now()
2563
+ });
2564
+ return;
2565
+ }
2566
+ let runId;
2567
+ let error;
2568
+ try {
2569
+ runId = (await this.options.startRun(resolution.request)).id;
2570
+ } catch (cause) {
2571
+ error = cause instanceof Error ? cause.message : String(cause);
2572
+ }
2573
+ this.record({
2574
+ files,
2575
+ scope: resolution.scope,
2576
+ taskIds: resolution.taskIds,
2577
+ runId,
2578
+ error,
2579
+ at: this.now()
2580
+ });
2581
+ if (runId) await this.options.waitForRun(runId);
2582
+ }
2583
+ record(change) {
2584
+ this.lastChange = change;
2585
+ const { at: _at, ...rest } = change;
2586
+ this.emit({
2587
+ type: "watch:change",
2588
+ ...rest
2589
+ });
2590
+ }
2591
+ /**
2592
+ * Ask every plugin what the changed files affect, and turn the answers into
2593
+ * one run request.
2594
+ */
2595
+ async resolveFiles(files) {
2596
+ const trigger = {
2597
+ source: "watch",
2598
+ files
2599
+ };
2600
+ const everything = {
2601
+ scope: "all",
2602
+ request: {
2603
+ filter: this.options.filter,
2604
+ clearActual: false,
2605
+ trigger
2606
+ }
2607
+ };
2608
+ let tasksByPlugin;
2609
+ try {
2610
+ tasksByPlugin = await this.options.discover();
2611
+ } catch {
2612
+ return everything;
2613
+ }
2614
+ const fullPlugins = /* @__PURE__ */ new Set();
2615
+ const taskIds = /* @__PURE__ */ new Set();
2616
+ for (const plugin of this.options.plugins) {
2617
+ const tasks = tasksByPlugin.get(plugin.name) ?? [];
2618
+ if (!plugin.watch) {
2619
+ fullPlugins.add(plugin.name);
2620
+ continue;
2621
+ }
2622
+ for (const file of files) {
2623
+ let resolved;
2624
+ try {
2625
+ resolved = plugin.watch.resolve(file, tasks);
2626
+ } catch {
2627
+ resolved = null;
2628
+ }
2629
+ if (resolved === null) {
2630
+ fullPlugins.add(plugin.name);
2631
+ break;
2632
+ }
2633
+ for (const id of resolved) taskIds.add(id);
2634
+ }
2635
+ }
2636
+ if (fullPlugins.size === 0) {
2637
+ if (taskIds.size === 0) return {
2638
+ scope: "none",
2639
+ request: {}
2640
+ };
2641
+ return this.byTaskIds([...taskIds], trigger, everything);
2642
+ }
2643
+ if (taskIds.size === 0) return {
2644
+ scope: "plugins",
2645
+ request: {
2646
+ plugins: [...fullPlugins],
2647
+ filter: this.options.filter,
2648
+ clearActual: false,
2649
+ trigger
2650
+ }
2651
+ };
2652
+ const expanded = new Set(taskIds);
2653
+ for (const name of fullPlugins) for (const task of tasksByPlugin.get(name) ?? []) expanded.add(task.id);
2654
+ return this.byTaskIds([...expanded], trigger, everything);
2655
+ }
2656
+ /**
2657
+ * A run of explicit ids, unless there are so many that naming them is
2658
+ * pointless — a branch switch or a formatter pass resolves half the project,
2659
+ * and a filtered full run is both cheaper to express and easier to read.
2660
+ */
2661
+ byTaskIds(taskIds, trigger, everything) {
2662
+ if (taskIds.length > this.maxTasks) return everything;
2663
+ return {
2664
+ scope: "tasks",
2665
+ taskIds,
2666
+ request: {
2667
+ taskIds,
2668
+ filter: this.options.filter,
2669
+ clearActual: false,
2670
+ trigger
2671
+ }
2672
+ };
2673
+ }
2674
+ isIgnored(candidate) {
2675
+ const absolute = path.resolve(this.cwd, candidate);
2676
+ const relative = path.relative(this.cwd, absolute);
2677
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return true;
2678
+ for (const ignored of this.ignoredRoots) if (absolute === ignored || absolute.startsWith(`${ignored}${path.sep}`)) return true;
2679
+ return relative.split(path.sep).some((segment) => DEFAULT_IGNORED_DIRS.has(segment));
2680
+ }
2681
+ };
2682
+ /** The part of a glob before its first magic character — the directory to watch. */
2683
+ const globRoot = (pattern) => {
2684
+ const segments = pattern.split("/");
2685
+ const staticSegments = [];
2686
+ for (const segment of segments) {
2687
+ if (/[*?[\]{}!+@(]/.test(segment)) break;
2688
+ staticSegments.push(segment);
2689
+ }
2690
+ const root = staticSegments.join("/");
2691
+ return root === "" ? "." : root;
2692
+ };
2693
+ /**
2694
+ * What to hand the watcher.
2695
+ *
2696
+ * The project root by default, plus the roots of whatever globs the plugins
2697
+ * declared. Plugin globs can only widen the set: a plugin that maps story files
2698
+ * precisely still has to be told about the component those stories render, and
2699
+ * that component is not in its globs.
2700
+ */
2701
+ const resolveRoots = (paths, plugins) => {
2702
+ const roots = new Set(paths && paths.length > 0 ? paths : ["."]);
2703
+ for (const plugin of plugins) for (const pattern of plugin.watch?.paths ?? []) roots.add(globRoot(pattern));
2704
+ if (roots.has(".")) return ["."];
2705
+ return [...roots];
2706
+ };
2707
+ const toRelative = (cwd, changedPath) => {
2708
+ if (!path.isAbsolute(changedPath)) return changedPath.split(path.sep).join("/");
2709
+ return path.relative(cwd, changedPath).split(path.sep).join("/");
2710
+ };
2711
+ //#endregion
2712
+ //#region src/engine/LocalEngine.ts
2713
+ /**
2714
+ * `CaptureEngine` backed by an in-process Playwright browser.
2715
+ *
2716
+ * Holds the config's live plugin objects, so it must live in the process that
2717
+ * loaded `cappa.config.ts`. The server takes one of these by injection rather
2718
+ * than building it, which is what keeps `@cappa/server` free of config loading
2719
+ * and makes a remote engine a drop-in alternative.
2720
+ *
2721
+ * One run at a time. Queuing is deliberately not implemented: the browser pool
2722
+ * is the real constraint, and a second concurrent run would fight it.
2723
+ */
2724
+ var LocalEngine = class {
2725
+ options;
2726
+ plugins;
2727
+ fileSystem;
2728
+ browser;
2729
+ runs;
2730
+ /**
2731
+ * Set synchronously the moment a run is claimed, before any `await`, so two
2732
+ * concurrent `startRun` calls cannot both pass the check and then fight over
2733
+ * the browser. Covers the window between claiming and the run finishing.
2734
+ */
2735
+ busy = false;
2736
+ activeRunId = null;
2737
+ targetsCache = null;
2738
+ /**
2739
+ * The tasks behind `targetsCache`, kept whole.
2740
+ *
2741
+ * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the
2742
+ * task it came from, `data` included — that is where a story's `importPath`
2743
+ * lives. Same discovery, two shapes, one cache lifetime.
2744
+ */
2745
+ taskCache = null;
2746
+ closed = false;
2747
+ watchSession = null;
2748
+ releaseBrowserHold = null;
2749
+ watchListeners = /* @__PURE__ */ new Set();
2750
+ watchEvents = [];
2751
+ watchSeq = 0;
2752
+ constructor(options) {
2753
+ this.options = options;
2754
+ this.plugins = options.plugins;
2755
+ this.fileSystem = new ScreenshotFileSystem(options.outputDir);
2756
+ this.runs = new RunStore(options.runStore);
2757
+ this.browser = new WarmBrowser({
2758
+ create: options.createScreenshotTool ?? (() => this.buildTool()),
2759
+ idleTimeoutMs: options.browserIdleTimeoutMs
2760
+ });
2761
+ }
2762
+ buildTool() {
2763
+ return new ScreenshotTool({
2764
+ outputDir: this.options.outputDir,
2765
+ diff: this.options.diff,
2766
+ retries: this.options.retries,
2767
+ concurrency: this.options.concurrency,
2768
+ logConsoleEvents: this.options.logConsoleEvents,
2769
+ fullPage: this.options.fullPage ?? true,
2770
+ viewport: this.options.viewport ?? {
2771
+ width: 1920,
2772
+ height: 1080
2773
+ },
2774
+ connectionTimeout: this.options.connectionTimeout
2775
+ });
2776
+ }
2777
+ async listPlugins() {
2778
+ return this.plugins.map((plugin) => ({
2779
+ name: plugin.name,
2780
+ description: plugin.description
2781
+ }));
2782
+ }
2783
+ /**
2784
+ * Discovery needs a browser (plugins query the app under test through it), so
2785
+ * this warms the browser on a cache miss.
2786
+ *
2787
+ * While a run holds the browser, only the cache can be served: discovering
2788
+ * would recycle the very contexts the run is capturing with.
2789
+ */
2790
+ async listTargets(options = {}) {
2791
+ this.assertOpen();
2792
+ if (this.targetsCache && !options.refresh) return this.targetsCache;
2793
+ if (this.busy) {
2794
+ if (this.targetsCache) return this.targetsCache;
2795
+ throw new RunInProgressError(this.activeRunId ?? "starting");
2796
+ }
2797
+ return this.discoverTargets();
2798
+ }
2799
+ async startRun(request = {}) {
2800
+ this.assertOpen();
2801
+ if (this.busy) throw new RunInProgressError(this.activeRunId ?? "starting");
2802
+ this.busy = true;
2803
+ try {
2804
+ await this.validateTaskIds(request);
2805
+ const runner = new CaptureRunner({
2806
+ screenshotTool: await this.browser.acquire(),
2807
+ plugins: this.plugins,
2808
+ outputDir: this.options.outputDir,
2809
+ fileSystem: this.fileSystem
2810
+ });
2811
+ const finish = () => {
2812
+ if (this.activeRunId !== runner.id) return;
2813
+ this.targetsCache = null;
2814
+ this.taskCache = null;
2815
+ this.runs.finalize(runner.id);
2816
+ this.activeRunId = null;
2817
+ this.busy = false;
2818
+ this.browser.release();
2819
+ };
2820
+ runner.on((event) => {
2821
+ if (event.type === "run:complete" || event.type === "run:error") finish();
2822
+ });
2823
+ this.runs.add(runner);
2824
+ this.activeRunId = runner.id;
2825
+ runner.run(request).catch(() => {}).finally(finish);
2826
+ return runner.getSummary();
2827
+ } catch (error) {
2828
+ this.busy = false;
2829
+ this.activeRunId = null;
2830
+ throw error;
2831
+ }
2832
+ }
2833
+ async getRun(id) {
2834
+ return this.runs.get(id);
2835
+ }
2836
+ async listRuns() {
2837
+ return this.runs.list();
2838
+ }
2839
+ async cancelRun(id) {
2840
+ this.runs.getRunner(id)?.abort();
2841
+ }
2842
+ subscribeRun(id, onEvent, options = {}) {
2843
+ return this.runs.subscribe(id, onEvent, options);
2844
+ }
2845
+ /**
2846
+ * Read the screenshot index from disk.
2847
+ *
2848
+ * Always a fresh read rather than a cached snapshot — anything can write to
2849
+ * `outputDir` while the server is up, including a CLI run in another terminal.
2850
+ */
2851
+ async listScreenshots(query = {}) {
2852
+ let screenshots = await collectScreenshots(this.options.outputDir);
2853
+ if (query.category) screenshots = screenshots.filter((screenshot) => screenshot.category === query.category);
2854
+ if (query.search) {
2855
+ const term = query.search.toLowerCase();
2856
+ screenshots = screenshots.filter((screenshot) => screenshot.name.toLowerCase().includes(term));
2857
+ }
2858
+ return screenshots;
2859
+ }
2860
+ async approve(names) {
2861
+ const screenshots = await this.listScreenshots();
2862
+ const approved = [];
2863
+ const errors = [];
2864
+ for (const name of names) {
2865
+ const screenshot = screenshots.find((entry) => entry.name === name);
2866
+ if (!screenshot) {
2867
+ errors.push({
2868
+ name,
2869
+ error: "Screenshot not found"
2870
+ });
2871
+ continue;
2872
+ }
2873
+ try {
2874
+ await this.fileSystem.approveScreenshots([screenshot], this.options.diff ?? { type: "pixel" });
2875
+ approved.push(name);
2876
+ } catch (error) {
2877
+ errors.push({
2878
+ name,
2879
+ error: error instanceof Error ? error.message : "Approval failed"
2880
+ });
2881
+ }
2882
+ }
2883
+ return {
2884
+ approved,
2885
+ errors
2886
+ };
2887
+ }
2888
+ /**
2889
+ * Re-capture affected tasks on file change until `stopWatch`.
2890
+ *
2891
+ * Every iteration goes through `startRun`, so a watch-triggered capture is an
2892
+ * ordinary run: same events, same run store, same single-run rule, visible in
2893
+ * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.
2894
+ */
2895
+ async startWatch(request = {}) {
2896
+ this.assertOpen();
2897
+ if (this.watchSession) throw new WatchInProgressError();
2898
+ const release = this.browser.hold();
2899
+ const session = new WatchSession({
2900
+ plugins: this.plugins,
2901
+ cwd: this.options.cwd,
2902
+ paths: request.paths,
2903
+ ignoredPaths: [this.options.outputDir],
2904
+ filter: request.filter,
2905
+ debounceMs: request.debounceMs,
2906
+ maxTasks: request.maxTasks,
2907
+ createWatcher: this.options.createWatcher,
2908
+ discover: () => this.discoverTasks(),
2909
+ startRun: (runRequest) => this.startRun(runRequest),
2910
+ waitForRun: (runId) => this.waitForRun(runId),
2911
+ emit: (event) => this.emitWatchEvent(event)
2912
+ });
2913
+ this.watchSession = session;
2914
+ this.releaseBrowserHold = release;
2915
+ try {
2916
+ return await session.start();
2917
+ } catch (error) {
2918
+ this.watchSession = null;
2919
+ this.releaseBrowserHold = null;
2920
+ release();
2921
+ throw error;
2922
+ }
2923
+ }
2924
+ async stopWatch() {
2925
+ await this.endWatch("requested");
2926
+ return this.getWatchStatus();
2927
+ }
2928
+ async getWatchStatus() {
2929
+ return this.watchSession?.getStatus() ?? {
2930
+ active: false,
2931
+ paths: [],
2932
+ debounceMs: 300
2933
+ };
2934
+ }
2935
+ subscribeWatch(onEvent, options = {}) {
2936
+ const sinceSeq = options.sinceSeq ?? 0;
2937
+ for (const event of this.watchEvents) if (event.seq > sinceSeq) onEvent(event);
2938
+ this.watchListeners.add(onEvent);
2939
+ return () => {
2940
+ this.watchListeners.delete(onEvent);
2941
+ };
2942
+ }
2943
+ async close() {
2944
+ this.closed = true;
2945
+ await this.endWatch("engine-closed");
2946
+ (this.activeRunId ? this.runs.getRunner(this.activeRunId) : void 0)?.abort();
2947
+ await this.browser.close();
2948
+ }
2949
+ async endWatch(reason) {
2950
+ const session = this.watchSession;
2951
+ const release = this.releaseBrowserHold;
2952
+ this.watchSession = null;
2953
+ this.releaseBrowserHold = null;
2954
+ try {
2955
+ await session?.stop(reason);
2956
+ } finally {
2957
+ release?.();
2958
+ }
2959
+ }
2960
+ emitWatchEvent(event) {
2961
+ this.watchSeq += 1;
2962
+ const full = {
2963
+ ...event,
2964
+ seq: this.watchSeq,
2965
+ at: Date.now()
2966
+ };
2967
+ this.watchEvents.push(full);
2968
+ const max = this.options.maxWatchEvents ?? 200;
2969
+ if (this.watchEvents.length > max) this.watchEvents = this.watchEvents.slice(-max);
2970
+ for (const listener of this.watchListeners) try {
2971
+ listener(full);
2972
+ } catch {}
2973
+ }
2974
+ /** Resolve once a run reaches a terminal event. */
2975
+ waitForRun(id) {
2976
+ return new Promise((resolve) => {
2977
+ let unsubscribe;
2978
+ let finished = false;
2979
+ const finish = () => {
2980
+ if (finished) return;
2981
+ finished = true;
2982
+ unsubscribe?.();
2983
+ resolve();
2984
+ };
2985
+ unsubscribe = this.runs.subscribe(id, (event) => {
2986
+ if (event.type === "run:complete" || event.type === "run:error") finish();
2987
+ });
2988
+ if (finished) unsubscribe();
2989
+ });
2990
+ }
2991
+ /** True while a browser process is alive. Exposed for tests and diagnostics. */
2992
+ get isWarm() {
2993
+ return this.browser.isWarm;
2994
+ }
2995
+ assertOpen() {
2996
+ if (this.closed) throw new Error("Engine has been closed");
2997
+ }
2998
+ /**
2999
+ * A client may only ask for tasks that discovery produced.
3000
+ *
3001
+ * This is a security boundary as much as a correctness one: it is what stops
3002
+ * a request from steering the browser to an arbitrary URL.
3003
+ */
3004
+ async validateTaskIds(request) {
3005
+ if (!request.taskIds || request.taskIds.length === 0) return;
3006
+ const targets = this.targetsCache ?? await this.discoverTargets();
3007
+ const known = new Set(targets.map((target) => target.id));
3008
+ const unknown = request.taskIds.filter((id) => !known.has(id));
3009
+ if (unknown.length > 0) throw new UnknownTargetsError(unknown);
3010
+ }
3011
+ /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */
3012
+ async discoverTasks() {
3013
+ if (this.taskCache) return this.taskCache;
3014
+ await this.discoverTargets();
3015
+ return this.taskCache ?? /* @__PURE__ */ new Map();
3016
+ }
3017
+ async discoverTargets() {
3018
+ const tool = await this.browser.acquire();
3019
+ try {
3020
+ const discovered = await Promise.all(this.plugins.map(async (plugin) => {
3021
+ const tasks = await plugin.discover(tool);
3022
+ return {
3023
+ plugin: plugin.name,
3024
+ tasks
3025
+ };
3026
+ }));
3027
+ this.taskCache = new Map(discovered.map(({ plugin, tasks }) => [plugin, tasks]));
3028
+ this.targetsCache = discovered.flatMap(({ plugin, tasks }) => tasks.map((task) => ({
3029
+ id: task.id,
3030
+ url: task.url,
3031
+ plugin
3032
+ })));
3033
+ return this.targetsCache;
3034
+ } finally {
3035
+ this.browser.release();
3036
+ }
3037
+ }
3038
+ };
3039
+ //#endregion
3040
+ //#region src/store.ts
3041
+ /**
3042
+ * `ScreenshotStore` over the local filesystem, delegating to
3043
+ * `ScreenshotFileSystem` so both views stay consistent.
3044
+ */
3045
+ var FsScreenshotStore = class {
3046
+ fs;
3047
+ constructor(outputDirOrFs) {
3048
+ this.fs = typeof outputDirOrFs === "string" ? new ScreenshotFileSystem(outputDirOrFs) : outputDirOrFs;
3049
+ }
3050
+ dirFor(bucket) {
3051
+ if (bucket === "actual") return this.fs.getActualDir();
3052
+ if (bucket === "expected") return this.fs.getExpectedDir();
3053
+ return this.fs.getDiffDir();
3054
+ }
3055
+ pathFor(bucket, key) {
3056
+ if (bucket === "actual") return this.fs.getActualFilePath(key);
3057
+ if (bucket === "expected") return this.fs.getExpectedFilePath(key);
3058
+ return this.fs.getDiffFilePath(key);
3059
+ }
3060
+ async has(bucket, key) {
3061
+ if (bucket === "expected") return this.fs.hasExpectedFile(key);
3062
+ const fsp = await import("node:fs/promises");
3063
+ try {
3064
+ await fsp.access(this.pathFor(bucket, key));
3065
+ return true;
3066
+ } catch {
3067
+ return false;
3068
+ }
3069
+ }
3070
+ async read(bucket, key) {
3071
+ if (bucket === "expected") return this.fs.readExpectedFile(key);
3072
+ return (await import("node:fs/promises")).readFile(this.pathFor(bucket, key));
3073
+ }
3074
+ async write(bucket, key, data) {
3075
+ if (bucket === "actual") {
3076
+ await this.fs.writeActualFile(key, data);
3077
+ return;
3078
+ }
3079
+ if (bucket === "diff") {
3080
+ await this.fs.writeDiffFile(key, data);
3081
+ return;
3082
+ }
3083
+ const filePath = this.pathFor(bucket, key);
3084
+ await this.fs.ensureParentDir(filePath);
3085
+ await (await import("node:fs/promises")).writeFile(filePath, data);
3086
+ }
3087
+ async list(bucket) {
3088
+ const files = bucket === "actual" ? await this.fs.getActualScreenshots() : bucket === "expected" ? await this.fs.getExpectedScreenshots() : await this.fs.getDiffScreenshots();
3089
+ const dir = this.dirFor(bucket);
3090
+ return files.map((file) => path.relative(dir, file));
3091
+ }
3092
+ async remove(bucket, key) {
3093
+ await (await import("node:fs/promises")).rm(this.pathFor(bucket, key), { force: true });
3094
+ }
3095
+ async clear(bucket) {
3096
+ if (bucket === "actual") {
3097
+ this.fs.clearActual();
3098
+ return;
3099
+ }
3100
+ if (bucket === "diff") {
3101
+ this.fs.clearDiff();
3102
+ return;
3103
+ }
3104
+ throw new Error("Refusing to clear the expected/ bucket: it holds the approved baselines");
3105
+ }
3106
+ async readMeta(key) {
3107
+ const { readDiffMeta } = await Promise.resolve().then(() => filesystem_exports);
3108
+ return readDiffMeta(this.fs.getDiffFilePath(key));
3109
+ }
3110
+ async writeMeta(key, meta) {
3111
+ await this.fs.writeDiffMetaFile(key, meta);
3112
+ }
3113
+ };
3114
+ //#endregion
3115
+ export { CaptureRunner, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_MAX_TASKS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, WarmBrowser, WatchInProgressError, WatchSession, collectScreenshots, compareImages, compareImagesGMSD, defineConfig, didScreenshotFail, filterTasks, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isWatchInProgressError, mapWithConcurrency, mergeCaptureManifest, readCaptureManifest, readDiffMeta, recordCaptureOrigins, sanitizeScreenshotFilename, selectTasks, toDiffMetaPath, toManifestKey, toSerializedError, toTaskStatus };
1253
3116
 
1254
3117
  //# sourceMappingURL=index.mjs.map