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