@cappa/core 0.12.4 → 0.13.1

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