@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.d.cts CHANGED
@@ -1,7 +1,8 @@
1
- import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/core-native";
1
+ import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/interpret-native";
2
2
  import "@blazediff/gmsd";
3
3
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
4
4
  import { Logger } from "@cappa/logger";
5
+ import "@blazediff/core-native";
5
6
  //#region src/compare/pixel.d.ts
6
7
  interface CompareResult$1 {
7
8
  numDiffPixels: number;
@@ -21,7 +22,7 @@ interface CompareResult$1 {
21
22
  * @param options - Comparison options
22
23
  * @returns Comparison result
23
24
  */
24
- declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult$1>;
25
+ export declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult$1>;
25
26
  /**
26
27
  * Quick comparison function that returns only pass/fail
27
28
  * @param image1 - First image (file path or Buffer)
@@ -29,22 +30,22 @@ declare function compareImages(image1: string | Buffer, image2: string | Buffer,
29
30
  * @param options - Comparison options
30
31
  * @returns Whether the images match
31
32
  */
32
- declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
33
+ export declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
33
34
  //#endregion
34
35
  //#region src/filesystem.d.ts
35
36
  /**
36
37
  * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
37
38
  */
38
- declare function toDiffMetaPath(diffImagePath: string): string;
39
+ export declare function toDiffMetaPath(diffImagePath: string): string;
39
40
  /**
40
41
  * Read a diff metadata sidecar, returning `undefined` when it is missing or
41
42
  * cannot be parsed (so callers can degrade gracefully).
42
43
  */
43
- declare function readDiffMeta(diffImagePath: string): Promise<DiffMetadata | undefined>;
44
+ export declare function readDiffMeta(diffImagePath: string): Promise<DiffMetadata | undefined>;
44
45
  /**
45
46
  * Class for interacting with the local file system to store the screenshots.
46
47
  */
47
- declare class ScreenshotFileSystem {
48
+ export declare class ScreenshotFileSystem {
48
49
  private readonly actual;
49
50
  private readonly expected;
50
51
  private readonly diff;
@@ -158,6 +159,219 @@ declare class ScreenshotFileSystem {
158
159
  getRelativePath(directory: "actual" | "expected" | "diff", filePath: string): string;
159
160
  }
160
161
  //#endregion
162
+ //#region src/runner/types.d.ts
163
+ /**
164
+ * Lifecycle of a single capture run.
165
+ *
166
+ * ```
167
+ * idle → discovering → running → (completed | failed | cancelled)
168
+ * ```
169
+ */
170
+ type RunState = "idle" | "discovering" | "running" | "completed" | "failed" | "cancelled";
171
+ /**
172
+ * Terminal state of an individual capture task.
173
+ *
174
+ * `passed` / `changed` / `new` mirror the screenshot categories; `failed` means
175
+ * the plugin reported a failure (see `didScreenshotFail`); `skipped` means the
176
+ * plugin deliberately skipped the task.
177
+ */
178
+ type TaskStatus = "pending" | "running" | "passed" | "changed" | "new" | "failed" | "skipped";
179
+ /** A discovered, runnable capture task together with the plugin that owns it. */
180
+ type Target = {
181
+ id: string;
182
+ url: string;
183
+ plugin: string;
184
+ };
185
+ /**
186
+ * Why a run was started, when it was not started by hand.
187
+ *
188
+ * Purely informational — the runner does nothing with it. It rides along on the
189
+ * request so a run list can say "this one came from saving Button.stories.tsx"
190
+ * without a second lookup or a parallel event stream.
191
+ */
192
+ type RunTrigger = {
193
+ source: "watch";
194
+ /** Changed files that triggered the run, relative to the watch root. */
195
+ files: string[];
196
+ };
197
+ /**
198
+ * Describes which subset of the discovered tasks a run should capture.
199
+ *
200
+ * `filter` and `taskIds` compose: a task must satisfy both when both are given.
201
+ */
202
+ type StartRunRequest = {
203
+ /** Restrict the run to these plugin names. Omit to run every plugin. */
204
+ plugins?: string[];
205
+ /** Glob matched against task ids (`path.matchesGlob` semantics). */
206
+ filter?: string;
207
+ /** Explicit task ids to capture. Ids not discovered are ignored. */
208
+ taskIds?: string[];
209
+ /**
210
+ * Clear `actual/` and `diff/` before capturing.
211
+ *
212
+ * Always `true` for a full CLI run. A UI re-capturing a single screenshot must
213
+ * pass `false`, otherwise the rest of the run's output is destroyed.
214
+ * @default true
215
+ */
216
+ clearActual?: boolean;
217
+ /** What started this run, when it was not a person. */
218
+ trigger?: RunTrigger;
219
+ };
220
+ /** An error flattened into something that survives a structured-clone or JSON. */
221
+ type SerializedError = {
222
+ name: string;
223
+ message: string;
224
+ stack?: string;
225
+ };
226
+ export declare const toSerializedError: (error: unknown) => SerializedError;
227
+ /**
228
+ * The shape plugins return from `execute`. Every field is optional because
229
+ * plugins are free to return whatever they want — only these keys are
230
+ * interpreted (by `didScreenshotFail`) and surfaced in failure reports.
231
+ */
232
+ type PluginCaptureResult = {
233
+ success?: boolean;
234
+ skipped?: boolean;
235
+ isNew?: boolean;
236
+ error?: unknown;
237
+ filepath?: string;
238
+ storyId?: string;
239
+ storyName?: string;
240
+ [key: string]: unknown;
241
+ };
242
+ /** A task that did not produce a passing screenshot. */
243
+ type TaskFailure = {
244
+ taskId: string;
245
+ taskUrl: string;
246
+ pluginName: string;
247
+ result: PluginCaptureResult;
248
+ };
249
+ /** Per-task record kept for the lifetime of a run. */
250
+ type TaskRecord = {
251
+ id: string;
252
+ url: string;
253
+ plugin: string;
254
+ status: TaskStatus;
255
+ durationMs?: number;
256
+ result?: PluginCaptureResult;
257
+ };
258
+ /** Coarse, serializable view of a run — enough to render a list row. */
259
+ type RunSummary = {
260
+ id: string;
261
+ state: RunState;
262
+ request: StartRunRequest;
263
+ startedAt: number;
264
+ finishedAt?: number;
265
+ durationMs?: number;
266
+ totalTasks: number;
267
+ completedTasks: number;
268
+ failedTasks: number;
269
+ /** Baselines in `expected/` with no matching `actual/` after the run. */
270
+ deletedScreenshots: string[];
271
+ /** `false` when discovery produced nothing (or everything was filtered out). */
272
+ anyTasksRan: boolean;
273
+ error?: SerializedError;
274
+ };
275
+ /** Full run view, including every task and failure. */
276
+ type RunDetail = RunSummary & {
277
+ tasks: TaskRecord[];
278
+ failures: TaskFailure[];
279
+ };
280
+ /**
281
+ * Levels the run event stream can carry.
282
+ *
283
+ * `success` is here because `ScreenshotTool` uses it — "Screenshot saved",
284
+ * "Screenshot passed visual comparison" — and those lines have to reach a
285
+ * remote client, not just the host's own terminal. Adding a level is a wire
286
+ * change: this one lands before `PROTOCOL_VERSION` 1 has ever been published,
287
+ * so it is part of what v1 will be. A later addition needs a version bump.
288
+ */
289
+ type RunLogLevel = "debug" | "info" | "warn" | "error" | "success";
290
+ type RunEventBase = {
291
+ /** Monotonic, 1-based, per run. Used for SSE `Last-Event-ID` replay. */
292
+ seq: number;
293
+ runId: string;
294
+ at: number;
295
+ };
296
+ /**
297
+ * Everything an observer needs to follow a run. Emitted synchronously, so a
298
+ * consumer forwarding these to a logger keeps ordering with logs written
299
+ * directly by `ScreenshotTool`.
300
+ */
301
+ type RunEvent = (RunEventBase & {
302
+ type: "run:start";
303
+ request: StartRunRequest;
304
+ }) | (RunEventBase & {
305
+ type: "discover:start";
306
+ plugins: string[];
307
+ }) | (RunEventBase & {
308
+ type: "discover:plugin";
309
+ plugin: string;
310
+ taskCount: number;
311
+ }) | (RunEventBase & {
312
+ type: "discover:complete";
313
+ targets: Target[];
314
+ totalTasks: number;
315
+ }) | (RunEventBase & {
316
+ type: "filter:applied";
317
+ filter?: string;
318
+ taskIds?: string[];
319
+ plugins: {
320
+ plugin: string;
321
+ before: number;
322
+ after: number;
323
+ }[];
324
+ }) | (RunEventBase & {
325
+ type: "plugin:start";
326
+ plugin: string;
327
+ taskCount: number;
328
+ }) | (RunEventBase & {
329
+ type: "task:start";
330
+ plugin: string;
331
+ taskId: string;
332
+ url: string;
333
+ }) | (RunEventBase & {
334
+ type: "task:complete";
335
+ plugin: string;
336
+ taskId: string;
337
+ url: string;
338
+ status: TaskStatus;
339
+ completed: number;
340
+ total: number;
341
+ durationMs: number;
342
+ result?: PluginCaptureResult;
343
+ }) | (RunEventBase & {
344
+ type: "plugin:complete";
345
+ plugin: string;
346
+ resultCount: number;
347
+ failed: boolean;
348
+ }) | (RunEventBase & {
349
+ type: "log";
350
+ level: RunLogLevel;
351
+ message: string;
352
+ args: unknown[];
353
+ }) | (RunEventBase & {
354
+ type: "run:complete";
355
+ summary: RunSummary;
356
+ }) | (RunEventBase & {
357
+ type: "run:error";
358
+ error: SerializedError;
359
+ }) | (RunEventBase & {
360
+ type: "run:cancelled";
361
+ });
362
+ type RunEventType = RunEvent["type"];
363
+ type RunEventListener = (event: RunEvent) => void;
364
+ /** Plugin shape the runner needs. Kept structural so tests can pass fakes. */
365
+ type RunnablePlugin = {
366
+ name: string;
367
+ description?: string;
368
+ discover: (screenshotTool: any) => Promise<PluginTask[]>;
369
+ execute: (task: PluginTask, page: any, screenshotTool: any, context: any) => Promise<unknown>;
370
+ initPage?: (page: any, screenshotTool: any) => Promise<unknown>;
371
+ /** How this plugin maps a changed file onto tasks. Absent means "cannot". */
372
+ watch?: PluginWatch;
373
+ };
374
+ //#endregion
161
375
  //#region src/screenshot.d.ts
162
376
  interface ScreenshotCaptureDetails {
163
377
  filename: string;
@@ -206,6 +420,18 @@ interface ScreenshotCaptureExtras {
206
420
  */
207
421
  captureStart?: number;
208
422
  }
423
+ /** The logger surface `ScreenshotTool` actually uses. */
424
+ type ScreenshotLogger = Pick<Logger, "debug" | "info" | "warn" | "error" | "success">;
425
+ /** Receives this tool's log output instead of the global logger. */
426
+ type ScreenshotLogSink = (level: RunLogLevel, message: string, ...args: unknown[]) => void;
427
+ /**
428
+ * Notified whenever this tool writes a screenshot.
429
+ *
430
+ * `page` identifies the caller: a run captures several tasks in parallel, one
431
+ * per pooled page, so the page is the only thing that ties a filename back to
432
+ * the task that asked for it.
433
+ */
434
+ type ScreenshotCaptureSink = (page: Page, filename: string) => void;
209
435
  declare class ScreenshotTool {
210
436
  browserType: "chromium" | "firefox" | "webkit";
211
437
  headless: boolean;
@@ -222,11 +448,23 @@ declare class ScreenshotTool {
222
448
  contexts: BrowserContext[];
223
449
  pages: Page[];
224
450
  diff: DiffOptions;
225
- logger: Logger;
451
+ /**
452
+ * Where this tool's own output goes.
453
+ *
454
+ * Normally the global logger. While a `CaptureRunner` owns the tool it is
455
+ * swapped for a shim that forwards into the run's event stream instead — see
456
+ * `setLogSink`.
457
+ */
458
+ logger: ScreenshotLogger;
226
459
  retries: number;
227
460
  filesystem: ScreenshotFileSystem;
228
461
  logConsoleEvents: boolean;
229
462
  connectionTimeout: number;
463
+ private defaultUserAgent;
464
+ /** The real logger, kept so `setLogSink(null)` restores the same instance. */
465
+ private readonly baseLogger;
466
+ /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
467
+ private captureSink;
230
468
  constructor(options: {
231
469
  browserType?: "chromium" | "firefox" | "webkit";
232
470
  headless?: boolean;
@@ -242,15 +480,64 @@ declare class ScreenshotTool {
242
480
  logConsoleEvents?: boolean;
243
481
  connectionTimeout?: number;
244
482
  });
483
+ /**
484
+ * Send this tool's own log output to `sink` instead of the global logger.
485
+ *
486
+ * `ScreenshotTool` writes lines a user expects to see — "Screenshot saved",
487
+ * "Screenshot passed visual comparison", the retry warnings — straight to the
488
+ * logger. That is fine in-process and useless over a network: with the
489
+ * browser on another machine those lines would stay in the *host's* terminal
490
+ * while the client showed a run with no commentary. A `CaptureRunner` installs
491
+ * a sink for the duration of a run so they travel as `log` events instead.
492
+ *
493
+ * Pass `null` to restore the real logger.
494
+ */
495
+ setLogSink(sink: ScreenshotLogSink | null): void;
496
+ /**
497
+ * Report every screenshot this tool writes to `sink`.
498
+ *
499
+ * A `CaptureRunner` installs one for the duration of a run so it can record
500
+ * which task produced which file. Nothing else can know: a plugin picks the
501
+ * filename inside `execute` and is free to derive it from the task however
502
+ * it likes, so the only reliable observation point is the write itself —
503
+ * which also catches variants, whose filenames the plugin never states.
504
+ *
505
+ * Pass `null` to stop reporting.
506
+ */
507
+ setCaptureSink(sink: ScreenshotCaptureSink | null): void;
245
508
  private resolveDiffOptions;
246
509
  private mergeDiffOptions;
247
510
  /**
248
511
  * Initialize playwright and page
249
512
  */
250
513
  init(): Promise<void>;
514
+ /**
515
+ * Create the pool of browser contexts and pages.
516
+ */
517
+ private createContexts;
518
+ /**
519
+ * Closes every context and page, leaving the browser process running.
520
+ */
521
+ closeContexts(): Promise<void>;
522
+ /**
523
+ * Throw away the current contexts and build a fresh pool on the same browser.
524
+ *
525
+ * A long-lived process that keeps the browser warm between capture runs must
526
+ * call this first: contexts accumulate cookies, storage and scroll position,
527
+ * and a screenshot taken against leaked state is not the screenshot the CLI
528
+ * would have taken with a fresh browser.
529
+ */
530
+ recycleContexts(): Promise<void>;
251
531
  /**
252
532
  * Closes browser
253
533
  * If not closed, the process will not exit
534
+ *
535
+ * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is
536
+ * delivered to the whole foreground process group, Chromium included, so by
537
+ * the time a signal handler gets here every context can already be dead and
538
+ * closing one throws `Failed to find context with id …`. Letting that escape
539
+ * turns a clean shutdown into an uncaught exception, which is the one thing
540
+ * teardown must never do.
254
541
  */
255
542
  close(): Promise<void>;
256
543
  /**
@@ -324,6 +611,37 @@ type PluginTask<TData = any> = {
324
611
  * Plugin function type definition (legacy)
325
612
  */
326
613
  type PluginFunction = (screenshotTool: ScreenshotTool) => Promise<any[]>;
614
+ /**
615
+ * Map a changed file onto the tasks it affects.
616
+ *
617
+ * Called once per changed file, for every file a watch session sees — not only
618
+ * for files matching `PluginWatch.paths`, which exist to widen what is watched
619
+ * rather than to narrow what is asked. A plugin that recognises the file
620
+ * answers with task ids; one that does not answers `null`.
621
+ *
622
+ * @returns the affected task ids, or `null` for "cannot tell" — which re-runs
623
+ * everything this plugin owns. `null` is the honest answer whenever the mapping
624
+ * is uncertain: a resolve that names too few tasks produces a watch mode that
625
+ * silently misses regressions, which is worse than one that re-runs too much.
626
+ */
627
+ type PluginWatchResolve<TData = any> = (file: string, tasks: PluginTask<TData>[]) => string[] | null;
628
+ /**
629
+ * How a plugin participates in watch mode.
630
+ *
631
+ * Optional on `PluginDef`: a plugin without it contributes its whole task set
632
+ * whenever anything in the watch set changes, which is correct for plugins
633
+ * whose tasks have no local source at all (`@cappa/plugin-pages` captures URLs
634
+ * behind a dev server it knows nothing about).
635
+ */
636
+ type PluginWatch<TData = any> = {
637
+ /**
638
+ * Extra globs, relative to the working directory, added to what the watch
639
+ * session watches. Sources this plugin can map precisely belong here — the
640
+ * session watches the project either way, so these only ever widen the set.
641
+ */
642
+ paths: string[];
643
+ resolve: PluginWatchResolve<TData>;
644
+ };
327
645
  /**
328
646
  * Plugin definition interface
329
647
  */
@@ -333,6 +651,11 @@ type PluginDef<TResult = any, TContext = any, TData = any> = {
333
651
  discover: (screenshotTool: ScreenshotTool) => Promise<PluginTask<TData>[]>;
334
652
  execute: (task: PluginTask<TData>, page: Page, screenshotTool: ScreenshotTool, context: TContext) => Promise<TResult>;
335
653
  initPage?: (page: Page, screenshotTool: ScreenshotTool) => Promise<TContext>;
654
+ /**
655
+ * Optional: how this plugin maps changed files onto tasks, for
656
+ * `cappa capture --watch` and the review UI's watch toggle.
657
+ */
658
+ watch?: PluginWatch<TData>;
336
659
  };
337
660
  /**
338
661
  * Plugin function type definition
@@ -524,6 +847,18 @@ type UserConfig = {
524
847
  * @default 3000
525
848
  */
526
849
  port?: number;
850
+ /**
851
+ * How long the browser stays warm between captures started from the UI,
852
+ * in milliseconds.
853
+ *
854
+ * Keeping it alive makes an interactive capture feel immediate instead of
855
+ * paying browser startup on every click; evicting it when idle stops a
856
+ * forgotten review session holding a browser process indefinitely. Set to
857
+ * `0` to shut the browser down after every run.
858
+ *
859
+ * @default 300000 (5 minutes)
860
+ */
861
+ browserIdleTimeout?: number;
527
862
  };
528
863
  };
529
864
  type Viewport = {
@@ -595,6 +930,21 @@ type Screenshot = {
595
930
  id: string;
596
931
  name: string;
597
932
  approved?: boolean;
933
+ /**
934
+ * The capture task that produced this screenshot, read back from the capture
935
+ * manifest.
936
+ *
937
+ * A screenshot's name is a filename a plugin chose; a task id is that
938
+ * plugin's own address for the thing it captured, and the two are unrelated
939
+ * (Storybook writes `example/button/primary` for task
940
+ * `example-button--primary`). Only a run can record the link, so this is
941
+ * absent for anything captured before the manifest existed — a consumer that
942
+ * needs a task id, such as re-capturing a single screenshot, must handle it
943
+ * being missing rather than falling back to `name`.
944
+ */
945
+ taskId?: string;
946
+ /** Plugin that owns `taskId`. Absent whenever `taskId` is. */
947
+ plugin?: string;
598
948
  } & (NewScreenshot | DeletedScreenshot | ChangedScreenshot | PassedScreenshot);
599
949
  type FailedScreenshot = Screenshot & {
600
950
  /**
@@ -626,7 +976,7 @@ interface CompareResult {
626
976
  * @param options - Comparison options
627
977
  * @returns Comparison result
628
978
  */
629
- declare function compareImagesGMSD(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfigGMSD): Promise<CompareResult>;
979
+ export declare function compareImagesGMSD(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfigGMSD): Promise<CompareResult>;
630
980
  /**
631
981
  * Quick comparison function that returns only pass/fail
632
982
  * @param image1 - First image (file path or Buffer)
@@ -634,13 +984,705 @@ declare function compareImagesGMSD(image1: string | Buffer, image2: string | Buf
634
984
  * @param options - Comparison options
635
985
  * @returns Whether the images match
636
986
  */
637
- declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffer, options?: DiffConfigGMSD): Promise<boolean>;
987
+ export declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffer, options?: DiffConfigGMSD): Promise<boolean>;
638
988
  //#endregion
639
989
  //#region src/config.d.ts
640
990
  /**
641
991
  * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
642
992
  */
643
- declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
993
+ export declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
994
+ //#endregion
995
+ //#region src/runner/CaptureRunner.d.ts
996
+ type CaptureRunnerOptions = {
997
+ /**
998
+ * An **already initialised** `ScreenshotTool`. The runner never calls `init()`
999
+ * or `close()` — browser lifetime belongs to the caller, so a long-lived
1000
+ * server can keep one browser warm across many runs while the CLI can keep
1001
+ * its init/close-per-run shape.
1002
+ */
1003
+ screenshotTool: ScreenshotTool;
1004
+ plugins: RunnablePlugin[];
1005
+ /** Defaults to the screenshot tool's output directory. */
1006
+ outputDir?: string;
1007
+ /**
1008
+ * Filesystem used to clear `actual/` and `diff/`. Defaults to the screenshot
1009
+ * tool's own instance, falling back to one built from `outputDir`.
1010
+ */
1011
+ fileSystem?: ScreenshotFileSystem;
1012
+ /** Stable run id. Generated when omitted. */
1013
+ id?: string;
1014
+ /** Injectable clock, for deterministic tests. */
1015
+ now?: () => number;
1016
+ };
1017
+ /**
1018
+ * Orchestrates a single capture run: discover → filter → execute, emitting
1019
+ * typed events as it goes.
1020
+ *
1021
+ * Deliberately free of any presentation or process concerns — no logger calls,
1022
+ * no `chalk`, no `process.exit`. Consumers render the events however they like:
1023
+ * the CLI writes them to the terminal, the server streams them over SSE.
1024
+ *
1025
+ * One instance represents one run. Create a new one per run.
1026
+ */
1027
+ export declare class CaptureRunner {
1028
+ readonly id: string;
1029
+ private readonly screenshotTool;
1030
+ private readonly plugins;
1031
+ private readonly outputDir;
1032
+ private readonly fileSystem;
1033
+ private readonly now;
1034
+ private readonly listeners;
1035
+ private readonly controller;
1036
+ private seq;
1037
+ private state;
1038
+ private request;
1039
+ private startedAt;
1040
+ private finishedAt;
1041
+ private error;
1042
+ private anyTasksRan;
1043
+ private deletedScreenshots;
1044
+ private readonly taskRecords;
1045
+ private readonly failures;
1046
+ private started;
1047
+ /**
1048
+ * Which task currently owns each pooled page.
1049
+ *
1050
+ * Tasks run concurrently, one per page, so the page is what disambiguates
1051
+ * the capture sink's reports. Populated only while a task is executing.
1052
+ */
1053
+ private readonly taskByPage;
1054
+ /** Screenshot name → the task that captured it, for the capture manifest. */
1055
+ private readonly capturedOrigins;
1056
+ constructor(options: CaptureRunnerOptions);
1057
+ /** Subscribe to run events. Returns an unsubscribe function. */
1058
+ on(listener: RunEventListener): () => void;
1059
+ get signal(): AbortSignal;
1060
+ /**
1061
+ * Request cancellation. In-flight tasks finish (Playwright gives us no safe
1062
+ * mid-screenshot abort), but no further tasks are started.
1063
+ */
1064
+ abort(): void;
1065
+ getSummary(): RunSummary;
1066
+ getDetail(): RunDetail;
1067
+ /**
1068
+ * Whether the run produced at least one failing screenshot or detected a
1069
+ * deleted baseline — the condition the CLI exits non-zero on.
1070
+ */
1071
+ get hasScreenshotFailure(): boolean;
1072
+ private emit;
1073
+ private log;
1074
+ /**
1075
+ * Run the capture. Resolves with the final detail; rejects if a plugin threw,
1076
+ * after emitting `run:error`.
1077
+ */
1078
+ run(request?: StartRunRequest): Promise<RunDetail>;
1079
+ /**
1080
+ * Route `ScreenshotTool`'s log output through this run's events.
1081
+ *
1082
+ * Guarded rather than called outright: tests inject minimal stand-ins for the
1083
+ * tool, and a fake without the method should not fail a run.
1084
+ */
1085
+ private attachToolLogSink;
1086
+ private detachToolLogSink;
1087
+ /**
1088
+ * Record which task produces which screenshot file.
1089
+ *
1090
+ * Guarded like the log sink: tests inject minimal tool stand-ins, and one
1091
+ * without the method must not fail a run — it only loses the manifest.
1092
+ */
1093
+ private attachToolCaptureSink;
1094
+ private detachToolCaptureSink;
1095
+ /**
1096
+ * Write what this run learned about screenshot origins.
1097
+ *
1098
+ * Idempotent, because it is called once on the happy path and again from
1099
+ * `run`'s `finally` for the paths that never reach it. Existing entries are
1100
+ * preserved and only names that no longer exist on disk are dropped, so a
1101
+ * run of one task does not erase every other screenshot's origin.
1102
+ */
1103
+ private persistCaptureOrigins;
1104
+ private discover;
1105
+ private execute;
1106
+ private collectDeleted;
1107
+ }
1108
+ //#endregion
1109
+ //#region src/engine/RunStore.d.ts
1110
+ type RunStoreOptions = {
1111
+ /**
1112
+ * Events buffered per run, for replay to a (re)connecting subscriber.
1113
+ * @default 5000
1114
+ */
1115
+ maxEventsPerRun?: number;
1116
+ /**
1117
+ * Finished runs kept in memory. Oldest are dropped first.
1118
+ * @default 20
1119
+ */
1120
+ maxRuns?: number;
1121
+ };
1122
+ /**
1123
+ * In-memory registry of capture runs and their event history.
1124
+ *
1125
+ * The event buffer is what lets an SSE client reconnect without losing
1126
+ * anything: subscribers replay from the last `seq` they saw before live
1127
+ * delivery starts.
1128
+ */
1129
+ export declare class RunStore {
1130
+ private readonly maxEventsPerRun;
1131
+ private readonly maxRuns;
1132
+ private readonly runs;
1133
+ /** Insertion order, oldest first — the eviction queue. */
1134
+ private readonly order;
1135
+ constructor(options?: RunStoreOptions);
1136
+ /** Register a runner and start buffering its events. */
1137
+ add(runner: CaptureRunner): void;
1138
+ /**
1139
+ * Freeze the final detail of a finished run so it stays queryable after the
1140
+ * runner is discarded.
1141
+ */
1142
+ finalize(runId: string): void;
1143
+ get(runId: string): RunDetail | undefined;
1144
+ getRunner(runId: string): CaptureRunner | undefined;
1145
+ /** Newest first. */
1146
+ list(): RunSummary[];
1147
+ /**
1148
+ * Subscribe to a run, replaying buffered events first.
1149
+ *
1150
+ * Replay is synchronous, so a subscriber cannot miss events that arrive
1151
+ * between the buffer read and the listener being registered.
1152
+ */
1153
+ subscribe(runId: string, onEvent: (event: RunEvent) => void, options?: {
1154
+ sinceSeq?: number;
1155
+ }): () => void;
1156
+ /** How many events were dropped from a run's buffer (0 when none were). */
1157
+ droppedEvents(runId: string): number;
1158
+ private evictOldRuns;
1159
+ }
1160
+ //#endregion
1161
+ //#region src/engine/types.d.ts
1162
+ type PluginInfo = {
1163
+ name: string;
1164
+ description?: string;
1165
+ };
1166
+ type ScreenshotQuery = {
1167
+ search?: string;
1168
+ category?: Screenshot["category"];
1169
+ };
1170
+ type ApproveResult = {
1171
+ approved: string[];
1172
+ errors: {
1173
+ name: string;
1174
+ error: string;
1175
+ }[];
1176
+ };
1177
+ type ListTargetsOptions = {
1178
+ /** Re-run plugin discovery instead of serving the cached target list. */
1179
+ refresh?: boolean;
1180
+ };
1181
+ type SubscribeOptions = {
1182
+ /**
1183
+ * Replay buffered events with `seq > sinceSeq` before streaming live ones.
1184
+ * This is what makes a dropped SSE connection invisible to the client.
1185
+ */
1186
+ sinceSeq?: number;
1187
+ };
1188
+ /**
1189
+ * How a watch iteration decided what to capture.
1190
+ *
1191
+ * - `tasks` — an explicit set of task ids, resolved by the plugins.
1192
+ * - `plugins` — every task of one or more plugins, because at least one could
1193
+ * not attribute the change (or ships no `watch` at all).
1194
+ * - `all` — everything under the session's filter: the resolved set was larger
1195
+ * than the cap, or discovery itself failed.
1196
+ * - `none` — nothing to capture.
1197
+ */
1198
+ type WatchScope = "tasks" | "plugins" | "all" | "none";
1199
+ /** What one settled batch of file changes led to. */
1200
+ type WatchChange = {
1201
+ /** Changed files, relative to the watch root. */
1202
+ files: string[];
1203
+ scope: WatchScope;
1204
+ /** Resolved task ids, when the scope is `tasks`. */
1205
+ taskIds?: string[];
1206
+ /** The run the change started, absent when none could be started. */
1207
+ runId?: string;
1208
+ /** Why no run was started, when that is what happened. */
1209
+ error?: string;
1210
+ at: number;
1211
+ };
1212
+ type WatchEventBase = {
1213
+ /** Monotonic, 1-based, per engine. Used for replay, like run events. */
1214
+ seq: number;
1215
+ at: number;
1216
+ };
1217
+ /**
1218
+ * The watch event stream.
1219
+ *
1220
+ * Separate from `RunEvent` because these events belong to a session that
1221
+ * outlives any single run — a watch session is a scheduler for runs, and the
1222
+ * runs it starts report themselves through the ordinary run stream.
1223
+ */
1224
+ type WatchEvent = (WatchEventBase & {
1225
+ type: "watch:start";
1226
+ paths: string[];
1227
+ filter?: string;
1228
+ debounceMs: number;
1229
+ }) | (WatchEventBase & {
1230
+ type: "watch:change";
1231
+ } & Omit<WatchChange, "at">) | (WatchEventBase & {
1232
+ type: "watch:stop";
1233
+ reason: "requested" | "engine-closed";
1234
+ });
1235
+ type WatchEventType = WatchEvent["type"];
1236
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
1237
+ /** A watch event before the engine stamps it with `seq` and `at`. */
1238
+ type EmittableWatchEvent = DistributiveOmit<WatchEvent, "seq" | "at">;
1239
+ /** What a watch session is doing, readable at any time. */
1240
+ type WatchStatus = {
1241
+ active: boolean;
1242
+ /** Roots being watched, relative to the working directory. */
1243
+ paths: string[];
1244
+ filter?: string;
1245
+ debounceMs: number;
1246
+ startedAt?: number;
1247
+ /** The most recent settled batch of changes, when there has been one. */
1248
+ lastChange?: WatchChange;
1249
+ };
1250
+ /** Options for `startWatch`. */
1251
+ type StartWatchRequest = {
1252
+ /**
1253
+ * Directories to watch, relative to the working directory.
1254
+ * @default ["."]
1255
+ */
1256
+ paths?: string[];
1257
+ /** Glob every watch-triggered run is restricted to (`path.matchesGlob`). */
1258
+ filter?: string;
1259
+ /**
1260
+ * How long changes must settle before a run starts.
1261
+ * @default 300
1262
+ */
1263
+ debounceMs?: number;
1264
+ /**
1265
+ * Above this many resolved task ids, capture everything under `filter`
1266
+ * instead. A branch switch is what this guards against.
1267
+ * @default 200
1268
+ */
1269
+ maxTasks?: number;
1270
+ };
1271
+ /**
1272
+ * Everything a UI needs to drive and observe captures.
1273
+ *
1274
+ * There are two implementations: `LocalEngine` runs the browser in-process, and
1275
+ * (later) a remote engine speaks HTTP + SSE to a server that does. The UI only
1276
+ * ever holds this interface, so moving the browser to another machine is a
1277
+ * different implementation rather than a rewrite.
1278
+ *
1279
+ * That is only true if the interface stays serializable: **no `Page`, `Browser`,
1280
+ * or plugin object may cross it** — arguments and return values must survive a
1281
+ * JSON round-trip. Plugins are live closures from `cappa.config.ts` and cannot
1282
+ * be sent anywhere; whichever process holds the engine is the one that loaded
1283
+ * the config.
1284
+ */
1285
+ interface CaptureEngine {
1286
+ /** Plugins this engine can run. */
1287
+ listPlugins(): Promise<PluginInfo[]>;
1288
+ /** Discovered, runnable tasks. Cached until `refresh` is requested. */
1289
+ listTargets(options?: ListTargetsOptions): Promise<Target[]>;
1290
+ /**
1291
+ * Start a capture. Resolves as soon as the run is registered — progress
1292
+ * arrives through `subscribeRun`.
1293
+ *
1294
+ * @throws {RunInProgressError} when a run is already active.
1295
+ */
1296
+ startRun(request?: StartRunRequest): Promise<RunSummary>;
1297
+ getRun(id: string): Promise<RunDetail | undefined>;
1298
+ /** Newest first. */
1299
+ listRuns(): Promise<RunSummary[]>;
1300
+ cancelRun(id: string): Promise<void>;
1301
+ /**
1302
+ * Observe a run. Returns an unsubscribe function.
1303
+ *
1304
+ * Buffered events are replayed synchronously before live delivery begins, so
1305
+ * a subscriber that attaches after `startRun` still sees the whole run.
1306
+ */
1307
+ subscribeRun(id: string, onEvent: (event: RunEvent) => void, options?: SubscribeOptions): () => void;
1308
+ listScreenshots(query?: ScreenshotQuery): Promise<Screenshot[]>;
1309
+ approve(names: string[]): Promise<ApproveResult>;
1310
+ /**
1311
+ * Re-capture on file change until `stopWatch`.
1312
+ *
1313
+ * Optional, because only an engine that can see the files is able to do it:
1314
+ * a remote engine drives the watcher on the *host*, and an engine with no
1315
+ * local filesystem at all has nothing to offer. Callers must feature-detect
1316
+ * rather than assume.
1317
+ *
1318
+ * @throws {WatchInProgressError} when a session is already active.
1319
+ */
1320
+ startWatch?(request?: StartWatchRequest): Promise<WatchStatus>;
1321
+ /**
1322
+ * Stop the active watch session and answer the status it left behind.
1323
+ *
1324
+ * A no-op when there is none — the status simply says it is inactive.
1325
+ */
1326
+ stopWatch?(): Promise<WatchStatus>;
1327
+ /** What the watch session is doing, or an inactive status when there is none. */
1328
+ getWatchStatus?(): Promise<WatchStatus>;
1329
+ /**
1330
+ * Observe the watch event stream. Returns an unsubscribe function.
1331
+ *
1332
+ * Buffered events are replayed synchronously before live delivery, exactly
1333
+ * as `subscribeRun` does.
1334
+ */
1335
+ subscribeWatch?(onEvent: (event: WatchEvent) => void, options?: SubscribeOptions): () => void;
1336
+ /** Release resources (browser, timers). Safe to call more than once. */
1337
+ close(): Promise<void>;
1338
+ }
1339
+ /**
1340
+ * Stable discriminators for engine errors.
1341
+ *
1342
+ * These exist because `instanceof` is not reliable across the package
1343
+ * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the
1344
+ * CLI binary) and an ESM one (the server) each load their own copy of these
1345
+ * classes: an error thrown by one is not an `instanceof` the other's class,
1346
+ * and the check silently fails — turning a 409 into a 500. Callers must use
1347
+ * the guards below rather than `instanceof`.
1348
+ */
1349
+ export declare const ENGINE_ERROR_CODES: {
1350
+ readonly runInProgress: "CAPPA_RUN_IN_PROGRESS";
1351
+ readonly unknownTargets: "CAPPA_UNKNOWN_TARGETS";
1352
+ readonly watchInProgress: "CAPPA_WATCH_IN_PROGRESS";
1353
+ };
1354
+ /** Thrown by `startRun` when the engine is already running something. */
1355
+ export declare class RunInProgressError extends Error {
1356
+ readonly code: "CAPPA_RUN_IN_PROGRESS";
1357
+ readonly activeRunId: string;
1358
+ constructor(activeRunId: string);
1359
+ }
1360
+ /** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */
1361
+ export declare class UnknownTargetsError extends Error {
1362
+ readonly code: "CAPPA_UNKNOWN_TARGETS";
1363
+ readonly taskIds: string[];
1364
+ constructor(taskIds: string[]);
1365
+ }
1366
+ /** Thrown by `startWatch` when a watch session is already running. */
1367
+ export declare class WatchInProgressError extends Error {
1368
+ readonly code: "CAPPA_WATCH_IN_PROGRESS";
1369
+ constructor();
1370
+ }
1371
+ /**
1372
+ * Identity-independent check for `RunInProgressError`.
1373
+ *
1374
+ * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.
1375
+ */
1376
+ export declare const isRunInProgressError: (error: unknown) => error is RunInProgressError;
1377
+ /** Identity-independent check for `UnknownTargetsError`. */
1378
+ export declare const isUnknownTargetsError: (error: unknown) => error is UnknownTargetsError;
1379
+ /** Identity-independent check for `WatchInProgressError`. */
1380
+ export declare const isWatchInProgressError: (error: unknown) => error is WatchInProgressError;
1381
+ //#endregion
1382
+ //#region src/engine/WatchSession.d.ts
1383
+ /**
1384
+ * The slice of a file watcher this session uses.
1385
+ *
1386
+ * Structural rather than chokidar's own type, so a test can drive a session
1387
+ * with a stand-in instead of real filesystem events — which are slow, ordered
1388
+ * by the OS rather than by the test, and different on every platform.
1389
+ */
1390
+ interface FileWatcher {
1391
+ on(event: "all", listener: (event: string, changedPath: string) => void): unknown;
1392
+ on(event: "ready", listener: () => void): unknown;
1393
+ on(event: "error", listener: (error: unknown) => void): unknown;
1394
+ close(): Promise<void>;
1395
+ }
1396
+ type CreateFileWatcher = (roots: string[], options: {
1397
+ cwd: string;
1398
+ ignored: (candidate: string) => boolean;
1399
+ }) => FileWatcher | Promise<FileWatcher>;
1400
+ /**
1401
+ * Directories no watch should ever descend into.
1402
+ *
1403
+ * `outputDir` is not here because it is not a fixed name — the engine passes it
1404
+ * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs
1405
+ * into it, every write is a change, and the session would trigger itself
1406
+ * forever.
1407
+ */
1408
+ export declare const DEFAULT_IGNORED_DIRS: Set<string>;
1409
+ /** Watch-mode defaults, exported so the CLI and docs can quote one source. */
1410
+ export declare const DEFAULT_DEBOUNCE_MS = 300;
1411
+ export declare const DEFAULT_MAX_TASKS = 200;
1412
+ type WatchSessionOptions = {
1413
+ plugins: RunnablePlugin[];
1414
+ /** Discovered tasks per plugin name. Called once per settled batch. */
1415
+ discover: () => Promise<Map<string, PluginTask[]>>;
1416
+ /** Start a run. Resolves as soon as the run is registered. */
1417
+ startRun: (request: StartRunRequest) => Promise<RunSummary>;
1418
+ /** Resolve when the given run reaches a terminal event. */
1419
+ waitForRun: (runId: string) => Promise<void>;
1420
+ emit?: (event: EmittableWatchEvent) => void;
1421
+ cwd?: string;
1422
+ /** Roots to watch, relative to `cwd`. @default ["."] */
1423
+ paths?: string[];
1424
+ /** Absolute or `cwd`-relative paths never to watch (the output directory). */
1425
+ ignoredPaths?: string[];
1426
+ filter?: string;
1427
+ debounceMs?: number;
1428
+ maxTasks?: number;
1429
+ createWatcher?: CreateFileWatcher;
1430
+ now?: () => number;
1431
+ };
1432
+ /**
1433
+ * Re-captures affected tasks when files change.
1434
+ *
1435
+ * A scheduler for runs, deliberately not a second orchestrator: every iteration
1436
+ * goes through the engine's ordinary `startRun`, so watch-triggered captures
1437
+ * emit the same events, land in the same run store and honour the same
1438
+ * one-run-at-a-time rule as a capture somebody clicked.
1439
+ *
1440
+ * Two behaviours matter more than they look:
1441
+ *
1442
+ * - **`clearActual` is always false.** Clearing on every save would delete the
1443
+ * diffs the user is looking at for tasks they did not touch.
1444
+ * - **Changes during a run are queued, never rejected.** The engine's single-run
1445
+ * rule stays intact, and the user gets the run they expect rather than a
1446
+ * conflict error they did not cause.
1447
+ */
1448
+ export declare class WatchSession {
1449
+ private readonly options;
1450
+ private readonly cwd;
1451
+ private readonly roots;
1452
+ private readonly ignoredRoots;
1453
+ private readonly debounceMs;
1454
+ private readonly maxTasks;
1455
+ private readonly now;
1456
+ private watcher;
1457
+ private readonly pending;
1458
+ private timer;
1459
+ private draining;
1460
+ private stopped;
1461
+ private startedAt;
1462
+ private lastChange;
1463
+ constructor(options: WatchSessionOptions);
1464
+ /** Begin watching. Resolves once the initial scan has settled. */
1465
+ start(): Promise<WatchStatus>;
1466
+ /**
1467
+ * Stop watching.
1468
+ *
1469
+ * Deliberately does not cancel a run already in flight: that run is the
1470
+ * answer to a save the user made, and killing it half-way leaves `actual/`
1471
+ * holding a partial capture.
1472
+ */
1473
+ stop(reason?: "requested" | "engine-closed"): Promise<void>;
1474
+ getStatus(): WatchStatus;
1475
+ private emit;
1476
+ private waitForReady;
1477
+ private onFileChanged;
1478
+ /**
1479
+ * Capture for everything pending, one batch at a time.
1480
+ *
1481
+ * The loop re-reads `pending` after each iteration, which is what turns a
1482
+ * save arriving mid-run into the next iteration rather than into a `409`.
1483
+ */
1484
+ private drain;
1485
+ private captureFor;
1486
+ private record;
1487
+ /**
1488
+ * Ask every plugin what the changed files affect, and turn the answers into
1489
+ * one run request.
1490
+ */
1491
+ private resolveFiles;
1492
+ /**
1493
+ * A run of explicit ids, unless there are so many that naming them is
1494
+ * pointless — a branch switch or a formatter pass resolves half the project,
1495
+ * and a filtered full run is both cheaper to express and easier to read.
1496
+ */
1497
+ private byTaskIds;
1498
+ private isIgnored;
1499
+ }
1500
+ //#endregion
1501
+ //#region src/engine/LocalEngine.d.ts
1502
+ type LocalEngineOptions = {
1503
+ outputDir: string;
1504
+ plugins: RunnablePlugin[];
1505
+ diff?: DiffOptions;
1506
+ retries?: number;
1507
+ concurrency?: number;
1508
+ logConsoleEvents?: boolean;
1509
+ fullPage?: boolean;
1510
+ viewport?: Viewport;
1511
+ connectionTimeout?: number;
1512
+ /**
1513
+ * How long the browser stays warm between runs.
1514
+ * @default 300_000 (5 minutes)
1515
+ */
1516
+ browserIdleTimeoutMs?: number;
1517
+ runStore?: RunStoreOptions;
1518
+ /** Overrides the screenshot tool factory. Tests use this. */
1519
+ createScreenshotTool?: () => ScreenshotTool;
1520
+ /** Working directory a watch session watches. @default process.cwd() */
1521
+ cwd?: string;
1522
+ /** Overrides the file watcher factory. Tests use this. */
1523
+ createWatcher?: CreateFileWatcher;
1524
+ /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */
1525
+ maxWatchEvents?: number;
1526
+ };
1527
+ /**
1528
+ * `CaptureEngine` backed by an in-process Playwright browser.
1529
+ *
1530
+ * Holds the config's live plugin objects, so it must live in the process that
1531
+ * loaded `cappa.config.ts`. The server takes one of these by injection rather
1532
+ * than building it, which is what keeps `@cappa/server` free of config loading
1533
+ * and makes a remote engine a drop-in alternative.
1534
+ *
1535
+ * One run at a time. Queuing is deliberately not implemented: the browser pool
1536
+ * is the real constraint, and a second concurrent run would fight it.
1537
+ */
1538
+ export declare class LocalEngine implements CaptureEngine {
1539
+ private readonly options;
1540
+ private readonly plugins;
1541
+ private readonly fileSystem;
1542
+ private readonly browser;
1543
+ private readonly runs;
1544
+ /**
1545
+ * Set synchronously the moment a run is claimed, before any `await`, so two
1546
+ * concurrent `startRun` calls cannot both pass the check and then fight over
1547
+ * the browser. Covers the window between claiming and the run finishing.
1548
+ */
1549
+ private busy;
1550
+ private activeRunId;
1551
+ private targetsCache;
1552
+ /**
1553
+ * The tasks behind `targetsCache`, kept whole.
1554
+ *
1555
+ * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the
1556
+ * task it came from, `data` included — that is where a story's `importPath`
1557
+ * lives. Same discovery, two shapes, one cache lifetime.
1558
+ */
1559
+ private taskCache;
1560
+ private closed;
1561
+ private watchSession;
1562
+ private releaseBrowserHold;
1563
+ private readonly watchListeners;
1564
+ private watchEvents;
1565
+ private watchSeq;
1566
+ constructor(options: LocalEngineOptions);
1567
+ private buildTool;
1568
+ listPlugins(): Promise<PluginInfo[]>;
1569
+ /**
1570
+ * Discovery needs a browser (plugins query the app under test through it), so
1571
+ * this warms the browser on a cache miss.
1572
+ *
1573
+ * While a run holds the browser, only the cache can be served: discovering
1574
+ * would recycle the very contexts the run is capturing with.
1575
+ */
1576
+ listTargets(options?: ListTargetsOptions): Promise<Target[]>;
1577
+ startRun(request?: StartRunRequest): Promise<RunSummary>;
1578
+ getRun(id: string): Promise<RunDetail | undefined>;
1579
+ listRuns(): Promise<RunSummary[]>;
1580
+ cancelRun(id: string): Promise<void>;
1581
+ subscribeRun(id: string, onEvent: (event: RunEvent) => void, options?: SubscribeOptions): () => void;
1582
+ /**
1583
+ * Read the screenshot index from disk.
1584
+ *
1585
+ * Always a fresh read rather than a cached snapshot — anything can write to
1586
+ * `outputDir` while the server is up, including a CLI run in another terminal.
1587
+ */
1588
+ listScreenshots(query?: ScreenshotQuery): Promise<Screenshot[]>;
1589
+ approve(names: string[]): Promise<ApproveResult>;
1590
+ /**
1591
+ * Re-capture affected tasks on file change until `stopWatch`.
1592
+ *
1593
+ * Every iteration goes through `startRun`, so a watch-triggered capture is an
1594
+ * ordinary run: same events, same run store, same single-run rule, visible in
1595
+ * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.
1596
+ */
1597
+ startWatch(request?: StartWatchRequest): Promise<WatchStatus>;
1598
+ stopWatch(): Promise<WatchStatus>;
1599
+ getWatchStatus(): Promise<WatchStatus>;
1600
+ subscribeWatch(onEvent: (event: WatchEvent) => void, options?: SubscribeOptions): () => void;
1601
+ close(): Promise<void>;
1602
+ private endWatch;
1603
+ private emitWatchEvent;
1604
+ /** Resolve once a run reaches a terminal event. */
1605
+ private waitForRun;
1606
+ /** True while a browser process is alive. Exposed for tests and diagnostics. */
1607
+ get isWarm(): boolean;
1608
+ private assertOpen;
1609
+ /**
1610
+ * A client may only ask for tasks that discovery produced.
1611
+ *
1612
+ * This is a security boundary as much as a correctness one: it is what stops
1613
+ * a request from steering the browser to an arbitrary URL.
1614
+ */
1615
+ private validateTaskIds;
1616
+ /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */
1617
+ private discoverTasks;
1618
+ private discoverTargets;
1619
+ }
1620
+ //#endregion
1621
+ //#region src/engine/WarmBrowser.d.ts
1622
+ type WarmBrowserOptions = {
1623
+ /** Builds an un-initialised `ScreenshotTool`. Called once per cold start. */
1624
+ create: () => ScreenshotTool;
1625
+ /**
1626
+ * How long the browser may sit unused before it is shut down.
1627
+ * `0` disables warm reuse entirely (close immediately after each release).
1628
+ * @default 300_000 (5 minutes)
1629
+ */
1630
+ idleTimeoutMs?: number;
1631
+ };
1632
+ /**
1633
+ * Keeps a Playwright browser alive between capture runs.
1634
+ *
1635
+ * Interactively, a cold Chromium start on every "Capture" click is the
1636
+ * difference between a snappy tool and a sluggish one — but a browser left
1637
+ * running forever is a memory leak, so it is evicted after an idle period.
1638
+ *
1639
+ * Contexts are recycled on every acquire after the first, because a warm
1640
+ * browser's pages carry cookies, storage and scroll position from the previous
1641
+ * run and a screenshot taken against leaked state is not the screenshot the CLI
1642
+ * would have taken.
1643
+ */
1644
+ export declare class WarmBrowser {
1645
+ private readonly createTool;
1646
+ private readonly idleTimeoutMs;
1647
+ private tool;
1648
+ private idleTimer;
1649
+ private inUse;
1650
+ private closed;
1651
+ /** Outstanding `hold()` leases. While any is held, eviction is suspended. */
1652
+ private holds;
1653
+ /** Serializes acquire/close so concurrent callers cannot race the browser. */
1654
+ private pending;
1655
+ constructor(options: WarmBrowserOptions);
1656
+ /** True while a browser process is alive. */
1657
+ get isWarm(): boolean;
1658
+ /**
1659
+ * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.
1660
+ * Always pair with `release()`.
1661
+ */
1662
+ acquire(): Promise<ScreenshotTool>;
1663
+ /**
1664
+ * Hand the browser back. It stays warm until the idle timeout elapses.
1665
+ */
1666
+ release(): void;
1667
+ /**
1668
+ * Suspend idle eviction until the returned function is called.
1669
+ *
1670
+ * Held by an active watch session. Without it, `WarmBrowser` closes the
1671
+ * browser between saves during a coffee break and the next save pays full
1672
+ * start-up — which is the entire premise of watch mode, defeated by its own
1673
+ * idle handling.
1674
+ */
1675
+ hold(): () => void;
1676
+ /** True while at least one lease suspends idle eviction. */
1677
+ get isHeld(): boolean;
1678
+ /** Shut the browser down now. Safe to call repeatedly. */
1679
+ close(): Promise<void>;
1680
+ private startIdleTimer;
1681
+ private cancelIdleTimer;
1682
+ /** Shut the browser down but stay usable — the next acquire starts cold. */
1683
+ private evict;
1684
+ private serialize;
1685
+ }
644
1686
  //#endregion
645
1687
  //#region src/mapWithConcurrency.d.ts
646
1688
  /**
@@ -648,7 +1690,163 @@ declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: Conf
648
1690
  * Preserves failure behavior: the first rejection rejects the returned promise.
649
1691
  * Results are returned in the same order as the input items.
650
1692
  */
651
- declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1693
+ export declare function mapWithConcurrency<T, R = void>(concurrency: number, items: readonly T[], fn: (item: T, workerIndex: number) => Promise<R>): Promise<R[]>;
1694
+ //#endregion
1695
+ //#region src/runner/tasks.d.ts
1696
+ /**
1697
+ * Decide whether a plugin's `execute` result represents a failed screenshot.
1698
+ *
1699
+ * Plugins return loosely-shaped objects, so this inspects the three signals that
1700
+ * matter: an explicit `error`, an explicit `success: false`, or a missing
1701
+ * `filepath` on a task that was not skipped.
1702
+ */
1703
+ export declare const didScreenshotFail: (result: unknown) => boolean;
1704
+ /**
1705
+ * Map a plugin result onto the status shown in the UI.
1706
+ *
1707
+ * Mirrors the screenshot categories: a capture with no baseline is `new`, a
1708
+ * failing comparison is `changed`, and anything `didScreenshotFail` flags for
1709
+ * another reason is `failed`.
1710
+ */
1711
+ export declare const toTaskStatus: (result: unknown) => TaskStatus;
1712
+ /** Restrict `tasks` to those whose id matches the glob `filter`. */
1713
+ export declare function filterTasks(tasks: PluginTask[], filter: string): PluginTask[];
1714
+ /** Restrict `tasks` to an explicit set of ids. */
1715
+ export declare function selectTasks(tasks: PluginTask[], taskIds: readonly string[]): PluginTask[];
1716
+ /**
1717
+ * Baselines in `expected/` that have no counterpart in `actual/` — screenshots
1718
+ * that existed when the baseline was approved but were not captured this run.
1719
+ */
1720
+ export declare function getDeletedScreenshots(outputDir: string): Promise<string[]>;
1721
+ //#endregion
1722
+ //#region src/screenshots/collectScreenshots.d.ts
1723
+ /**
1724
+ * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and
1725
+ * group them into the screenshot representations used by the CLI commands
1726
+ * (including the diff metadata sidecar with the optional interpretation).
1727
+ *
1728
+ * The capture manifest is folded in here so every consumer — the CLI, the
1729
+ * server, the review UI — sees the same `taskId`, and so a screenshot captured
1730
+ * before manifests existed simply has none rather than a wrong one.
1731
+ */
1732
+ export declare const collectScreenshots: (outputDir: string) => Promise<Screenshot[]>;
1733
+ //#endregion
1734
+ //#region src/screenshots/groupScreenshots.d.ts
1735
+ export declare const groupScreenshots: (actualScreenshots: string[], expectedScreenshots: string[], diffScreenshots: string[], outputDir: string) => Promise<Screenshot[]>;
1736
+ //#endregion
1737
+ //#region src/screenshots/manifest.d.ts
1738
+ /**
1739
+ * Maps a screenshot back to the capture task that produced it.
1740
+ *
1741
+ * Nothing on disk carries this. A screenshot's name comes from the filename a
1742
+ * plugin chose (`example/button/primary`), while the task id comes from the
1743
+ * plugin's own addressing scheme (`example-button--primary` for Storybook) —
1744
+ * and there is no rule connecting the two. Without a record written at capture
1745
+ * time, "re-capture this one screenshot" has no task to ask for, which is
1746
+ * exactly how the review UI's re-capture button came to send a name the engine
1747
+ * had never heard of.
1748
+ *
1749
+ * Kept beside `actual/` and `expected/` rather than inside them so it is never
1750
+ * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is
1751
+ * configured with `serveDotFiles: false`) will not serve it.
1752
+ */
1753
+ export declare const MANIFEST_FILENAME = ".cappa-manifest.json";
1754
+ /** Bumped only if the on-disk shape changes incompatibly. */
1755
+ export declare const MANIFEST_VERSION = 1;
1756
+ /** Where a screenshot came from. */
1757
+ type ScreenshotOrigin = {
1758
+ /** Task id as `discover` produced it — what `startRun` accepts. */
1759
+ taskId: string;
1760
+ /** Plugin that owns the task. */
1761
+ plugin: string;
1762
+ };
1763
+ type CaptureManifest = {
1764
+ version: number;
1765
+ /** Keyed by screenshot name (relative path, no `.png`). */
1766
+ screenshots: Record<string, ScreenshotOrigin>;
1767
+ };
1768
+ /**
1769
+ * The key a capture filename is recorded under.
1770
+ *
1771
+ * Must match the `name` `groupScreenshots` derives, or a lookup silently
1772
+ * misses: the relative path with its `.png` dropped, and separators normalised
1773
+ * so a manifest written on Windows is readable on Linux.
1774
+ */
1775
+ export declare const toManifestKey: (filename: string) => string;
1776
+ /**
1777
+ * Read the manifest, or an empty one.
1778
+ *
1779
+ * Never throws: the manifest is an optimisation, and a missing, truncated or
1780
+ * hand-edited file must degrade to "we do not know where this came from"
1781
+ * rather than break the screenshot index every command depends on.
1782
+ */
1783
+ export declare const readCaptureManifest: (outputDir: string) => Promise<CaptureManifest>;
1784
+ /**
1785
+ * Merge freshly captured origins into whatever the manifest already holds.
1786
+ *
1787
+ * A run only captures the tasks it was asked for, so existing entries have to
1788
+ * survive — otherwise re-capturing one screenshot would strip every other
1789
+ * screenshot's origin and disable the button that started it.
1790
+ *
1791
+ * `knownNames`, when given, is the set of screenshots that currently exist;
1792
+ * entries outside it are dropped so renames and deletions do not accumulate
1793
+ * forever. New origins are always kept, whether or not they appear in it.
1794
+ */
1795
+ export declare const mergeCaptureManifest: (existing: CaptureManifest, origins: Record<string, ScreenshotOrigin>, knownNames?: Iterable<string>) => CaptureManifest;
1796
+ /**
1797
+ * Persist `origins`, merged over what is already recorded.
1798
+ *
1799
+ * Best-effort by design: a read-only or full disk must not turn a successful
1800
+ * capture run into a failed one, so a write failure is reported to the caller
1801
+ * as `false` rather than thrown.
1802
+ */
1803
+ export declare const recordCaptureOrigins: (outputDir: string, origins: Record<string, ScreenshotOrigin>, knownNames?: Iterable<string>) => Promise<boolean>;
1804
+ //#endregion
1805
+ //#region src/store.d.ts
1806
+ /** The three buckets a screenshot can live in. */
1807
+ type ScreenshotBucket = "actual" | "expected" | "diff";
1808
+ /**
1809
+ * Byte storage for screenshots, addressed by bucket + relative key
1810
+ * (`button--primary.png`, `nested/card.png`).
1811
+ *
1812
+ * `ScreenshotFileSystem` is local-disk by construction, which is correct for
1813
+ * the CLI and a local server but not for an engine running on a machine the
1814
+ * reviewer cannot reach. This interface is the seam: an object-store
1815
+ * implementation later is an implementation, not a fork.
1816
+ *
1817
+ * Only `FsScreenshotStore` exists today — nothing in the codebase depends on a
1818
+ * second implementation, and none is planned in this change.
1819
+ */
1820
+ interface ScreenshotStore {
1821
+ has(bucket: ScreenshotBucket, key: string): Promise<boolean>;
1822
+ read(bucket: ScreenshotBucket, key: string): Promise<Buffer>;
1823
+ write(bucket: ScreenshotBucket, key: string, data: Buffer): Promise<void>;
1824
+ /** Relative keys, recursively. */
1825
+ list(bucket: ScreenshotBucket): Promise<string[]>;
1826
+ remove(bucket: ScreenshotBucket, key: string): Promise<void>;
1827
+ /** Drop every object in a bucket. */
1828
+ clear(bucket: ScreenshotBucket): Promise<void>;
1829
+ readMeta(key: string): Promise<DiffMetadata | undefined>;
1830
+ writeMeta(key: string, meta: DiffMetadata): Promise<void>;
1831
+ }
1832
+ /**
1833
+ * `ScreenshotStore` over the local filesystem, delegating to
1834
+ * `ScreenshotFileSystem` so both views stay consistent.
1835
+ */
1836
+ export declare class FsScreenshotStore implements ScreenshotStore {
1837
+ private readonly fs;
1838
+ constructor(outputDirOrFs: string | ScreenshotFileSystem);
1839
+ private dirFor;
1840
+ private pathFor;
1841
+ has(bucket: ScreenshotBucket, key: string): Promise<boolean>;
1842
+ read(bucket: ScreenshotBucket, key: string): Promise<Buffer>;
1843
+ write(bucket: ScreenshotBucket, key: string, data: Buffer): Promise<void>;
1844
+ list(bucket: ScreenshotBucket): Promise<string[]>;
1845
+ remove(bucket: ScreenshotBucket, key: string): Promise<void>;
1846
+ clear(bucket: ScreenshotBucket): Promise<void>;
1847
+ readMeta(key: string): Promise<DiffMetadata | undefined>;
1848
+ writeMeta(key: string, meta: DiffMetadata): Promise<void>;
1849
+ }
652
1850
  //#endregion
653
- export { type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type InterpretResult, type NewScreenshot, type PassedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, mapWithConcurrency, readDiffMeta, toDiffMetaPath };
1851
+ export { type ApproveResult, type CaptureEngine, type CaptureManifest, type CaptureRunnerOptions, type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type CreateFileWatcher, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type EmittableWatchEvent, type FailedScreenshot, type FileWatcher, type InterpretResult, type ListTargetsOptions, type LocalEngineOptions, type NewScreenshot, type PassedScreenshot, type Plugin, type PluginCaptureResult, type PluginDef, type PluginFunction, type PluginInfo, type PluginTask, type PluginWatch, type PluginWatchResolve, type RunDetail, type RunEvent, type RunEventListener, type RunEventType, type RunLogLevel, type RunState, type RunStoreOptions, type RunSummary, type RunTrigger, type RunnablePlugin, type Screenshot, type ScreenshotBucket, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, type ScreenshotCaptureSink, type ScreenshotOptions, type ScreenshotOrigin, type ScreenshotQuery, type ScreenshotSettings, type ScreenshotStore, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type SerializedError, type StartRunRequest, type StartWatchRequest, type SubscribeOptions, type Target, type TaskFailure, type TaskRecord, type TaskStatus, type UserConfig, type Viewport, type WarmBrowserOptions, type WatchChange, type WatchEvent, type WatchEventType, type WatchScope, type WatchSessionOptions, type WatchStatus };
654
1852
  //# sourceMappingURL=index.d.cts.map