@cappa/core 0.12.3 → 0.13.0

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