@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.cjs +1824 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1210 -12
- package/dist/index.d.mts +1210 -12
- package/dist/index.mjs +1799 -9
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -10
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["fsp","path","os","fs","path","fsp","fs","path"],"sources":["../src/features/png/util.ts","../src/features/png/png.ts","../src/compare/gmsd.ts","../src/compare/pixel.ts","../src/config.ts","../src/mapWithConcurrency.ts","../src/filesystem.ts","../src/screenshot.ts"],"sourcesContent":["import { open } from \"node:fs/promises\";\nimport type { MetadataEntries } from \"./types\";\n\ntype ParsedChunk = {\n type: string;\n data: Buffer;\n length: number;\n offset: number;\n};\n\n// Magic Bytes:\n// The first 8 bytes of every valid PNG file.\n// Used to verify that the file is actually a PNG before processing.\nconst pngSignature = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\n// A pre-calculated lookup table for the CRC32 algorithm.\n// We use this to quickly calculate the checksum for each chunk we write.\n// Without this table, calculating CRC bit-by-bit would be significantly slower.\nconst crcTable = new Uint32Array(256).map((_, index) => {\n let c = index;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n\n return c >>> 0;\n});\n\n/**\n * Chunk Parser Generator\n *\n * A PNG file is essentially a list of chunks.\n * Structure of a chunk:\n * 1. Length (4 bytes): The size of the data field.\n * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').\n * 3. Data (Length bytes): The actual payload.\n * 4. CRC (4 bytes): Checksum.\n */\nfunction* readChunks(buffer: Buffer): Generator<ParsedChunk> {\n let offset = pngSignature.length;\n\n while (offset + 8 <= buffer.length) {\n const length = buffer.readUInt32BE(offset);\n const type = buffer.toString(\"ascii\", offset + 4, offset + 8);\n const dataStart = offset + 8;\n const dataEnd = dataStart + length;\n\n if (dataEnd > buffer.length) {\n return;\n }\n\n const data = buffer.subarray(dataStart, dataEnd);\n\n yield { type, data, length, offset };\n\n offset = dataEnd + 4; // Skip CRC\n\n if (type === \"IEND\") {\n return;\n }\n }\n}\n\n/**\n * Constructs a raw binary `tEXt` chunk.\n */\nexport function createTextChunk(key: string, value: string) {\n const keyBuffer = Buffer.from(key, \"latin1\");\n const valueBuffer = Buffer.from(value, \"latin1\");\n const data = Buffer.concat([keyBuffer, Buffer.from([0]), valueBuffer]);\n const lengthBuffer = Buffer.alloc(4);\n const typeBuffer = Buffer.from(\"tEXt\");\n\n lengthBuffer.writeUInt32BE(data.length, 0);\n\n const crcBuffer = Buffer.alloc(4);\n crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);\n\n return Buffer.concat([lengthBuffer, typeBuffer, data, crcBuffer]);\n}\n\n/**\n * Calculates the CRC32 checksum for a buffer.\n * Used to ensure data integrity.\n */\nexport function crc32(buffer: Buffer) {\n let crc = 0 ^ -1;\n\n for (let i = 0; i < buffer.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the index is valid\n crc = (crc >>> 8) ^ crcTable[(crc ^ buffer[i]!) & 0xff]!;\n }\n\n return (crc ^ -1) >>> 0;\n}\n\n/**\n * Helper to locate the IEND chunk, which marks the end of a PNG stream.\n */\nfunction findIendChunk(buffer: Buffer): ParsedChunk | undefined {\n for (const chunk of readChunks(buffer)) {\n if (chunk.type === \"IEND\") {\n return chunk;\n }\n }\n\n return undefined;\n}\n\n/**\n * Inserts metadata chunks into a PNG buffer.\n * It places them right before the final `IEND` chunk.\n */\nexport function injectTextMetadata(buffer: Buffer, metadata: MetadataEntries) {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return buffer;\n }\n\n const iendChunk = findIendChunk(buffer);\n if (!iendChunk) {\n return buffer;\n }\n\n const textChunks = Object.entries(metadata).map(([key, value]) =>\n createTextChunk(key, value),\n );\n\n return Buffer.concat([\n buffer.subarray(0, iendChunk.offset),\n ...textChunks,\n buffer.subarray(iendChunk.offset),\n ]);\n}\n\nexport function isValidPngSignature(buffer: Buffer): boolean {\n if (buffer.length < pngSignature.length) return false;\n return buffer.subarray(0, pngSignature.length).equals(pngSignature);\n}\n\nconst IHDR_MIN_BYTES = 24;\n\nexport async function readIhdrDimensions(\n source: string | Buffer,\n): Promise<{ width: number; height: number }> {\n let buf: Buffer;\n\n if (typeof source === \"string\") {\n const fh = await open(source, \"r\");\n try {\n buf = Buffer.alloc(IHDR_MIN_BYTES);\n await fh.read(buf, 0, IHDR_MIN_BYTES, 0);\n } finally {\n await fh.close();\n }\n } else {\n buf = source;\n }\n\n if (\n buf.length < IHDR_MIN_BYTES ||\n !buf.subarray(0, pngSignature.length).equals(pngSignature)\n ) {\n throw new Error(\"Not a valid PNG\");\n }\n\n const width = buf.readUInt32BE(16);\n const height = buf.readUInt32BE(20);\n return { width, height };\n}\n\n/**\n * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.\n */\nexport function extractTextMetadata(buffer: Buffer): MetadataEntries {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return {};\n }\n\n const metadata: MetadataEntries = {};\n\n for (const chunk of readChunks(buffer)) {\n if (chunk.type !== \"tEXt\") {\n continue;\n }\n\n const separatorIndex = chunk.data.indexOf(0);\n if (separatorIndex < 0) {\n continue;\n }\n\n const key = chunk.data.toString(\"latin1\", 0, separatorIndex);\n const value = chunk.data.toString(\"latin1\", separatorIndex + 1);\n\n metadata[key] = value;\n }\n\n return metadata;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport sharp from \"sharp\";\nimport type { MetadataEntries } from \"./types\";\nimport { extractTextMetadata, injectTextMetadata } from \"./util\";\n\n/**\n * A wrapper around `sharp` that adds support for reading and writing\n * textual metadata (tEXt chunks). Used for fast PNG decode/encode.\n */\nexport class PNG {\n private width_: number;\n private height_: number;\n private data_: Buffer;\n private sourcePath?: string;\n private metadataEntries: MetadataEntries;\n\n private constructor(\n width: number,\n height: number,\n data: Buffer,\n sourcePath?: string,\n metadata?: MetadataEntries,\n ) {\n this.width_ = width;\n this.height_ = height;\n this.data_ = data;\n this.sourcePath = sourcePath;\n this.metadataEntries = { ...(metadata ?? {}) };\n }\n\n static create(width: number, height: number): PNG {\n const data = Buffer.alloc(width * height * 4, 0);\n return new PNG(width, height, data);\n }\n\n static async load(source: string | Buffer): Promise<PNG> {\n const buffer = typeof source === \"string\" ? await readFile(source) : source;\n const metadata = extractTextMetadata(buffer);\n\n const pipeline = sharp(buffer).ensureAlpha();\n const { data: raw, info } = await pipeline\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const data = Buffer.from(raw);\n const sourcePath = typeof source === \"string\" ? source : undefined;\n\n return new PNG(info.width, info.height, data, sourcePath, metadata);\n }\n\n get width(): number {\n return this.width_;\n }\n\n get height(): number {\n return this.height_;\n }\n\n get data(): Buffer {\n return this.data_;\n }\n\n get metadata(): MetadataEntries {\n return { ...this.metadataEntries };\n }\n\n setMetadata(key: string, value: string): void {\n this.metadataEntries = { ...this.metadataEntries, [key]: value };\n }\n\n replaceMetadata(metadata: MetadataEntries): void {\n this.metadataEntries = { ...metadata };\n }\n\n removeMetadata(key: string): void {\n const { [key]: _, ...remaining } = this.metadataEntries;\n this.metadataEntries = remaining;\n }\n\n clearMetadata(): void {\n this.metadataEntries = {};\n }\n\n async toBuffer(): Promise<Buffer> {\n const baseBuffer = await sharp(this.data_, {\n raw: { width: this.width_, height: this.height_, channels: 4 },\n })\n .png()\n .toBuffer();\n\n if (Object.keys(this.metadataEntries).length === 0) {\n return baseBuffer;\n }\n\n return injectTextMetadata(baseBuffer, this.metadataEntries);\n }\n\n async save(filepath?: string): Promise<void> {\n const targetPath = filepath ?? this.sourcePath;\n\n if (!targetPath) {\n throw new Error(\"No filepath provided for saving PNG\");\n }\n\n await writeFile(targetPath, await this.toBuffer());\n }\n}\n","import fs from \"node:fs\";\nimport gmsd, { type GmsdOptions } from \"@blazediff/gmsd\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport type { DiffConfigGMSD } from \"../types\";\n\nexport type CompareOptions = GmsdOptions;\n\nexport interface CompareResult {\n gmsd: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: GmsdOptions,\n) => {\n return gmsd(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImagesGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfigGMSD = {},\n): Promise<CompareResult> {\n // Load both PNGs in parallel with sharp for better performance\n const [png1, png2] = await Promise.all([loadPNG(image1), loadPNG(image2)]);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return { gmsd: Infinity, passed: false };\n }\n\n const diff = withDiff ? PNG.create(width, height) : undefined;\n\n try {\n const gmsd = compare(png1.data, png2.data, diff?.data, width, height, {\n downsample: options.downsample ?? 0,\n c: options.c ?? 170,\n });\n\n // Convert diff image to buffer\n const diffBuffer = diff\n ? await annotateDiffImage(diff, options).toBuffer()\n : undefined;\n\n return {\n gmsd,\n diffBuffer,\n passed: gmsd <= (options.threshold ?? 0.1),\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n gmsd: Infinity,\n passed: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n return PNG.load(source);\n}\n\nfunction annotateDiffImage(image: PNG, options: DiffConfigGMSD) {\n image.setMetadata(\"cappa.diff.algorithm\", \"gmsd\");\n\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined) {\n continue;\n }\n\n image.setMetadata(`cappa.diff.${key}`, String(value));\n }\n\n return image;\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatchGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfigGMSD = {},\n): Promise<boolean> {\n const result = await compareImagesGMSD(image1, image2, false, options);\n\n return result.passed;\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type BlazeDiffOptions,\n type BlazeDiffResult,\n compare as blazediffCompare,\n interpret as blazediffInterpret,\n type InterpretResult,\n} from \"@blazediff/core-native\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport {\n injectTextMetadata,\n isValidPngSignature,\n readIhdrDimensions,\n} from \"../features/png/util\";\nimport type { DiffConfig } from \"../types\";\n\n/** Pixel diff options: Cappa `DiffConfig` plus optional native-only output tuning. */\nexport type CompareOptions = DiffConfig &\n Partial<Pick<BlazeDiffOptions, \"diffMask\" | \"compression\" | \"quality\">>;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\n interpretation?: InterpretResult; // Structured diff analysis (when `interpret` is enabled)\n}\n\ntype TempState = { tempRoot?: string };\n\nasync function ensureTempRoot(state: TempState): Promise<string> {\n if (!state.tempRoot) {\n state.tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), \"cappa-pxl-\"));\n }\n return state.tempRoot;\n}\n\nasync function resolveInputPath(\n source: string | Buffer,\n fileName: string,\n state: TempState,\n): Promise<string> {\n if (typeof source === \"string\") {\n await fsp.access(source, fs.constants.R_OK);\n return path.resolve(source);\n }\n\n if (!isValidPngSignature(source)) {\n throw new Error(\"Invalid PNG buffer: missing PNG signature\");\n }\n\n const root = await ensureTempRoot(state);\n const dest = path.join(root, fileName);\n await fsp.writeFile(dest, source);\n return dest;\n}\n\nfunction toNativeOptions(config: DiffConfig): BlazeDiffOptions {\n const extra = config as CompareOptions;\n const out: BlazeDiffOptions = {\n threshold: extra.threshold,\n antialiasing: extra.includeAA ?? false,\n };\n\n if (extra.diffMask !== undefined) {\n out.diffMask = extra.diffMask;\n }\n if (extra.compression !== undefined) {\n out.compression = extra.compression;\n }\n if (extra.quality !== undefined) {\n out.quality = extra.quality;\n }\n\n return out;\n}\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n const state: TempState = {};\n let diffPath: string | undefined;\n\n try {\n const p1 = await resolveInputPath(image1, \"expected.png\", state);\n const p2 = await resolveInputPath(image2, \"actual.png\", state);\n\n if (withDiff) {\n const root = await ensureTempRoot(state);\n diffPath = path.join(root, \"diff.png\");\n }\n\n const wantInterpret = !!(options as CompareOptions).interpret && withDiff;\n\n let nativeResult: BlazeDiffResult;\n\n try {\n // Never pass `interpret` to `compare` — the native binding skips writing\n // the diff image when interpret mode is on. Interpretation is fetched in\n // a separate call below when needed.\n nativeResult = await blazediffCompare(\n p1,\n p2,\n withDiff ? diffPath : undefined,\n toNativeOptions(options),\n );\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n\n if (nativeResult.match === false) {\n if (nativeResult.reason === \"file-not-exists\") {\n throw new Error(`File not found: ${nativeResult.file}`);\n }\n\n if (nativeResult.reason === \"layout-diff\") {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n }\n\n const { width, height } = await readIhdrDimensions(p1);\n const totalPixels = width * height;\n\n if (nativeResult.match) {\n return {\n numDiffPixels: 0,\n totalPixels,\n percentDifference: 0,\n diffBuffer: undefined,\n passed: isPassed(0, 0, options),\n differentSizes: false,\n };\n }\n\n let diffBuffer: Buffer | undefined;\n if (withDiff && diffPath) {\n const rawDiff = await fsp.readFile(diffPath);\n const diffMetadata: Record<string, string> = {\n \"cappa.diff.algorithm\": \"pixel\",\n };\n for (const [key, value] of Object.entries(options)) {\n if (value !== undefined) {\n diffMetadata[`cappa.diff.${key}`] = String(value);\n }\n }\n diffBuffer = injectTextMetadata(rawDiff, diffMetadata);\n }\n\n const numDiffPixels = nativeResult.diffCount;\n const percentDifference = nativeResult.diffPercentage;\n\n let interpretation: InterpretResult | undefined;\n if (wantInterpret && !nativeResult.match) {\n try {\n interpretation = await blazediffInterpret(p1, p2, {\n threshold: options.threshold,\n antialiasing: options.includeAA ?? false,\n });\n } catch {\n // Interpretation is best-effort; don't fail the comparison.\n }\n }\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n differentSizes: false,\n interpretation,\n };\n } finally {\n if (state.tempRoot) {\n await fsp\n .rm(state.tempRoot, { recursive: true, force: true })\n .catch(() => {\n // ignore cleanup errors\n });\n }\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\n */\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport async function createDiffSizePngImage(\n width: number,\n height: number,\n): Promise<Buffer> {\n const png = PNG.create(width, height);\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return png.toBuffer();\n}\n","import type { ConfigEnv, PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","/**\n * Run async work over `items` with at most `concurrency` tasks in flight.\n * Preserves failure behavior: the first rejection rejects the returned promise.\n * Results are returned in the same order as the input items.\n */\nexport async function mapWithConcurrency<T, R = void>(\n concurrency: number,\n items: readonly T[],\n fn: (item: T, workerIndex: number) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, concurrency);\n const workerCount = Math.min(limit, items.length);\n const results: R[] = new Array(items.length);\n let next = 0;\n\n const worker = async (workerIndex: number): Promise<void> => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n const item = items[i];\n if (item === undefined) {\n return;\n }\n results[i] = await fn(item, workerIndex);\n }\n };\n\n await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));\n\n return results;\n}\n","import fs from \"node:fs\";\nimport fsp, { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getLogger } from \"@cappa/logger\";\nimport { imagesMatch } from \"./compare/pixel\";\nimport { extractTextMetadata, injectTextMetadata } from \"./features/png/util\";\nimport { mapWithConcurrency } from \"./mapWithConcurrency\";\nimport type {\n DiffConfig,\n DiffMetadata,\n DiffOptions,\n Screenshot,\n} from \"./types\";\n\nconst APPROVE_SCREENSHOTS_CONCURRENCY = 8;\n\n/**\n * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).\n */\nexport function toDiffMetaPath(diffImagePath: string): string {\n const ext = path.extname(diffImagePath);\n return ext\n ? `${diffImagePath.slice(0, -ext.length)}.json`\n : `${diffImagePath}.json`;\n}\n\n/**\n * Read a diff metadata sidecar, returning `undefined` when it is missing or\n * cannot be parsed (so callers can degrade gracefully).\n */\nexport async function readDiffMeta(\n diffImagePath: string,\n): Promise<DiffMetadata | undefined> {\n try {\n const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), \"utf8\");\n return JSON.parse(raw) as DiffMetadata;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actual: string;\n private readonly expected: string;\n private readonly diff: string;\n\n constructor(outputDir: string) {\n this.actual = path.resolve(outputDir, \"actual\");\n this.expected = path.resolve(outputDir, \"expected\");\n this.diff = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDirSync(this.actual);\n this.ensureParentDirSync(this.expected);\n this.ensureParentDirSync(this.diff);\n }\n\n clearActual() {\n this.removeDir(this.actual);\n }\n\n clearDiff() {\n this.removeDir(this.diff);\n }\n\n getActualScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.actual, \"**/*.png\")));\n }\n\n getExpectedScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.expected, \"**/*.png\")));\n }\n\n getDiffScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.diff, \"**/*.png\")));\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actual, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).\n */\n async approveScreenshots(\n screenshots: Screenshot[],\n diff: DiffOptions,\n ): Promise<void> {\n const outputDir = path.dirname(this.actual);\n\n await mapWithConcurrency(\n APPROVE_SCREENSHOTS_CONCURRENCY,\n screenshots,\n (screenshot) => this.approveOneScreenshot(screenshot, outputDir, diff),\n );\n }\n\n private async approveOneScreenshot(\n screenshot: Screenshot,\n outputDir: string,\n diff: DiffOptions,\n ): Promise<void> {\n const logger = getLogger();\n\n logger.debug(`Approving screenshot with category: ${screenshot.category}`);\n\n if (screenshot.category === \"new\") {\n logger.debug(`Approving new screenshot: ${screenshot.actualPath}`);\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"deleted\") {\n logger.debug(`Deleting expected screenshot: ${screenshot.expectedPath}`);\n await fsp.unlink(path.resolve(outputDir, screenshot.expectedPath));\n return;\n }\n\n if (screenshot.category === \"changed\") {\n logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"passed\") {\n if (!screenshot.expectedPath) {\n throw new Error(\"Expected path is required for passed screenshots\");\n }\n\n const matches = await imagesMatch(\n path.resolve(outputDir, screenshot.actualPath),\n path.resolve(outputDir, screenshot.expectedPath),\n diff.type === \"gmsd\"\n ? { threshold: diff.threshold }\n : (diff as DiffConfig),\n );\n\n if (!matches) {\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n }\n }\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private async approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actual, relativePath);\n const expectedPath = path.resolve(this.expected, relativePath);\n const diffPath = path.resolve(this.diff, relativePath);\n\n await this.ensureParentDir(expectedPath);\n\n await fsp.copyFile(actualPath, expectedPath);\n\n try {\n await fsp.access(diffPath);\n } catch {\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n await this.copyDiffMetadataToExpected(diffPath, expectedPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n private async copyDiffMetadataToExpected(\n diffPath: string,\n expectedPath: string,\n ): Promise<void> {\n const diffExtension = path.extname(diffPath).toLowerCase();\n const expectedExtension = path.extname(expectedPath).toLowerCase();\n\n if (diffExtension !== \".png\" || expectedExtension !== \".png\") {\n return;\n }\n\n try {\n const diffBuffer = await fsp.readFile(diffPath);\n const diffMetadata = extractTextMetadata(diffBuffer);\n\n if (Object.keys(diffMetadata).length === 0) {\n return;\n }\n\n const expectedBuffer = await fsp.readFile(expectedPath);\n const expectedMetadata = extractTextMetadata(expectedBuffer);\n\n const mergedMetadata = {\n ...expectedMetadata,\n ...diffMetadata,\n };\n\n const expectedWithMetadata = injectTextMetadata(\n expectedBuffer,\n mergedMetadata,\n );\n await fsp.writeFile(expectedPath, expectedWithMetadata);\n } catch {\n // Ignore metadata transfer errors to keep approval resilient.\n }\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n async ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n await fsp.mkdir(dir, { recursive: true });\n }\n\n /**\n * Synchronous version used only during constructor initialization.\n */\n private ensureParentDirSync(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actual;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expected;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diff;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actual, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expected, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diff, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n async writeActualFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getActualFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n async writeDiffFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Get the path to a diff metadata sidecar file (`<name>.json`)\n */\n getDiffMetaFilePath(filename: string): string {\n return toDiffMetaPath(this.getDiffFilePath(filename));\n }\n\n /**\n * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.\n */\n async writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void> {\n const filepath = this.getDiffMetaFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, JSON.stringify(meta));\n }\n\n /**\n * Check if an expected file exists\n */\n async hasExpectedFile(filename: string): Promise<boolean> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n await fsp.access(expectedPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read an expected file\n */\n async readExpectedFile(filename: string): Promise<Buffer> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n return await fsp.readFile(expectedPath);\n } catch {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n }\n\n /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actual, filePath);\n }\n\n getRelativePath(directory: \"actual\" | \"expected\" | \"diff\", filePath: string) {\n const relativePath = path.relative(this[directory], filePath);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot resolve relative path outside of ${directory} directory: ${filePath}`,\n );\n }\n\n return relativePath;\n }\n}\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n compareImagesGMSD,\n type CompareResult as GMSDCompareResult,\n} from \"./compare/gmsd\";\nimport {\n compareImages,\n createDiffSizePngImage,\n type CompareResult as PixelCompareResult,\n} from \"./compare/pixel\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type {\n DiffConfig,\n DiffConfigGMSD,\n DiffOptions,\n DiffOptionsGMSD,\n DiffOptionsPixel,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultPixelDiffConfig: DiffOptionsPixel = {\n type: \"pixel\",\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nconst defaultGMSDDiffConfig: DiffOptionsGMSD = {\n type: \"gmsd\",\n threshold: 0.1,\n downsample: 0,\n c: 170,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n }\n >;\n /**\n * Optional diff configuration override applied to this capture.\n * Merged on top of the global ScreenshotTool diff config.\n */\n diff?: DiffOptions;\n /**\n * Skip navigating to the base URL before capturing the base screenshot.\n * Use this when the page is already at the correct URL and in a stable state,\n * to avoid the redundant navigation.\n */\n skipBaseNavigation?: boolean;\n /**\n * Optional callback invoked after each navigation (variants only, or base when\n * skipBaseNavigation is false) to wait for visual stability before capturing.\n */\n waitForStability?: (page: Page) => Promise<void>;\n /**\n * Timestamp (from `performance.now()`) marking when the screenshot process\n * started — i.e. when the browser first navigated to the page. When provided,\n * the logged duration covers the full journey: navigation → stability waits →\n * capture. When omitted, timing begins at the capture step itself.\n */\n captureStart?: number;\n}\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n fullPage: boolean;\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffOptions;\n logger: Logger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: boolean;\n connectionTimeout: number;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n fullPage?: boolean;\n outputDir?: string;\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: boolean;\n connectionTimeout?: number;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.fullPage = options.fullPage ?? true;\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = this.resolveDiffOptions(options.diff);\n this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n this.connectionTimeout = options.connectionTimeout ?? 20000;\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n private resolveDiffOptions(diff?: DiffOptions): DiffOptions {\n if (diff?.type === \"gmsd\") {\n return { ...defaultGMSDDiffConfig, ...diff };\n }\n\n return { ...defaultPixelDiffConfig, ...diff, type: \"pixel\" };\n }\n\n private mergeDiffOptions(override?: DiffOptions): DiffOptions {\n const base = this.resolveDiffOptions(this.diff);\n\n if (!override) {\n return base;\n }\n\n if (override.type === \"gmsd\" || base.type === \"gmsd\") {\n const gmsdBase: DiffOptionsGMSD =\n base.type === \"gmsd\" ? base : defaultGMSDDiffConfig;\n\n return { ...gmsdBase, ...override, type: \"gmsd\" };\n }\n\n return {\n ...(base as DiffOptionsPixel),\n ...(override as DiffOptionsPixel),\n type: \"pixel\",\n };\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n const browser = await browserClass.launch({\n headless: this.headless,\n });\n\n if (!browser)\n throw new Error(\"Something went wrong with starting the browser.\");\n\n this.browser = browser;\n\n const tempCtx = await browser.newContext();\n const tempPage = await tempCtx.newPage();\n const defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);\n await tempCtx.close();\n\n // Create N contexts and pages in parallel\n const results = await Promise.all(\n Array.from({ length: this.concurrency }, async () => {\n const context = await browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n return { context, page };\n }),\n );\n\n this.contexts = results.map((r) => r.context);\n this.pages = results.map((r) => r.page);\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n for (const context of this.contexts) {\n await context.close();\n }\n if (this.browser) {\n await this.browser.close();\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: this.connectionTimeout,\n });\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n await this.filesystem.ensureParentDir(filepath);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\n const screenshotOptions = {\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: string | Buffer,\n options: ScreenshotSettings & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n diffOverride?: DiffOptions,\n ): Promise<{\n screenshotPath: string;\n comparisonResult: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage ?? this.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n diffOverride,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n await this.filesystem.writeActualFile(\n filename,\n retryScreenshot.screenshotPath,\n );\n this.logger.debug(`Actual screenshot saved: ${filepath}`);\n\n if (retryScreenshot.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n retryScreenshot.comparisonResult?.diffBuffer &&\n !retryScreenshot.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n\n await this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n\n // When interpretation is enabled, persist diff stats + interpretation as\n // a sidecar so the review UI and CLI can surface them after rebuilding\n // state from disk. Skipped entirely otherwise so no extra files appear\n // for users who have not opted in (pixel only).\n const result = retryScreenshot.comparisonResult;\n if (\"numDiffPixels\" in result && result.interpretation) {\n await this.filesystem.writeDiffMetaFile(diffFilename, {\n numDiffPixels: result.numDiffPixels,\n percentDifference: result.percentDifference,\n interpretation: result.interpretation,\n });\n }\n }\n\n // different sizes diff image\n if (\n retryScreenshot.comparisonResult !== null &&\n typeof retryScreenshot.comparisonResult === \"object\" &&\n \"differentSizes\" in retryScreenshot.comparisonResult &&\n retryScreenshot.comparisonResult.differentSizes\n ) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = await createDiffSizePngImage(200, 200);\n\n await this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult: retryScreenshot.comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async retryScreenshot(\n page: Page,\n referenceImage: string | Buffer,\n options: ScreenshotSettings,\n diffOverride?: DiffOptions,\n ) {\n const diffConfig = this.mergeDiffOptions(diffOverride);\n\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\n ...options,\n delay: this.getIncBackoffDelay(i, options.delay || 0),\n });\n\n if (!screenshotBuffer) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n const comparisonResult =\n diffConfig.type === \"gmsd\"\n ? await compareImagesGMSD(\n screenshotBuffer,\n referenceImage,\n true,\n diffConfig as DiffConfigGMSD,\n )\n : await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n diffConfig as DiffConfig,\n );\n\n // last retry\n if (i === this.retries - 1 && !comparisonResult.passed) {\n this.logger.error(\n `Failed to match screenshot after ${this.retries} retries`,\n );\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\n }\n\n if (comparisonResult.passed) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: true,\n };\n } else {\n const summary =\n \"numDiffPixels\" in comparisonResult\n ? comparisonResult.differentSizes\n ? \"different image sizes\"\n : `${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`\n : `gmsd score ${comparisonResult.gmsd.toFixed(4)}`;\n\n this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${summary}`,\n );\n }\n } catch (error) {\n this.logger.error(\n `Error taking screenshot after ${i + 1} retries:`,\n (error as Error).message,\n );\n }\n }\n\n return {\n screenshotPath: null,\n comparisonResult: null,\n passed: false,\n };\n }\n\n getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n captureStart?: number;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const start = extras.captureStart ?? performance.now();\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n const diffOverride = extras.diff;\n\n if (!(await this.filesystem.hasExpectedFile(filename))) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.getExpectedFilePath(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n diffOverride,\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n const duration = Math.round(performance.now() - start);\n this.logger.debug(`${filename} captured in ${duration}ms`);\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n const baseDiffOverride = extras.diff;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n const baseDiffOverride = extras.diff;\n\n // Capture base screenshot\n let baseStart: number;\n if (!extras.skipBaseNavigation) {\n baseStart = performance.now();\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n } else {\n baseStart = performance.now();\n }\n\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart ?? baseStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n const variantStart = performance.now();\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n captureStart: variantStart,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Gets the exponential backoff delay\n */\n getIncBackoffDelay(i: number, delay: number): number {\n return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;\n }\n\n /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,eAAe,OAAO,KAAK;CAC/B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAC5C,CAAC;AAKD,MAAM,4BAAW,IAAI,YAAY,GAAG,EAAA,CAAE,KAAK,GAAG,UAAU;CACtD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;CAG7C,OAAO,MAAM;AACf,CAAC;;;;;;;;;;;AAYD,UAAU,WAAW,QAAwC;CAC3D,IAAI,SAAS,aAAa;CAE1B,OAAO,SAAS,KAAK,OAAO,QAAQ;EAClC,MAAM,SAAS,OAAO,aAAa,MAAM;EACzC,MAAM,OAAO,OAAO,SAAS,SAAS,SAAS,GAAG,SAAS,CAAC;EAC5D,MAAM,YAAY,SAAS;EAC3B,MAAM,UAAU,YAAY;EAE5B,IAAI,UAAU,OAAO,QACnB;EAKF,MAAM;GAAE;GAAM,MAFD,OAAO,SAAS,WAAW,OAEvB;GAAG;GAAQ;EAAO;EAEnC,SAAS,UAAU;EAEnB,IAAI,SAAS,QACX;CAEJ;AACF;;;;AAKA,SAAgB,gBAAgB,KAAa,OAAe;CAC1D,MAAM,YAAY,OAAO,KAAK,KAAK,QAAQ;CAC3C,MAAM,cAAc,OAAO,KAAK,OAAO,QAAQ;CAC/C,MAAM,OAAO,OAAO,OAAO;EAAC;EAAW,OAAO,KAAK,CAAC,CAAC,CAAC;EAAG;CAAW,CAAC;CACrE,MAAM,eAAe,OAAO,MAAM,CAAC;CACnC,MAAM,aAAa,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AM,IAAI,MAAM,cAAc,MAAM,cAAc;EAGpD,OAAO,KAAK,MAAM;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["open","readFile","writeFile","gmsd","fsp","path","os","fs","blazediffCompare","interpret","path","fsp","glob","getLogger","fs","path","fsp","path","glob","randomUUID","relative","getLogger","path","path","createHash","glob","path","path","path"],"sources":["../src/features/png/util.ts","../src/features/png/png.ts","../src/compare/gmsd.ts","../src/compare/pixel.ts","../src/config.ts","../src/mapWithConcurrency.ts","../src/filesystem.ts","../src/screenshots/manifest.ts","../src/runner/tasks.ts","../src/runner/types.ts","../src/runner/CaptureRunner.ts","../src/screenshot.ts","../src/screenshots/groupScreenshots.ts","../src/screenshots/collectScreenshots.ts","../src/engine/RunStore.ts","../src/engine/types.ts","../src/engine/WarmBrowser.ts","../src/engine/WatchSession.ts","../src/engine/LocalEngine.ts","../src/store.ts"],"sourcesContent":["import { open } from \"node:fs/promises\";\nimport type { MetadataEntries } from \"./types\";\n\ntype ParsedChunk = {\n type: string;\n data: Buffer;\n length: number;\n offset: number;\n};\n\n// Magic Bytes:\n// The first 8 bytes of every valid PNG file.\n// Used to verify that the file is actually a PNG before processing.\nconst pngSignature = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\n// A pre-calculated lookup table for the CRC32 algorithm.\n// We use this to quickly calculate the checksum for each chunk we write.\n// Without this table, calculating CRC bit-by-bit would be significantly slower.\nconst crcTable = new Uint32Array(256).map((_, index) => {\n let c = index;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n\n return c >>> 0;\n});\n\n/**\n * Chunk Parser Generator\n *\n * A PNG file is essentially a list of chunks.\n * Structure of a chunk:\n * 1. Length (4 bytes): The size of the data field.\n * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').\n * 3. Data (Length bytes): The actual payload.\n * 4. CRC (4 bytes): Checksum.\n */\nfunction* readChunks(buffer: Buffer): Generator<ParsedChunk> {\n let offset = pngSignature.length;\n\n while (offset + 8 <= buffer.length) {\n const length = buffer.readUInt32BE(offset);\n const type = buffer.toString(\"ascii\", offset + 4, offset + 8);\n const dataStart = offset + 8;\n const dataEnd = dataStart + length;\n\n if (dataEnd > buffer.length) {\n return;\n }\n\n const data = buffer.subarray(dataStart, dataEnd);\n\n yield { type, data, length, offset };\n\n offset = dataEnd + 4; // Skip CRC\n\n if (type === \"IEND\") {\n return;\n }\n }\n}\n\n/**\n * Constructs a raw binary `tEXt` chunk.\n */\nexport function createTextChunk(key: string, value: string) {\n const keyBuffer = Buffer.from(key, \"latin1\");\n const valueBuffer = Buffer.from(value, \"latin1\");\n const data = Buffer.concat([keyBuffer, Buffer.from([0]), valueBuffer]);\n const lengthBuffer = Buffer.alloc(4);\n const typeBuffer = Buffer.from(\"tEXt\");\n\n lengthBuffer.writeUInt32BE(data.length, 0);\n\n const crcBuffer = Buffer.alloc(4);\n crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);\n\n return Buffer.concat([lengthBuffer, typeBuffer, data, crcBuffer]);\n}\n\n/**\n * Calculates the CRC32 checksum for a buffer.\n * Used to ensure data integrity.\n */\nexport function crc32(buffer: Buffer) {\n let crc = 0 ^ -1;\n\n for (let i = 0; i < buffer.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the index is valid\n crc = (crc >>> 8) ^ crcTable[(crc ^ buffer[i]!) & 0xff]!;\n }\n\n return (crc ^ -1) >>> 0;\n}\n\n/**\n * Helper to locate the IEND chunk, which marks the end of a PNG stream.\n */\nfunction findIendChunk(buffer: Buffer): ParsedChunk | undefined {\n for (const chunk of readChunks(buffer)) {\n if (chunk.type === \"IEND\") {\n return chunk;\n }\n }\n\n return undefined;\n}\n\n/**\n * Inserts metadata chunks into a PNG buffer.\n * It places them right before the final `IEND` chunk.\n */\nexport function injectTextMetadata(buffer: Buffer, metadata: MetadataEntries) {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return buffer;\n }\n\n const iendChunk = findIendChunk(buffer);\n if (!iendChunk) {\n return buffer;\n }\n\n const textChunks = Object.entries(metadata).map(([key, value]) =>\n createTextChunk(key, value),\n );\n\n return Buffer.concat([\n buffer.subarray(0, iendChunk.offset),\n ...textChunks,\n buffer.subarray(iendChunk.offset),\n ]);\n}\n\nexport function isValidPngSignature(buffer: Buffer): boolean {\n if (buffer.length < pngSignature.length) return false;\n return buffer.subarray(0, pngSignature.length).equals(pngSignature);\n}\n\nconst IHDR_MIN_BYTES = 24;\n\nexport async function readIhdrDimensions(\n source: string | Buffer,\n): Promise<{ width: number; height: number }> {\n let buf: Buffer;\n\n if (typeof source === \"string\") {\n const fh = await open(source, \"r\");\n try {\n buf = Buffer.alloc(IHDR_MIN_BYTES);\n await fh.read(buf, 0, IHDR_MIN_BYTES, 0);\n } finally {\n await fh.close();\n }\n } else {\n buf = source;\n }\n\n if (\n buf.length < IHDR_MIN_BYTES ||\n !buf.subarray(0, pngSignature.length).equals(pngSignature)\n ) {\n throw new Error(\"Not a valid PNG\");\n }\n\n const width = buf.readUInt32BE(16);\n const height = buf.readUInt32BE(20);\n return { width, height };\n}\n\n/**\n * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.\n */\nexport function extractTextMetadata(buffer: Buffer): MetadataEntries {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return {};\n }\n\n const metadata: MetadataEntries = {};\n\n for (const chunk of readChunks(buffer)) {\n if (chunk.type !== \"tEXt\") {\n continue;\n }\n\n const separatorIndex = chunk.data.indexOf(0);\n if (separatorIndex < 0) {\n continue;\n }\n\n const key = chunk.data.toString(\"latin1\", 0, separatorIndex);\n const value = chunk.data.toString(\"latin1\", separatorIndex + 1);\n\n metadata[key] = value;\n }\n\n return metadata;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport sharp from \"sharp\";\nimport type { MetadataEntries } from \"./types\";\nimport { extractTextMetadata, injectTextMetadata } from \"./util\";\n\n/**\n * A wrapper around `sharp` that adds support for reading and writing\n * textual metadata (tEXt chunks). Used for fast PNG decode/encode.\n */\nexport class PNG {\n private width_: number;\n private height_: number;\n private data_: Buffer;\n private sourcePath?: string;\n private metadataEntries: MetadataEntries;\n\n private constructor(\n width: number,\n height: number,\n data: Buffer,\n sourcePath?: string,\n metadata?: MetadataEntries,\n ) {\n this.width_ = width;\n this.height_ = height;\n this.data_ = data;\n this.sourcePath = sourcePath;\n this.metadataEntries = { ...(metadata ?? {}) };\n }\n\n static create(width: number, height: number): PNG {\n const data = Buffer.alloc(width * height * 4, 0);\n return new PNG(width, height, data);\n }\n\n static async load(source: string | Buffer): Promise<PNG> {\n const buffer = typeof source === \"string\" ? await readFile(source) : source;\n const metadata = extractTextMetadata(buffer);\n\n const pipeline = sharp(buffer).ensureAlpha();\n const { data: raw, info } = await pipeline\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const data = Buffer.from(raw);\n const sourcePath = typeof source === \"string\" ? source : undefined;\n\n return new PNG(info.width, info.height, data, sourcePath, metadata);\n }\n\n get width(): number {\n return this.width_;\n }\n\n get height(): number {\n return this.height_;\n }\n\n get data(): Buffer {\n return this.data_;\n }\n\n get metadata(): MetadataEntries {\n return { ...this.metadataEntries };\n }\n\n setMetadata(key: string, value: string): void {\n this.metadataEntries = { ...this.metadataEntries, [key]: value };\n }\n\n replaceMetadata(metadata: MetadataEntries): void {\n this.metadataEntries = { ...metadata };\n }\n\n removeMetadata(key: string): void {\n const { [key]: _, ...remaining } = this.metadataEntries;\n this.metadataEntries = remaining;\n }\n\n clearMetadata(): void {\n this.metadataEntries = {};\n }\n\n async toBuffer(): Promise<Buffer> {\n const baseBuffer = await sharp(this.data_, {\n raw: { width: this.width_, height: this.height_, channels: 4 },\n })\n .png()\n .toBuffer();\n\n if (Object.keys(this.metadataEntries).length === 0) {\n return baseBuffer;\n }\n\n return injectTextMetadata(baseBuffer, this.metadataEntries);\n }\n\n async save(filepath?: string): Promise<void> {\n const targetPath = filepath ?? this.sourcePath;\n\n if (!targetPath) {\n throw new Error(\"No filepath provided for saving PNG\");\n }\n\n await writeFile(targetPath, await this.toBuffer());\n }\n}\n","import fs from \"node:fs\";\nimport gmsd, { type GmsdOptions } from \"@blazediff/gmsd\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport type { DiffConfigGMSD } from \"../types\";\n\nexport type CompareOptions = GmsdOptions;\n\nexport interface CompareResult {\n gmsd: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: GmsdOptions,\n) => {\n return gmsd(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImagesGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfigGMSD = {},\n): Promise<CompareResult> {\n // Load both PNGs in parallel with sharp for better performance\n const [png1, png2] = await Promise.all([loadPNG(image1), loadPNG(image2)]);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return { gmsd: Infinity, passed: false };\n }\n\n const diff = withDiff ? PNG.create(width, height) : undefined;\n\n try {\n const gmsd = compare(png1.data, png2.data, diff?.data, width, height, {\n downsample: options.downsample ?? 0,\n c: options.c ?? 170,\n });\n\n // Convert diff image to buffer\n const diffBuffer = diff\n ? await annotateDiffImage(diff, options).toBuffer()\n : undefined;\n\n return {\n gmsd,\n diffBuffer,\n passed: gmsd <= (options.threshold ?? 0.1),\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n gmsd: Infinity,\n passed: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n return PNG.load(source);\n}\n\nfunction annotateDiffImage(image: PNG, options: DiffConfigGMSD) {\n image.setMetadata(\"cappa.diff.algorithm\", \"gmsd\");\n\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined) {\n continue;\n }\n\n image.setMetadata(`cappa.diff.${key}`, String(value));\n }\n\n return image;\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatchGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfigGMSD = {},\n): Promise<boolean> {\n const result = await compareImagesGMSD(image1, image2, false, options);\n\n return result.passed;\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type BlazeDiffOptions,\n type BlazeDiffResult,\n compare as blazediffCompare,\n} from \"@blazediff/core-native\";\nimport { type InterpretResult, interpret } from \"@blazediff/interpret-native\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport {\n injectTextMetadata,\n isValidPngSignature,\n readIhdrDimensions,\n} from \"../features/png/util\";\nimport type { DiffConfig } from \"../types\";\n\n/** Pixel diff options: Cappa `DiffConfig` plus optional native-only output tuning. */\nexport type CompareOptions = DiffConfig &\n Partial<Pick<BlazeDiffOptions, \"diffMask\" | \"compression\" | \"quality\">>;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\n interpretation?: InterpretResult; // Structured diff analysis (when `interpret` is enabled)\n}\n\ntype TempState = { tempRoot?: string };\n\nasync function ensureTempRoot(state: TempState): Promise<string> {\n if (!state.tempRoot) {\n state.tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), \"cappa-pxl-\"));\n }\n return state.tempRoot;\n}\n\nasync function resolveInputPath(\n source: string | Buffer,\n fileName: string,\n state: TempState,\n): Promise<string> {\n if (typeof source === \"string\") {\n await fsp.access(source, fs.constants.R_OK);\n return path.resolve(source);\n }\n\n if (!isValidPngSignature(source)) {\n throw new Error(\"Invalid PNG buffer: missing PNG signature\");\n }\n\n const root = await ensureTempRoot(state);\n const dest = path.join(root, fileName);\n await fsp.writeFile(dest, source);\n return dest;\n}\n\nfunction toNativeOptions(config: DiffConfig): BlazeDiffOptions {\n const extra = config as CompareOptions;\n const out: BlazeDiffOptions = {\n threshold: extra.threshold,\n antialiasing: extra.includeAA ?? false,\n };\n\n if (extra.diffMask !== undefined) {\n out.diffMask = extra.diffMask;\n }\n if (extra.compression !== undefined) {\n out.compression = extra.compression;\n }\n if (extra.quality !== undefined) {\n out.quality = extra.quality;\n }\n\n return out;\n}\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n const state: TempState = {};\n let diffPath: string | undefined;\n\n try {\n const p1 = await resolveInputPath(image1, \"expected.png\", state);\n const p2 = await resolveInputPath(image2, \"actual.png\", state);\n\n if (withDiff) {\n const root = await ensureTempRoot(state);\n diffPath = path.join(root, \"diff.png\");\n }\n\n const wantInterpret = !!(options as CompareOptions).interpret && withDiff;\n\n let nativeResult: BlazeDiffResult;\n\n try {\n // Never pass `interpret` to `compare` — the native binding skips writing\n // the diff image when interpret mode is on. Interpretation is fetched in\n // a separate call below when needed.\n nativeResult = await blazediffCompare(\n p1,\n p2,\n withDiff ? diffPath : undefined,\n toNativeOptions(options),\n );\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n\n if (nativeResult.match === false) {\n if (nativeResult.reason === \"file-not-exists\") {\n throw new Error(`File not found: ${nativeResult.file}`);\n }\n\n if (nativeResult.reason === \"layout-diff\") {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n }\n\n const { width, height } = await readIhdrDimensions(p1);\n const totalPixels = width * height;\n\n if (nativeResult.match) {\n return {\n numDiffPixels: 0,\n totalPixels,\n percentDifference: 0,\n diffBuffer: undefined,\n passed: isPassed(0, 0, options),\n differentSizes: false,\n };\n }\n\n let diffBuffer: Buffer | undefined;\n if (withDiff && diffPath) {\n const rawDiff = await fsp.readFile(diffPath);\n const diffMetadata: Record<string, string> = {\n \"cappa.diff.algorithm\": \"pixel\",\n };\n for (const [key, value] of Object.entries(options)) {\n if (value !== undefined) {\n diffMetadata[`cappa.diff.${key}`] = String(value);\n }\n }\n diffBuffer = injectTextMetadata(rawDiff, diffMetadata);\n }\n\n const numDiffPixels = nativeResult.diffCount;\n const percentDifference = nativeResult.diffPercentage;\n\n let interpretation: InterpretResult | undefined;\n if (wantInterpret && !nativeResult.match) {\n try {\n interpretation = await interpret(p1, p2, undefined, {\n source: \"pixel\",\n threshold: options.threshold,\n antialiasing: options.includeAA ?? false,\n });\n } catch {\n // Interpretation is best-effort; don't fail the comparison.\n }\n }\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n differentSizes: false,\n interpretation,\n };\n } finally {\n if (state.tempRoot) {\n await fsp\n .rm(state.tempRoot, { recursive: true, force: true })\n .catch(() => {\n // ignore cleanup errors\n });\n }\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\n */\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport async function createDiffSizePngImage(\n width: number,\n height: number,\n): Promise<Buffer> {\n const png = PNG.create(width, height);\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return png.toBuffer();\n}\n","import type { ConfigEnv, PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","/**\n * Run async work over `items` with at most `concurrency` tasks in flight.\n * Preserves failure behavior: the first rejection rejects the returned promise.\n * Results are returned in the same order as the input items.\n */\nexport async function mapWithConcurrency<T, R = void>(\n concurrency: number,\n items: readonly T[],\n fn: (item: T, workerIndex: number) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, concurrency);\n const workerCount = Math.min(limit, items.length);\n const results: R[] = new Array(items.length);\n let next = 0;\n\n const worker = async (workerIndex: number): Promise<void> => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n const item = items[i];\n if (item === undefined) {\n return;\n }\n results[i] = await fn(item, workerIndex);\n }\n };\n\n await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));\n\n return results;\n}\n","import fs from \"node:fs\";\nimport fsp, { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getLogger } from \"@cappa/logger\";\nimport { imagesMatch } from \"./compare/pixel\";\nimport { extractTextMetadata, injectTextMetadata } from \"./features/png/util\";\nimport { mapWithConcurrency } from \"./mapWithConcurrency\";\nimport type {\n DiffConfig,\n DiffMetadata,\n DiffOptions,\n Screenshot,\n} from \"./types\";\n\nconst APPROVE_SCREENSHOTS_CONCURRENCY = 8;\n\n/**\n * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).\n */\nexport function toDiffMetaPath(diffImagePath: string): string {\n const ext = path.extname(diffImagePath);\n return ext\n ? `${diffImagePath.slice(0, -ext.length)}.json`\n : `${diffImagePath}.json`;\n}\n\n/**\n * Read a diff metadata sidecar, returning `undefined` when it is missing or\n * cannot be parsed (so callers can degrade gracefully).\n */\nexport async function readDiffMeta(\n diffImagePath: string,\n): Promise<DiffMetadata | undefined> {\n try {\n const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), \"utf8\");\n return JSON.parse(raw) as DiffMetadata;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actual: string;\n private readonly expected: string;\n private readonly diff: string;\n\n constructor(outputDir: string) {\n this.actual = path.resolve(outputDir, \"actual\");\n this.expected = path.resolve(outputDir, \"expected\");\n this.diff = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDirSync(this.actual);\n this.ensureParentDirSync(this.expected);\n this.ensureParentDirSync(this.diff);\n }\n\n clearActual() {\n this.removeDir(this.actual);\n }\n\n clearDiff() {\n this.removeDir(this.diff);\n }\n\n getActualScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.actual, \"**/*.png\")));\n }\n\n getExpectedScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.expected, \"**/*.png\")));\n }\n\n getDiffScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.diff, \"**/*.png\")));\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actual, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).\n */\n async approveScreenshots(\n screenshots: Screenshot[],\n diff: DiffOptions,\n ): Promise<void> {\n const outputDir = path.dirname(this.actual);\n\n await mapWithConcurrency(\n APPROVE_SCREENSHOTS_CONCURRENCY,\n screenshots,\n (screenshot) => this.approveOneScreenshot(screenshot, outputDir, diff),\n );\n }\n\n private async approveOneScreenshot(\n screenshot: Screenshot,\n outputDir: string,\n diff: DiffOptions,\n ): Promise<void> {\n const logger = getLogger();\n\n logger.debug(`Approving screenshot with category: ${screenshot.category}`);\n\n if (screenshot.category === \"new\") {\n logger.debug(`Approving new screenshot: ${screenshot.actualPath}`);\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"deleted\") {\n logger.debug(`Deleting expected screenshot: ${screenshot.expectedPath}`);\n await fsp.unlink(path.resolve(outputDir, screenshot.expectedPath));\n return;\n }\n\n if (screenshot.category === \"changed\") {\n logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"passed\") {\n if (!screenshot.expectedPath) {\n throw new Error(\"Expected path is required for passed screenshots\");\n }\n\n const matches = await imagesMatch(\n path.resolve(outputDir, screenshot.actualPath),\n path.resolve(outputDir, screenshot.expectedPath),\n diff.type === \"gmsd\"\n ? { threshold: diff.threshold }\n : (diff as DiffConfig),\n );\n\n if (!matches) {\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n }\n }\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private async approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actual, relativePath);\n const expectedPath = path.resolve(this.expected, relativePath);\n const diffPath = path.resolve(this.diff, relativePath);\n\n await this.ensureParentDir(expectedPath);\n\n await fsp.copyFile(actualPath, expectedPath);\n\n try {\n await fsp.access(diffPath);\n } catch {\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n await this.copyDiffMetadataToExpected(diffPath, expectedPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n private async copyDiffMetadataToExpected(\n diffPath: string,\n expectedPath: string,\n ): Promise<void> {\n const diffExtension = path.extname(diffPath).toLowerCase();\n const expectedExtension = path.extname(expectedPath).toLowerCase();\n\n if (diffExtension !== \".png\" || expectedExtension !== \".png\") {\n return;\n }\n\n try {\n const diffBuffer = await fsp.readFile(diffPath);\n const diffMetadata = extractTextMetadata(diffBuffer);\n\n if (Object.keys(diffMetadata).length === 0) {\n return;\n }\n\n const expectedBuffer = await fsp.readFile(expectedPath);\n const expectedMetadata = extractTextMetadata(expectedBuffer);\n\n const mergedMetadata = {\n ...expectedMetadata,\n ...diffMetadata,\n };\n\n const expectedWithMetadata = injectTextMetadata(\n expectedBuffer,\n mergedMetadata,\n );\n await fsp.writeFile(expectedPath, expectedWithMetadata);\n } catch {\n // Ignore metadata transfer errors to keep approval resilient.\n }\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n async ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n await fsp.mkdir(dir, { recursive: true });\n }\n\n /**\n * Synchronous version used only during constructor initialization.\n */\n private ensureParentDirSync(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actual;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expected;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diff;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actual, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expected, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diff, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n async writeActualFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getActualFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n async writeDiffFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Get the path to a diff metadata sidecar file (`<name>.json`)\n */\n getDiffMetaFilePath(filename: string): string {\n return toDiffMetaPath(this.getDiffFilePath(filename));\n }\n\n /**\n * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.\n */\n async writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void> {\n const filepath = this.getDiffMetaFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, JSON.stringify(meta));\n }\n\n /**\n * Check if an expected file exists\n */\n async hasExpectedFile(filename: string): Promise<boolean> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n await fsp.access(expectedPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read an expected file\n */\n async readExpectedFile(filename: string): Promise<Buffer> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n return await fsp.readFile(expectedPath);\n } catch {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n }\n\n /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actual, filePath);\n }\n\n getRelativePath(directory: \"actual\" | \"expected\" | \"diff\", filePath: string) {\n const relativePath = path.relative(this[directory], filePath);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot resolve relative path outside of ${directory} directory: ${filePath}`,\n );\n }\n\n return relativePath;\n }\n}\n","import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Maps a screenshot back to the capture task that produced it.\n *\n * Nothing on disk carries this. A screenshot's name comes from the filename a\n * plugin chose (`example/button/primary`), while the task id comes from the\n * plugin's own addressing scheme (`example-button--primary` for Storybook) —\n * and there is no rule connecting the two. Without a record written at capture\n * time, \"re-capture this one screenshot\" has no task to ask for, which is\n * exactly how the review UI's re-capture button came to send a name the engine\n * had never heard of.\n *\n * Kept beside `actual/` and `expected/` rather than inside them so it is never\n * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is\n * configured with `serveDotFiles: false`) will not serve it.\n */\nexport const MANIFEST_FILENAME = \".cappa-manifest.json\";\n\n/** Bumped only if the on-disk shape changes incompatibly. */\nexport const MANIFEST_VERSION = 1;\n\n/** Where a screenshot came from. */\nexport type ScreenshotOrigin = {\n /** Task id as `discover` produced it — what `startRun` accepts. */\n taskId: string;\n /** Plugin that owns the task. */\n plugin: string;\n};\n\nexport type CaptureManifest = {\n version: number;\n /** Keyed by screenshot name (relative path, no `.png`). */\n screenshots: Record<string, ScreenshotOrigin>;\n};\n\nexport const emptyManifest = (): CaptureManifest => ({\n version: MANIFEST_VERSION,\n screenshots: {},\n});\n\nexport const manifestPath = (outputDir: string): string =>\n path.resolve(outputDir, MANIFEST_FILENAME);\n\n/**\n * The key a capture filename is recorded under.\n *\n * Must match the `name` `groupScreenshots` derives, or a lookup silently\n * misses: the relative path with its `.png` dropped, and separators normalised\n * so a manifest written on Windows is readable on Linux.\n */\nexport const toManifestKey = (filename: string): string =>\n filename\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.png$/i, \"\");\n\nconst isOrigin = (value: unknown): value is ScreenshotOrigin =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ScreenshotOrigin).taskId === \"string\" &&\n typeof (value as ScreenshotOrigin).plugin === \"string\";\n\n/**\n * Read the manifest, or an empty one.\n *\n * Never throws: the manifest is an optimisation, and a missing, truncated or\n * hand-edited file must degrade to \"we do not know where this came from\"\n * rather than break the screenshot index every command depends on.\n */\nexport const readCaptureManifest = async (\n outputDir: string,\n): Promise<CaptureManifest> => {\n try {\n const raw = await fsp.readFile(manifestPath(outputDir), \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n (parsed as CaptureManifest).version !== MANIFEST_VERSION\n ) {\n return emptyManifest();\n }\n\n const screenshots = (parsed as CaptureManifest).screenshots;\n if (typeof screenshots !== \"object\" || screenshots === null) {\n return emptyManifest();\n }\n\n const entries = Object.entries(screenshots).filter(([, origin]) =>\n isOrigin(origin),\n );\n\n return {\n version: MANIFEST_VERSION,\n screenshots: Object.fromEntries(entries) as Record<\n string,\n ScreenshotOrigin\n >,\n };\n } catch {\n return emptyManifest();\n }\n};\n\n/**\n * Merge freshly captured origins into whatever the manifest already holds.\n *\n * A run only captures the tasks it was asked for, so existing entries have to\n * survive — otherwise re-capturing one screenshot would strip every other\n * screenshot's origin and disable the button that started it.\n *\n * `knownNames`, when given, is the set of screenshots that currently exist;\n * entries outside it are dropped so renames and deletions do not accumulate\n * forever. New origins are always kept, whether or not they appear in it.\n */\nexport const mergeCaptureManifest = (\n existing: CaptureManifest,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): CaptureManifest => {\n const keep = knownNames ? new Set(knownNames) : undefined;\n\n const merged: Record<string, ScreenshotOrigin> = {};\n\n for (const [name, origin] of Object.entries(existing.screenshots)) {\n if (!keep || keep.has(name)) {\n merged[name] = origin;\n }\n }\n\n for (const [name, origin] of Object.entries(origins)) {\n merged[name] = origin;\n }\n\n return { version: MANIFEST_VERSION, screenshots: merged };\n};\n\n/**\n * Persist `origins`, merged over what is already recorded.\n *\n * Best-effort by design: a read-only or full disk must not turn a successful\n * capture run into a failed one, so a write failure is reported to the caller\n * as `false` rather than thrown.\n */\nexport const recordCaptureOrigins = async (\n outputDir: string,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): Promise<boolean> => {\n try {\n const merged = mergeCaptureManifest(\n await readCaptureManifest(outputDir),\n origins,\n knownNames,\n );\n\n await fsp.mkdir(path.resolve(outputDir), { recursive: true });\n await fsp.writeFile(\n manifestPath(outputDir),\n `${JSON.stringify(merged, null, 2)}\\n`,\n \"utf8\",\n );\n\n return true;\n } catch {\n return false;\n }\n};\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type { PluginCaptureResult, TaskStatus } from \"./types\";\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * Decide whether a plugin's `execute` result represents a failed screenshot.\n *\n * Plugins return loosely-shaped objects, so this inspects the three signals that\n * matter: an explicit `error`, an explicit `success: false`, or a missing\n * `filepath` on a task that was not skipped.\n */\nexport const didScreenshotFail = (result: unknown): boolean => {\n if (!isObject(result)) {\n return false;\n }\n\n if (\"error\" in result && result.error != null) {\n return true;\n }\n\n if (\"success\" in result) {\n const { success } = result as PluginCaptureResult;\n if (success === false) {\n return true;\n }\n }\n\n if (\"filepath\" in result) {\n const { filepath, skipped } = result as PluginCaptureResult;\n if (!filepath && skipped !== true) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Map a plugin result onto the status shown in the UI.\n *\n * Mirrors the screenshot categories: a capture with no baseline is `new`, a\n * failing comparison is `changed`, and anything `didScreenshotFail` flags for\n * another reason is `failed`.\n */\nexport const toTaskStatus = (result: unknown): TaskStatus => {\n if (!isObject(result)) {\n return \"passed\";\n }\n\n const typed = result as PluginCaptureResult;\n\n if (typed.skipped === true) {\n return \"skipped\";\n }\n\n if (\"error\" in typed && typed.error != null) {\n return \"failed\";\n }\n\n if (typed.isNew === true) {\n return \"new\";\n }\n\n if (typed.success === false) {\n return \"changed\";\n }\n\n if (didScreenshotFail(typed)) {\n return \"failed\";\n }\n\n return \"passed\";\n};\n\n/** Restrict `tasks` to those whose id matches the glob `filter`. */\nexport function filterTasks(tasks: PluginTask[], filter: string): PluginTask[] {\n return tasks.filter((task) => path.matchesGlob(task.id, filter));\n}\n\n/** Restrict `tasks` to an explicit set of ids. */\nexport function selectTasks(\n tasks: PluginTask[],\n taskIds: readonly string[],\n): PluginTask[] {\n const wanted = new Set(taskIds);\n return tasks.filter((task) => wanted.has(task.id));\n}\n\n/**\n * Baselines in `expected/` that have no counterpart in `actual/` — screenshots\n * that existed when the baseline was approved but were not captured this run.\n */\nexport async function getDeletedScreenshots(\n outputDir: string,\n): Promise<string[]> {\n const actualDir = path.resolve(outputDir, \"actual\");\n const expectedDir = path.resolve(outputDir, \"expected\");\n\n const [actualFiles, expectedFiles] = await Promise.all([\n Array.fromAsync(glob(path.join(actualDir, \"**/*.png\"))),\n Array.fromAsync(glob(path.join(expectedDir, \"**/*.png\"))),\n ]);\n\n const actualRelative = new Set(\n actualFiles.map((p) => path.relative(actualDir, p)),\n );\n\n return expectedFiles\n .map((p) => path.relative(expectedDir, p))\n .filter((rel) => !actualRelative.has(rel));\n}\n","import type { PluginTask, PluginWatch } from \"../plugin\";\n\n/**\n * Lifecycle of a single capture run.\n *\n * ```\n * idle → discovering → running → (completed | failed | cancelled)\n * ```\n */\nexport type RunState =\n | \"idle\"\n | \"discovering\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\n/**\n * Terminal state of an individual capture task.\n *\n * `passed` / `changed` / `new` mirror the screenshot categories; `failed` means\n * the plugin reported a failure (see `didScreenshotFail`); `skipped` means the\n * plugin deliberately skipped the task.\n */\nexport type TaskStatus =\n | \"pending\"\n | \"running\"\n | \"passed\"\n | \"changed\"\n | \"new\"\n | \"failed\"\n | \"skipped\";\n\n/** A discovered, runnable capture task together with the plugin that owns it. */\nexport type Target = {\n id: string;\n url: string;\n plugin: string;\n};\n\n/**\n * Why a run was started, when it was not started by hand.\n *\n * Purely informational — the runner does nothing with it. It rides along on the\n * request so a run list can say \"this one came from saving Button.stories.tsx\"\n * without a second lookup or a parallel event stream.\n */\nexport type RunTrigger = {\n source: \"watch\";\n /** Changed files that triggered the run, relative to the watch root. */\n files: string[];\n};\n\n/**\n * Describes which subset of the discovered tasks a run should capture.\n *\n * `filter` and `taskIds` compose: a task must satisfy both when both are given.\n */\nexport type StartRunRequest = {\n /** Restrict the run to these plugin names. Omit to run every plugin. */\n plugins?: string[];\n /** Glob matched against task ids (`path.matchesGlob` semantics). */\n filter?: string;\n /** Explicit task ids to capture. Ids not discovered are ignored. */\n taskIds?: string[];\n /**\n * Clear `actual/` and `diff/` before capturing.\n *\n * Always `true` for a full CLI run. A UI re-capturing a single screenshot must\n * pass `false`, otherwise the rest of the run's output is destroyed.\n * @default true\n */\n clearActual?: boolean;\n /** What started this run, when it was not a person. */\n trigger?: RunTrigger;\n};\n\n/** An error flattened into something that survives a structured-clone or JSON. */\nexport type SerializedError = {\n name: string;\n message: string;\n stack?: string;\n};\n\nexport const toSerializedError = (error: unknown): SerializedError => {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n }\n\n return { name: \"Error\", message: String(error) };\n};\n\n/**\n * The shape plugins return from `execute`. Every field is optional because\n * plugins are free to return whatever they want — only these keys are\n * interpreted (by `didScreenshotFail`) and surfaced in failure reports.\n */\nexport type PluginCaptureResult = {\n success?: boolean;\n skipped?: boolean;\n isNew?: boolean;\n error?: unknown;\n filepath?: string;\n storyId?: string;\n storyName?: string;\n [key: string]: unknown;\n};\n\n/** A task that did not produce a passing screenshot. */\nexport type TaskFailure = {\n taskId: string;\n taskUrl: string;\n pluginName: string;\n result: PluginCaptureResult;\n};\n\n/** Per-task record kept for the lifetime of a run. */\nexport type TaskRecord = {\n id: string;\n url: string;\n plugin: string;\n status: TaskStatus;\n durationMs?: number;\n result?: PluginCaptureResult;\n};\n\n/** Coarse, serializable view of a run — enough to render a list row. */\nexport type RunSummary = {\n id: string;\n state: RunState;\n request: StartRunRequest;\n startedAt: number;\n finishedAt?: number;\n durationMs?: number;\n totalTasks: number;\n completedTasks: number;\n failedTasks: number;\n /** Baselines in `expected/` with no matching `actual/` after the run. */\n deletedScreenshots: string[];\n /** `false` when discovery produced nothing (or everything was filtered out). */\n anyTasksRan: boolean;\n error?: SerializedError;\n};\n\n/** Full run view, including every task and failure. */\nexport type RunDetail = RunSummary & {\n tasks: TaskRecord[];\n failures: TaskFailure[];\n};\n\n/**\n * Levels the run event stream can carry.\n *\n * `success` is here because `ScreenshotTool` uses it — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\" — and those lines have to reach a\n * remote client, not just the host's own terminal. Adding a level is a wire\n * change: this one lands before `PROTOCOL_VERSION` 1 has ever been published,\n * so it is part of what v1 will be. A later addition needs a version bump.\n */\nexport type RunLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n\ntype RunEventBase = {\n /** Monotonic, 1-based, per run. Used for SSE `Last-Event-ID` replay. */\n seq: number;\n runId: string;\n at: number;\n};\n\n/**\n * Everything an observer needs to follow a run. Emitted synchronously, so a\n * consumer forwarding these to a logger keeps ordering with logs written\n * directly by `ScreenshotTool`.\n */\nexport type RunEvent =\n | (RunEventBase & { type: \"run:start\"; request: StartRunRequest })\n | (RunEventBase & { type: \"discover:start\"; plugins: string[] })\n | (RunEventBase & {\n type: \"discover:plugin\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"discover:complete\";\n targets: Target[];\n totalTasks: number;\n })\n | (RunEventBase & {\n type: \"filter:applied\";\n filter?: string;\n taskIds?: string[];\n plugins: { plugin: string; before: number; after: number }[];\n })\n | (RunEventBase & {\n type: \"plugin:start\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"task:start\";\n plugin: string;\n taskId: string;\n url: string;\n })\n | (RunEventBase & {\n type: \"task:complete\";\n plugin: string;\n taskId: string;\n url: string;\n status: TaskStatus;\n completed: number;\n total: number;\n durationMs: number;\n result?: PluginCaptureResult;\n })\n | (RunEventBase & {\n type: \"plugin:complete\";\n plugin: string;\n resultCount: number;\n failed: boolean;\n })\n | (RunEventBase & {\n type: \"log\";\n level: RunLogLevel;\n message: string;\n args: unknown[];\n })\n | (RunEventBase & { type: \"run:complete\"; summary: RunSummary })\n | (RunEventBase & { type: \"run:error\"; error: SerializedError })\n | (RunEventBase & { type: \"run:cancelled\" });\n\nexport type RunEventType = RunEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * A run event before the runner stamps it with `seq`, `runId` and `at`.\n *\n * `Omit` must distribute over the union here — a plain `Omit<RunEvent, …>`\n * collapses to the keys every member shares, which is just `type`.\n */\nexport type EmittableRunEvent = DistributiveOmit<\n RunEvent,\n \"seq\" | \"runId\" | \"at\"\n>;\n\nexport type RunEventListener = (event: RunEvent) => void;\n\n/** Plugin shape the runner needs. Kept structural so tests can pass fakes. */\nexport type RunnablePlugin = {\n name: string;\n description?: string;\n discover: (screenshotTool: any) => Promise<PluginTask[]>;\n execute: (\n task: PluginTask,\n page: any,\n screenshotTool: any,\n context: any,\n ) => Promise<unknown>;\n initPage?: (page: any, screenshotTool: any) => Promise<unknown>;\n /** How this plugin maps a changed file onto tasks. Absent means \"cannot\". */\n watch?: PluginWatch;\n};\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\nimport { ScreenshotFileSystem } from \"../filesystem\";\nimport { mapWithConcurrency } from \"../mapWithConcurrency\";\nimport type { PluginTask } from \"../plugin\";\nimport type ScreenshotTool from \"../screenshot\";\nimport {\n recordCaptureOrigins,\n type ScreenshotOrigin,\n toManifestKey,\n} from \"../screenshots/manifest\";\nimport {\n didScreenshotFail,\n filterTasks,\n getDeletedScreenshots,\n selectTasks,\n toTaskStatus,\n} from \"./tasks\";\nimport type {\n EmittableRunEvent,\n PluginCaptureResult,\n RunDetail,\n RunEvent,\n RunEventListener,\n RunLogLevel,\n RunnablePlugin,\n RunState,\n RunSummary,\n StartRunRequest,\n Target,\n TaskFailure,\n TaskRecord,\n} from \"./types\";\nimport { toSerializedError } from \"./types\";\n\nexport type CaptureRunnerOptions = {\n /**\n * An **already initialised** `ScreenshotTool`. The runner never calls `init()`\n * or `close()` — browser lifetime belongs to the caller, so a long-lived\n * server can keep one browser warm across many runs while the CLI can keep\n * its init/close-per-run shape.\n */\n screenshotTool: ScreenshotTool;\n plugins: RunnablePlugin[];\n /** Defaults to the screenshot tool's output directory. */\n outputDir?: string;\n /**\n * Filesystem used to clear `actual/` and `diff/`. Defaults to the screenshot\n * tool's own instance, falling back to one built from `outputDir`.\n */\n fileSystem?: ScreenshotFileSystem;\n /** Stable run id. Generated when omitted. */\n id?: string;\n /** Injectable clock, for deterministic tests. */\n now?: () => number;\n};\n\n/**\n * Orchestrates a single capture run: discover → filter → execute, emitting\n * typed events as it goes.\n *\n * Deliberately free of any presentation or process concerns — no logger calls,\n * no `chalk`, no `process.exit`. Consumers render the events however they like:\n * the CLI writes them to the terminal, the server streams them over SSE.\n *\n * One instance represents one run. Create a new one per run.\n */\nexport class CaptureRunner {\n readonly id: string;\n\n private readonly screenshotTool: ScreenshotTool;\n private readonly plugins: RunnablePlugin[];\n private readonly outputDir: string;\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly now: () => number;\n private readonly listeners = new Set<RunEventListener>();\n private readonly controller = new AbortController();\n\n private seq = 0;\n private state: RunState = \"idle\";\n private request: StartRunRequest = {};\n private startedAt = 0;\n private finishedAt: number | undefined;\n private error: unknown;\n private anyTasksRan = false;\n private deletedScreenshots: string[] = [];\n private readonly taskRecords = new Map<string, TaskRecord>();\n private readonly failures: TaskFailure[] = [];\n private started = false;\n\n /**\n * Which task currently owns each pooled page.\n *\n * Tasks run concurrently, one per page, so the page is what disambiguates\n * the capture sink's reports. Populated only while a task is executing.\n */\n private readonly taskByPage = new Map<unknown, ScreenshotOrigin>();\n /** Screenshot name → the task that captured it, for the capture manifest. */\n private readonly capturedOrigins = new Map<string, ScreenshotOrigin>();\n\n constructor(options: CaptureRunnerOptions) {\n this.screenshotTool = options.screenshotTool;\n this.plugins = options.plugins;\n this.outputDir = options.outputDir ?? options.screenshotTool.outputDir;\n this.fileSystem =\n options.fileSystem ??\n options.screenshotTool.filesystem ??\n new ScreenshotFileSystem(this.outputDir);\n this.id = options.id ?? randomUUID();\n this.now = options.now ?? (() => Date.now());\n }\n\n /** Subscribe to run events. Returns an unsubscribe function. */\n on(listener: RunEventListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n /**\n * Request cancellation. In-flight tasks finish (Playwright gives us no safe\n * mid-screenshot abort), but no further tasks are started.\n */\n abort(): void {\n if (this.state === \"completed\" || this.state === \"failed\") {\n return;\n }\n this.controller.abort();\n }\n\n getSummary(): RunSummary {\n const tasks = [...this.taskRecords.values()];\n const completedTasks = tasks.filter(\n (task) => task.status !== \"pending\" && task.status !== \"running\",\n ).length;\n\n return {\n id: this.id,\n state: this.state,\n request: this.request,\n startedAt: this.startedAt,\n finishedAt: this.finishedAt,\n durationMs:\n this.finishedAt === undefined\n ? undefined\n : this.finishedAt - this.startedAt,\n totalTasks: tasks.length,\n completedTasks,\n failedTasks: this.failures.length,\n deletedScreenshots: this.deletedScreenshots,\n anyTasksRan: this.anyTasksRan,\n error:\n this.error === undefined ? undefined : toSerializedError(this.error),\n };\n }\n\n getDetail(): RunDetail {\n return {\n ...this.getSummary(),\n tasks: [...this.taskRecords.values()],\n failures: [...this.failures],\n };\n }\n\n /**\n * Whether the run produced at least one failing screenshot or detected a\n * deleted baseline — the condition the CLI exits non-zero on.\n */\n get hasScreenshotFailure(): boolean {\n return this.failures.length > 0 || this.deletedScreenshots.length > 0;\n }\n\n private emit(event: EmittableRunEvent): void {\n this.seq += 1;\n const full = {\n ...event,\n seq: this.seq,\n runId: this.id,\n at: this.now(),\n } as RunEvent;\n\n for (const listener of this.listeners) {\n try {\n listener(full);\n } catch {\n // A misbehaving observer must never take down the run.\n }\n }\n }\n\n private log(level: RunLogLevel, message: string, ...args: unknown[]): void {\n this.emit({ type: \"log\", level, message, args });\n }\n\n /**\n * Run the capture. Resolves with the final detail; rejects if a plugin threw,\n * after emitting `run:error`.\n */\n async run(request: StartRunRequest = {}): Promise<RunDetail> {\n if (this.started) {\n throw new Error(`Run ${this.id} has already been started`);\n }\n this.started = true;\n\n this.request = request;\n this.startedAt = this.now();\n this.emit({ type: \"run:start\", request });\n\n // For the duration of the run, the tool's own output becomes part of the\n // event stream rather than going straight to whatever logger this process\n // happens to have. That is what lets a client watching a remote run see\n // \"Screenshot saved\" and the retry warnings at all.\n this.attachToolLogSink();\n this.attachToolCaptureSink();\n\n try {\n try {\n if (request.clearActual ?? true) {\n this.log(\"debug\", `Cleaning output directory: ${this.outputDir}`);\n this.fileSystem.clearActual();\n this.fileSystem.clearDiff();\n }\n\n const pluginTasks = await this.discover(request);\n\n if (!this.controller.signal.aborted) {\n await this.execute(pluginTasks);\n }\n } catch (error) {\n this.error = error;\n this.state = \"failed\";\n this.finishedAt = this.now();\n this.emit({ type: \"run:error\", error: toSerializedError(error) });\n throw error;\n }\n\n await this.collectDeleted();\n\n // Before the terminal event, not after: consumers refresh their\n // screenshot index the moment they see `run:complete`, and a manifest\n // written after that would leave the re-capture button dark until the\n // next refresh.\n await this.persistCaptureOrigins();\n\n this.finishedAt = this.now();\n this.state = this.controller.signal.aborted ? \"cancelled\" : \"completed\";\n\n if (this.state === \"cancelled\") {\n this.emit({ type: \"run:cancelled\" });\n }\n\n const summary = this.getSummary();\n this.emit({ type: \"run:complete\", summary });\n\n return this.getDetail();\n } finally {\n this.detachToolLogSink();\n this.detachToolCaptureSink();\n // Runs after the terminal event on purpose: a cancelled or failed run\n // still captured something, and the origins it did record are what make\n // those screenshots re-capturable.\n await this.persistCaptureOrigins();\n }\n }\n\n /**\n * Route `ScreenshotTool`'s log output through this run's events.\n *\n * Guarded rather than called outright: tests inject minimal stand-ins for the\n * tool, and a fake without the method should not fail a run.\n */\n private attachToolLogSink(): void {\n this.screenshotTool.setLogSink?.((level, message, ...args) => {\n this.log(level, message, ...args);\n });\n }\n\n private detachToolLogSink(): void {\n this.screenshotTool.setLogSink?.(null);\n }\n\n /**\n * Record which task produces which screenshot file.\n *\n * Guarded like the log sink: tests inject minimal tool stand-ins, and one\n * without the method must not fail a run — it only loses the manifest.\n */\n private attachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.((page, filename) => {\n const origin = this.taskByPage.get(page);\n if (origin) {\n this.capturedOrigins.set(toManifestKey(filename), origin);\n }\n });\n }\n\n private detachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.(null);\n this.taskByPage.clear();\n }\n\n /**\n * Write what this run learned about screenshot origins.\n *\n * Idempotent, because it is called once on the happy path and again from\n * `run`'s `finally` for the paths that never reach it. Existing entries are\n * preserved and only names that no longer exist on disk are dropped, so a\n * run of one task does not erase every other screenshot's origin.\n */\n private async persistCaptureOrigins(): Promise<void> {\n if (this.capturedOrigins.size === 0) {\n return;\n }\n\n const origins = Object.fromEntries(this.capturedOrigins);\n this.capturedOrigins.clear();\n\n let knownNames: string[] | undefined;\n try {\n const [actual, expected] = await Promise.all([\n this.fileSystem.getActualScreenshots(),\n this.fileSystem.getExpectedScreenshots(),\n ]);\n knownNames = [\n ...actual.map((file) =>\n toManifestKey(relative(this.fileSystem.getActualDir(), file)),\n ),\n ...expected.map((file) =>\n toManifestKey(relative(this.fileSystem.getExpectedDir(), file)),\n ),\n ];\n } catch {\n // Could not enumerate what exists, so prune nothing rather than\n // discarding entries that are probably still valid.\n knownNames = undefined;\n }\n\n const written = await recordCaptureOrigins(\n this.outputDir,\n origins,\n knownNames,\n );\n\n if (!written) {\n this.log(\n \"debug\",\n \"Could not write the capture manifest; re-capturing a single screenshot may be unavailable.\",\n );\n }\n }\n\n private async discover(\n request: StartRunRequest,\n ): Promise<{ plugin: RunnablePlugin; tasks: PluginTask[] }[]> {\n this.state = \"discovering\";\n\n const wanted = request.plugins ? new Set(request.plugins) : undefined;\n const plugins = wanted\n ? this.plugins.filter((plugin) => wanted.has(plugin.name))\n : this.plugins;\n\n this.emit({\n type: \"discover:start\",\n plugins: plugins.map((plugin) => plugin.name),\n });\n\n const pluginTasks = await Promise.all(\n plugins.map(async (plugin) => {\n this.log(\"debug\", `Discovering tasks for plugin: ${plugin.name}`);\n const tasks = await plugin.discover(this.screenshotTool);\n this.emit({\n type: \"discover:plugin\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n return { plugin, tasks };\n }),\n );\n\n const targets: Target[] = pluginTasks.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n })),\n );\n\n this.emit({\n type: \"discover:complete\",\n targets,\n totalTasks: targets.length,\n });\n\n if (request.filter === undefined && request.taskIds === undefined) {\n return pluginTasks;\n }\n\n const applied: { plugin: string; before: number; after: number }[] = [];\n\n for (const entry of pluginTasks) {\n const before = entry.tasks.length;\n let tasks = entry.tasks;\n\n if (request.filter !== undefined) {\n tasks = filterTasks(tasks, request.filter);\n }\n if (request.taskIds !== undefined) {\n tasks = selectTasks(tasks, request.taskIds);\n }\n\n entry.tasks = tasks;\n applied.push({ plugin: entry.plugin.name, before, after: tasks.length });\n }\n\n this.emit({\n type: \"filter:applied\",\n filter: request.filter,\n taskIds: request.taskIds,\n plugins: applied,\n });\n\n return pluginTasks;\n }\n\n private async execute(\n pluginTasks: { plugin: RunnablePlugin; tasks: PluginTask[] }[],\n ): Promise<void> {\n this.state = \"running\";\n\n for (const { plugin, tasks } of pluginTasks) {\n if (tasks.length === 0) {\n continue;\n }\n\n if (this.controller.signal.aborted) {\n return;\n }\n\n this.anyTasksRan = true;\n let pluginHasFailure = false;\n\n for (const task of tasks) {\n this.taskRecords.set(task.id, {\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n status: \"pending\",\n });\n }\n\n this.emit({\n type: \"plugin:start\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n\n this.log(\n \"debug\",\n `Processing ${tasks.length} tasks with concurrency ${this.screenshotTool.concurrency}`,\n );\n\n let completedTasks = 0;\n const pageContexts = new Map<number, unknown>();\n\n const results = await mapWithConcurrency(\n this.screenshotTool.concurrency,\n tasks,\n async (task, workerIndex) => {\n if (this.controller.signal.aborted) {\n return undefined;\n }\n\n const page = this.screenshotTool.getPageFromPool(workerIndex);\n\n if (!pageContexts.has(workerIndex) && plugin.initPage) {\n pageContexts.set(\n workerIndex,\n await plugin.initPage(page, this.screenshotTool),\n );\n }\n const context = pageContexts.get(workerIndex);\n\n const record = this.taskRecords.get(task.id);\n if (record) {\n record.status = \"running\";\n }\n\n this.emit({\n type: \"task:start\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n });\n\n const taskStart = this.now();\n // Claim the page for this task so the capture sink can attribute the\n // files written during `execute` — including variants, whose\n // filenames only the tool ever sees.\n this.taskByPage.set(page, { taskId: task.id, plugin: plugin.name });\n let result: unknown;\n try {\n result = await plugin.execute(\n task,\n page,\n this.screenshotTool,\n context,\n );\n } finally {\n this.taskByPage.delete(page);\n }\n const durationMs = this.now() - taskStart;\n\n completedTasks++;\n\n const failed = didScreenshotFail(result);\n const status = toTaskStatus(result);\n const typedResult = result as PluginCaptureResult | undefined;\n\n if (record) {\n record.status = status;\n record.durationMs = durationMs;\n record.result = typedResult;\n }\n\n if (failed) {\n pluginHasFailure = true;\n this.failures.push({\n taskId: task.id,\n taskUrl: task.url,\n result: typedResult ?? {},\n pluginName: plugin.name,\n });\n }\n\n this.emit({\n type: \"task:complete\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n status,\n completed: completedTasks,\n total: tasks.length,\n durationMs,\n result: typedResult,\n });\n\n return result;\n },\n );\n\n this.emit({\n type: \"plugin:complete\",\n plugin: plugin.name,\n resultCount: results.length,\n failed: pluginHasFailure,\n });\n }\n }\n\n private async collectDeleted(): Promise<void> {\n if (!this.anyTasksRan) {\n return;\n }\n\n try {\n this.deletedScreenshots = await getDeletedScreenshots(this.outputDir);\n } catch (error) {\n this.log(\"warn\", \"Could not check for deleted screenshots:\", error);\n }\n }\n}\n\nexport type { TaskRecord };\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n compareImagesGMSD,\n type CompareResult as GMSDCompareResult,\n} from \"./compare/gmsd\";\nimport {\n compareImages,\n createDiffSizePngImage,\n type CompareResult as PixelCompareResult,\n} from \"./compare/pixel\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type { RunLogLevel } from \"./runner/types\";\nimport type {\n DiffConfig,\n DiffConfigGMSD,\n DiffOptions,\n DiffOptionsGMSD,\n DiffOptionsPixel,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultPixelDiffConfig: DiffOptionsPixel = {\n type: \"pixel\",\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nconst defaultGMSDDiffConfig: DiffOptionsGMSD = {\n type: \"gmsd\",\n threshold: 0.1,\n downsample: 0,\n c: 170,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n }\n >;\n /**\n * Optional diff configuration override applied to this capture.\n * Merged on top of the global ScreenshotTool diff config.\n */\n diff?: DiffOptions;\n /**\n * Skip navigating to the base URL before capturing the base screenshot.\n * Use this when the page is already at the correct URL and in a stable state,\n * to avoid the redundant navigation.\n */\n skipBaseNavigation?: boolean;\n /**\n * Optional callback invoked after each navigation (variants only, or base when\n * skipBaseNavigation is false) to wait for visual stability before capturing.\n */\n waitForStability?: (page: Page) => Promise<void>;\n /**\n * Timestamp (from `performance.now()`) marking when the screenshot process\n * started — i.e. when the browser first navigated to the page. When provided,\n * the logged duration covers the full journey: navigation → stability waits →\n * capture. When omitted, timing begins at the capture step itself.\n */\n captureStart?: number;\n}\n\n/** The logger surface `ScreenshotTool` actually uses. */\nexport type ScreenshotLogger = Pick<\n Logger,\n \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\"\n>;\n\n/** Receives this tool's log output instead of the global logger. */\nexport type ScreenshotLogSink = (\n level: RunLogLevel,\n message: string,\n ...args: unknown[]\n) => void;\n\n/**\n * Notified whenever this tool writes a screenshot.\n *\n * `page` identifies the caller: a run captures several tasks in parallel, one\n * per pooled page, so the page is the only thing that ties a filename back to\n * the task that asked for it.\n */\nexport type ScreenshotCaptureSink = (page: Page, filename: string) => void;\n\nconst LOG_SINK_LEVELS = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n] as const satisfies readonly RunLogLevel[];\n\n/** A logger-shaped object that forwards every call to `sink`. */\nconst toSinkLogger = (sink: ScreenshotLogSink): ScreenshotLogger =>\n Object.fromEntries(\n LOG_SINK_LEVELS.map((level) => [\n level,\n (message: unknown, ...args: unknown[]) =>\n sink(level, String(message), ...args),\n ]),\n ) as ScreenshotLogger;\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n fullPage: boolean;\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffOptions;\n /**\n * Where this tool's own output goes.\n *\n * Normally the global logger. While a `CaptureRunner` owns the tool it is\n * swapped for a shim that forwards into the run's event stream instead — see\n * `setLogSink`.\n */\n logger: ScreenshotLogger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: boolean;\n connectionTimeout: number;\n private defaultUserAgent = \"\";\n /** The real logger, kept so `setLogSink(null)` restores the same instance. */\n private readonly baseLogger: ScreenshotLogger;\n /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */\n private captureSink: ScreenshotCaptureSink | null = null;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n fullPage?: boolean;\n outputDir?: string;\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: boolean;\n connectionTimeout?: number;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.fullPage = options.fullPage ?? true;\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = this.resolveDiffOptions(options.diff);\n this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n this.connectionTimeout = options.connectionTimeout ?? 20000;\n\n this.baseLogger = getLogger();\n this.logger = this.baseLogger;\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Send this tool's own log output to `sink` instead of the global logger.\n *\n * `ScreenshotTool` writes lines a user expects to see — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\", the retry warnings — straight to the\n * logger. That is fine in-process and useless over a network: with the\n * browser on another machine those lines would stay in the *host's* terminal\n * while the client showed a run with no commentary. A `CaptureRunner` installs\n * a sink for the duration of a run so they travel as `log` events instead.\n *\n * Pass `null` to restore the real logger.\n */\n setLogSink(sink: ScreenshotLogSink | null): void {\n this.logger = sink ? toSinkLogger(sink) : this.baseLogger;\n }\n\n /**\n * Report every screenshot this tool writes to `sink`.\n *\n * A `CaptureRunner` installs one for the duration of a run so it can record\n * which task produced which file. Nothing else can know: a plugin picks the\n * filename inside `execute` and is free to derive it from the task however\n * it likes, so the only reliable observation point is the write itself —\n * which also catches variants, whose filenames the plugin never states.\n *\n * Pass `null` to stop reporting.\n */\n setCaptureSink(sink: ScreenshotCaptureSink | null): void {\n this.captureSink = sink;\n }\n\n private resolveDiffOptions(diff?: DiffOptions): DiffOptions {\n if (diff?.type === \"gmsd\") {\n return { ...defaultGMSDDiffConfig, ...diff };\n }\n\n return { ...defaultPixelDiffConfig, ...diff, type: \"pixel\" };\n }\n\n private mergeDiffOptions(override?: DiffOptions): DiffOptions {\n const base = this.resolveDiffOptions(this.diff);\n\n if (!override) {\n return base;\n }\n\n if (override.type === \"gmsd\" || base.type === \"gmsd\") {\n const gmsdBase: DiffOptionsGMSD =\n base.type === \"gmsd\" ? base : defaultGMSDDiffConfig;\n\n return { ...gmsdBase, ...override, type: \"gmsd\" };\n }\n\n return {\n ...(base as DiffOptionsPixel),\n ...(override as DiffOptionsPixel),\n type: \"pixel\",\n };\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n const browser = await browserClass.launch({\n headless: this.headless,\n });\n\n if (!browser)\n throw new Error(\"Something went wrong with starting the browser.\");\n\n this.browser = browser;\n\n const tempCtx = await browser.newContext();\n const tempPage = await tempCtx.newPage();\n this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);\n await tempCtx.close();\n\n await this.createContexts();\n }\n\n /**\n * Create the pool of browser contexts and pages.\n */\n private async createContexts() {\n const browser = this.browser;\n if (!browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n // Create N contexts and pages in parallel\n const results = await Promise.all(\n Array.from({ length: this.concurrency }, async () => {\n const context = await browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${this.defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n return { context, page };\n }),\n );\n\n this.contexts = results.map((r) => r.context);\n this.pages = results.map((r) => r.page);\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes every context and page, leaving the browser process running.\n */\n async closeContexts() {\n for (const context of this.contexts) {\n await context.close();\n }\n\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n /**\n * Throw away the current contexts and build a fresh pool on the same browser.\n *\n * A long-lived process that keeps the browser warm between capture runs must\n * call this first: contexts accumulate cookies, storage and scroll position,\n * and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken with a fresh browser.\n */\n async recycleContexts() {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n await this.closeContexts();\n await this.createContexts();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n *\n * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is\n * delivered to the whole foreground process group, Chromium included, so by\n * the time a signal handler gets here every context can already be dead and\n * closing one throws `Failed to find context with id …`. Letting that escape\n * turns a clean shutdown into an uncaught exception, which is the one thing\n * teardown must never do.\n */\n async close() {\n try {\n await this.closeContexts();\n } catch (error) {\n getLogger().debug(\"Error closing browser contexts:\", error);\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n if (this.browser) {\n try {\n await this.browser.close();\n } catch (error) {\n getLogger().debug(\"Error closing the browser:\", error);\n }\n this.browser = null;\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: this.connectionTimeout,\n });\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n await this.filesystem.ensureParentDir(filepath);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\n const screenshotOptions = {\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: string | Buffer,\n options: ScreenshotSettings & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n diffOverride?: DiffOptions,\n ): Promise<{\n screenshotPath: string;\n comparisonResult: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage ?? this.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n diffOverride,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n await this.filesystem.writeActualFile(\n filename,\n retryScreenshot.screenshotPath,\n );\n this.logger.debug(`Actual screenshot saved: ${filepath}`);\n\n if (retryScreenshot.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n retryScreenshot.comparisonResult?.diffBuffer &&\n !retryScreenshot.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n\n await this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n\n // When interpretation is enabled, persist diff stats + interpretation as\n // a sidecar so the review UI and CLI can surface them after rebuilding\n // state from disk. Skipped entirely otherwise so no extra files appear\n // for users who have not opted in (pixel only).\n const result = retryScreenshot.comparisonResult;\n if (\"numDiffPixels\" in result && result.interpretation) {\n await this.filesystem.writeDiffMetaFile(diffFilename, {\n numDiffPixels: result.numDiffPixels,\n percentDifference: result.percentDifference,\n interpretation: result.interpretation,\n });\n }\n }\n\n // different sizes diff image\n if (\n retryScreenshot.comparisonResult !== null &&\n typeof retryScreenshot.comparisonResult === \"object\" &&\n \"differentSizes\" in retryScreenshot.comparisonResult &&\n retryScreenshot.comparisonResult.differentSizes\n ) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = await createDiffSizePngImage(200, 200);\n\n await this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult: retryScreenshot.comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async retryScreenshot(\n page: Page,\n referenceImage: string | Buffer,\n options: ScreenshotSettings,\n diffOverride?: DiffOptions,\n ) {\n const diffConfig = this.mergeDiffOptions(diffOverride);\n\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\n ...options,\n delay: this.getIncBackoffDelay(i, options.delay || 0),\n });\n\n if (!screenshotBuffer) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n const comparisonResult =\n diffConfig.type === \"gmsd\"\n ? await compareImagesGMSD(\n screenshotBuffer,\n referenceImage,\n true,\n diffConfig as DiffConfigGMSD,\n )\n : await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n diffConfig as DiffConfig,\n );\n\n // last retry\n if (i === this.retries - 1 && !comparisonResult.passed) {\n this.logger.error(\n `Failed to match screenshot after ${this.retries} retries`,\n );\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\n }\n\n if (comparisonResult.passed) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: true,\n };\n } else {\n const summary =\n \"numDiffPixels\" in comparisonResult\n ? comparisonResult.differentSizes\n ? \"different image sizes\"\n : `${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`\n : `gmsd score ${comparisonResult.gmsd.toFixed(4)}`;\n\n this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${summary}`,\n );\n }\n } catch (error) {\n this.logger.error(\n `Error taking screenshot after ${i + 1} retries:`,\n (error as Error).message,\n );\n }\n }\n\n return {\n screenshotPath: null,\n comparisonResult: null,\n passed: false,\n };\n }\n\n getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n captureStart?: number;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const start = extras.captureStart ?? performance.now();\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n const diffOverride = extras.diff;\n\n if (!(await this.filesystem.hasExpectedFile(filename))) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.getExpectedFilePath(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n diffOverride,\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n const duration = Math.round(performance.now() - start);\n this.logger.debug(`${filename} captured in ${duration}ms`);\n\n // Reported after the capture, so a task that threw on the way here does not\n // claim a file it never wrote. A failing sink is the observer's problem and\n // must not fail the capture.\n try {\n this.captureSink?.(page, filename);\n } catch {\n // ignored\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n const baseDiffOverride = extras.diff;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n const baseDiffOverride = extras.diff;\n\n // Capture base screenshot\n let baseStart: number;\n if (!extras.skipBaseNavigation) {\n baseStart = performance.now();\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n } else {\n baseStart = performance.now();\n }\n\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart ?? baseStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n const variantStart = performance.now();\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n captureStart: variantStart,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Gets the exponential backoff delay\n */\n getIncBackoffDelay(i: number, delay: number): number {\n return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;\n }\n\n /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { readDiffMeta } from \"../filesystem\";\nimport type { Screenshot } from \"../types\";\n\nexport const groupScreenshots = async (\n actualScreenshots: string[],\n expectedScreenshots: string[],\n diffScreenshots: string[],\n outputDir: string,\n): Promise<Screenshot[]> => {\n const screenshotRepresentations: Screenshot[] = [];\n\n // Build Maps for O(1) lookups instead of O(n) .find() calls\n const expectedByRelativePath = new Map<string, string>();\n for (const screenshot of expectedScreenshots) {\n const relativePath = path.relative(`${outputDir}/expected`, screenshot);\n expectedByRelativePath.set(relativePath, screenshot);\n }\n\n const diffByRelativePath = new Map<string, string>();\n for (const screenshot of diffScreenshots) {\n const relativePath = path.relative(`${outputDir}/diff`, screenshot);\n diffByRelativePath.set(relativePath, screenshot);\n }\n\n const actualRelativePaths = new Set<string>();\n\n for (const screenshot of actualScreenshots) {\n const relativePath = path.relative(`${outputDir}/actual`, screenshot);\n actualRelativePaths.add(relativePath);\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n const expectedScreenshot = expectedByRelativePath.get(relativePath);\n const diffScreenshot = diffByRelativePath.get(relativePath);\n\n // Load the diff metadata sidecar (stats + interpretation) for changed\n // screenshots so it can be surfaced in the review UI and CLI.\n const diffMeta = diffScreenshot\n ? await readDiffMeta(diffScreenshot)\n : undefined;\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: buildCategory(expectedScreenshot, diffScreenshot),\n expectedPath: expectedScreenshot\n ? path.relative(outputDir, expectedScreenshot)\n : undefined,\n diffPath: diffScreenshot\n ? path.relative(outputDir, diffScreenshot)\n : undefined,\n actualPath: path.relative(outputDir, screenshot),\n ...(diffMeta ? { diffMeta } : {}),\n } as Screenshot);\n }\n\n for (const expectedScreenshot of expectedScreenshots) {\n const relativePath = path.relative(\n `${outputDir}/expected`,\n expectedScreenshot,\n );\n\n // If the actual screenshot exists, it means we already added it\n if (actualRelativePaths.has(relativePath)) {\n continue;\n }\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: \"deleted\",\n expectedPath: path.relative(outputDir, expectedScreenshot),\n });\n }\n\n return screenshotRepresentations.sort((a, b) => {\n return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];\n });\n};\n\nconst buildCategory = (\n expectedScreenshot: string | undefined,\n diffScreenshot: string | undefined,\n) => {\n if (expectedScreenshot && diffScreenshot) {\n return \"changed\";\n }\n if (expectedScreenshot) {\n return \"passed\";\n }\n\n return \"new\";\n};\n\nconst CATEGORY_ORDER: Record<Screenshot[\"category\"], number> = {\n new: 0,\n deleted: 1,\n changed: 2,\n passed: 3,\n};\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Screenshot } from \"../types\";\nimport { groupScreenshots } from \"./groupScreenshots\";\nimport { readCaptureManifest } from \"./manifest\";\n\nconst listPngs = async (dir: string): Promise<string[]> =>\n Array.fromAsync(await glob(path.resolve(dir, \"**/*.png\")));\n\n/**\n * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and\n * group them into the screenshot representations used by the CLI commands\n * (including the diff metadata sidecar with the optional interpretation).\n *\n * The capture manifest is folded in here so every consumer — the CLI, the\n * server, the review UI — sees the same `taskId`, and so a screenshot captured\n * before manifests existed simply has none rather than a wrong one.\n */\nexport const collectScreenshots = async (\n outputDir: string,\n): Promise<Screenshot[]> => {\n const [actualScreenshots, expectedScreenshots, diffScreenshots, manifest] =\n await Promise.all([\n listPngs(path.resolve(outputDir, \"actual\")),\n listPngs(path.resolve(outputDir, \"expected\")),\n listPngs(path.resolve(outputDir, \"diff\")),\n readCaptureManifest(outputDir),\n ]);\n\n const screenshots = await groupScreenshots(\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n outputDir,\n );\n\n return screenshots.map((screenshot) => {\n const origin = manifest.screenshots[screenshot.name];\n return origin\n ? { ...screenshot, taskId: origin.taskId, plugin: origin.plugin }\n : screenshot;\n });\n};\n","import type { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type { RunDetail, RunEvent, RunSummary } from \"../runner/types\";\n\nexport type RunStoreOptions = {\n /**\n * Events buffered per run, for replay to a (re)connecting subscriber.\n * @default 5000\n */\n maxEventsPerRun?: number;\n /**\n * Finished runs kept in memory. Oldest are dropped first.\n * @default 20\n */\n maxRuns?: number;\n};\n\ntype RunEntry = {\n id: string;\n runner: CaptureRunner;\n events: RunEvent[];\n /** Events dropped off the front of the buffer, so replay gaps are detectable. */\n dropped: number;\n listeners: Set<(event: RunEvent) => void>;\n /** Frozen once the run finishes, so detail survives after the runner is gone. */\n finalDetail?: RunDetail;\n};\n\n/**\n * In-memory registry of capture runs and their event history.\n *\n * The event buffer is what lets an SSE client reconnect without losing\n * anything: subscribers replay from the last `seq` they saw before live\n * delivery starts.\n */\nexport class RunStore {\n private readonly maxEventsPerRun: number;\n private readonly maxRuns: number;\n private readonly runs = new Map<string, RunEntry>();\n /** Insertion order, oldest first — the eviction queue. */\n private readonly order: string[] = [];\n\n constructor(options: RunStoreOptions = {}) {\n this.maxEventsPerRun = options.maxEventsPerRun ?? 5000;\n this.maxRuns = options.maxRuns ?? 20;\n }\n\n /** Register a runner and start buffering its events. */\n add(runner: CaptureRunner): void {\n const entry: RunEntry = {\n id: runner.id,\n runner,\n events: [],\n dropped: 0,\n listeners: new Set(),\n };\n\n this.runs.set(runner.id, entry);\n this.order.push(runner.id);\n this.evictOldRuns();\n\n runner.on((event) => {\n entry.events.push(event);\n if (entry.events.length > this.maxEventsPerRun) {\n entry.dropped += entry.events.length - this.maxEventsPerRun;\n entry.events.splice(0, entry.events.length - this.maxEventsPerRun);\n }\n\n for (const listener of entry.listeners) {\n try {\n listener(event);\n } catch {\n // A failing subscriber must not disturb the run or other subscribers.\n }\n }\n });\n }\n\n /**\n * Freeze the final detail of a finished run so it stays queryable after the\n * runner is discarded.\n */\n finalize(runId: string): void {\n const entry = this.runs.get(runId);\n if (entry) {\n entry.finalDetail = entry.runner.getDetail();\n }\n }\n\n get(runId: string): RunDetail | undefined {\n const entry = this.runs.get(runId);\n if (!entry) {\n return undefined;\n }\n\n return entry.finalDetail ?? entry.runner.getDetail();\n }\n\n getRunner(runId: string): CaptureRunner | undefined {\n return this.runs.get(runId)?.runner;\n }\n\n /** Newest first. */\n list(): RunSummary[] {\n return [...this.order]\n .reverse()\n .map((id) => {\n const entry = this.runs.get(id);\n if (!entry) {\n return undefined;\n }\n return entry.finalDetail ?? entry.runner.getSummary();\n })\n .filter((summary): summary is RunSummary => summary !== undefined);\n }\n\n /**\n * Subscribe to a run, replaying buffered events first.\n *\n * Replay is synchronous, so a subscriber cannot miss events that arrive\n * between the buffer read and the listener being registered.\n */\n subscribe(\n runId: string,\n onEvent: (event: RunEvent) => void,\n options: { sinceSeq?: number } = {},\n ): () => void {\n const entry = this.runs.get(runId);\n if (!entry) {\n return () => {};\n }\n\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of entry.events) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n entry.listeners.add(onEvent);\n return () => {\n entry.listeners.delete(onEvent);\n };\n }\n\n /** How many events were dropped from a run's buffer (0 when none were). */\n droppedEvents(runId: string): number {\n return this.runs.get(runId)?.dropped ?? 0;\n }\n\n private evictOldRuns(): void {\n while (this.order.length > this.maxRuns) {\n const oldest = this.order.shift();\n if (oldest !== undefined) {\n this.runs.delete(oldest);\n }\n }\n }\n}\n","import type {\n RunDetail,\n RunEvent,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport type { Screenshot } from \"../types\";\n\nexport type PluginInfo = {\n name: string;\n description?: string;\n};\n\nexport type ScreenshotQuery = {\n search?: string;\n category?: Screenshot[\"category\"];\n};\n\nexport type ApproveResult = {\n approved: string[];\n errors: { name: string; error: string }[];\n};\n\nexport type ListTargetsOptions = {\n /** Re-run plugin discovery instead of serving the cached target list. */\n refresh?: boolean;\n};\n\nexport type SubscribeOptions = {\n /**\n * Replay buffered events with `seq > sinceSeq` before streaming live ones.\n * This is what makes a dropped SSE connection invisible to the client.\n */\n sinceSeq?: number;\n};\n\n/**\n * How a watch iteration decided what to capture.\n *\n * - `tasks` — an explicit set of task ids, resolved by the plugins.\n * - `plugins` — every task of one or more plugins, because at least one could\n * not attribute the change (or ships no `watch` at all).\n * - `all` — everything under the session's filter: the resolved set was larger\n * than the cap, or discovery itself failed.\n * - `none` — nothing to capture.\n */\nexport type WatchScope = \"tasks\" | \"plugins\" | \"all\" | \"none\";\n\n/** What one settled batch of file changes led to. */\nexport type WatchChange = {\n /** Changed files, relative to the watch root. */\n files: string[];\n scope: WatchScope;\n /** Resolved task ids, when the scope is `tasks`. */\n taskIds?: string[];\n /** The run the change started, absent when none could be started. */\n runId?: string;\n /** Why no run was started, when that is what happened. */\n error?: string;\n at: number;\n};\n\ntype WatchEventBase = {\n /** Monotonic, 1-based, per engine. Used for replay, like run events. */\n seq: number;\n at: number;\n};\n\n/**\n * The watch event stream.\n *\n * Separate from `RunEvent` because these events belong to a session that\n * outlives any single run — a watch session is a scheduler for runs, and the\n * runs it starts report themselves through the ordinary run stream.\n */\nexport type WatchEvent =\n | (WatchEventBase & {\n type: \"watch:start\";\n paths: string[];\n filter?: string;\n debounceMs: number;\n })\n | (WatchEventBase & { type: \"watch:change\" } & Omit<WatchChange, \"at\">)\n | (WatchEventBase & {\n type: \"watch:stop\";\n reason: \"requested\" | \"engine-closed\";\n });\n\nexport type WatchEventType = WatchEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/** A watch event before the engine stamps it with `seq` and `at`. */\nexport type EmittableWatchEvent = DistributiveOmit<WatchEvent, \"seq\" | \"at\">;\n\n/** What a watch session is doing, readable at any time. */\nexport type WatchStatus = {\n active: boolean;\n /** Roots being watched, relative to the working directory. */\n paths: string[];\n filter?: string;\n debounceMs: number;\n startedAt?: number;\n /** The most recent settled batch of changes, when there has been one. */\n lastChange?: WatchChange;\n};\n\n/** Options for `startWatch`. */\nexport type StartWatchRequest = {\n /**\n * Directories to watch, relative to the working directory.\n * @default [\".\"]\n */\n paths?: string[];\n /** Glob every watch-triggered run is restricted to (`path.matchesGlob`). */\n filter?: string;\n /**\n * How long changes must settle before a run starts.\n * @default 300\n */\n debounceMs?: number;\n /**\n * Above this many resolved task ids, capture everything under `filter`\n * instead. A branch switch is what this guards against.\n * @default 200\n */\n maxTasks?: number;\n};\n\n/**\n * Everything a UI needs to drive and observe captures.\n *\n * There are two implementations: `LocalEngine` runs the browser in-process, and\n * (later) a remote engine speaks HTTP + SSE to a server that does. The UI only\n * ever holds this interface, so moving the browser to another machine is a\n * different implementation rather than a rewrite.\n *\n * That is only true if the interface stays serializable: **no `Page`, `Browser`,\n * or plugin object may cross it** — arguments and return values must survive a\n * JSON round-trip. Plugins are live closures from `cappa.config.ts` and cannot\n * be sent anywhere; whichever process holds the engine is the one that loaded\n * the config.\n */\nexport interface CaptureEngine {\n /** Plugins this engine can run. */\n listPlugins(): Promise<PluginInfo[]>;\n\n /** Discovered, runnable tasks. Cached until `refresh` is requested. */\n listTargets(options?: ListTargetsOptions): Promise<Target[]>;\n\n /**\n * Start a capture. Resolves as soon as the run is registered — progress\n * arrives through `subscribeRun`.\n *\n * @throws {RunInProgressError} when a run is already active.\n */\n startRun(request?: StartRunRequest): Promise<RunSummary>;\n\n getRun(id: string): Promise<RunDetail | undefined>;\n\n /** Newest first. */\n listRuns(): Promise<RunSummary[]>;\n\n cancelRun(id: string): Promise<void>;\n\n /**\n * Observe a run. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery begins, so\n * a subscriber that attaches after `startRun` still sees the whole run.\n */\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n listScreenshots(query?: ScreenshotQuery): Promise<Screenshot[]>;\n\n approve(names: string[]): Promise<ApproveResult>;\n\n /**\n * Re-capture on file change until `stopWatch`.\n *\n * Optional, because only an engine that can see the files is able to do it:\n * a remote engine drives the watcher on the *host*, and an engine with no\n * local filesystem at all has nothing to offer. Callers must feature-detect\n * rather than assume.\n *\n * @throws {WatchInProgressError} when a session is already active.\n */\n startWatch?(request?: StartWatchRequest): Promise<WatchStatus>;\n\n /**\n * Stop the active watch session and answer the status it left behind.\n *\n * A no-op when there is none — the status simply says it is inactive.\n */\n stopWatch?(): Promise<WatchStatus>;\n\n /** What the watch session is doing, or an inactive status when there is none. */\n getWatchStatus?(): Promise<WatchStatus>;\n\n /**\n * Observe the watch event stream. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery, exactly\n * as `subscribeRun` does.\n */\n subscribeWatch?(\n onEvent: (event: WatchEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n /** Release resources (browser, timers). Safe to call more than once. */\n close(): Promise<void>;\n}\n\n/**\n * Stable discriminators for engine errors.\n *\n * These exist because `instanceof` is not reliable across the package\n * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the\n * CLI binary) and an ESM one (the server) each load their own copy of these\n * classes: an error thrown by one is not an `instanceof` the other's class,\n * and the check silently fails — turning a 409 into a 500. Callers must use\n * the guards below rather than `instanceof`.\n */\nexport const ENGINE_ERROR_CODES = {\n runInProgress: \"CAPPA_RUN_IN_PROGRESS\",\n unknownTargets: \"CAPPA_UNKNOWN_TARGETS\",\n watchInProgress: \"CAPPA_WATCH_IN_PROGRESS\",\n} as const;\n\n/** Thrown by `startRun` when the engine is already running something. */\nexport class RunInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.runInProgress;\n readonly activeRunId: string;\n\n constructor(activeRunId: string) {\n super(`A capture run is already in progress (${activeRunId})`);\n this.name = \"RunInProgressError\";\n this.activeRunId = activeRunId;\n }\n}\n\n/** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */\nexport class UnknownTargetsError extends Error {\n readonly code = ENGINE_ERROR_CODES.unknownTargets;\n readonly taskIds: string[];\n\n constructor(taskIds: string[]) {\n super(`Unknown task ids: ${taskIds.join(\", \")}`);\n this.name = \"UnknownTargetsError\";\n this.taskIds = taskIds;\n }\n}\n\n/** Thrown by `startWatch` when a watch session is already running. */\nexport class WatchInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.watchInProgress;\n\n constructor() {\n super(\"A watch session is already running\");\n this.name = \"WatchInProgressError\";\n }\n}\n\nconst hasCode = (error: unknown, code: string): boolean =>\n error instanceof Error && (error as { code?: unknown }).code === code;\n\n/**\n * Identity-independent check for `RunInProgressError`.\n *\n * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.\n */\nexport const isRunInProgressError = (\n error: unknown,\n): error is RunInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.runInProgress);\n\n/** Identity-independent check for `UnknownTargetsError`. */\nexport const isUnknownTargetsError = (\n error: unknown,\n): error is UnknownTargetsError =>\n hasCode(error, ENGINE_ERROR_CODES.unknownTargets);\n\n/** Identity-independent check for `WatchInProgressError`. */\nexport const isWatchInProgressError = (\n error: unknown,\n): error is WatchInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.watchInProgress);\n","import type ScreenshotTool from \"../screenshot\";\n\nexport type WarmBrowserOptions = {\n /** Builds an un-initialised `ScreenshotTool`. Called once per cold start. */\n create: () => ScreenshotTool;\n /**\n * How long the browser may sit unused before it is shut down.\n * `0` disables warm reuse entirely (close immediately after each release).\n * @default 300_000 (5 minutes)\n */\n idleTimeoutMs?: number;\n};\n\n/**\n * Keeps a Playwright browser alive between capture runs.\n *\n * Interactively, a cold Chromium start on every \"Capture\" click is the\n * difference between a snappy tool and a sluggish one — but a browser left\n * running forever is a memory leak, so it is evicted after an idle period.\n *\n * Contexts are recycled on every acquire after the first, because a warm\n * browser's pages carry cookies, storage and scroll position from the previous\n * run and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken.\n */\nexport class WarmBrowser {\n private readonly createTool: () => ScreenshotTool;\n private readonly idleTimeoutMs: number;\n\n private tool: ScreenshotTool | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private inUse = false;\n private closed = false;\n /** Outstanding `hold()` leases. While any is held, eviction is suspended. */\n private holds = 0;\n /** Serializes acquire/close so concurrent callers cannot race the browser. */\n private pending: Promise<unknown> = Promise.resolve();\n\n constructor(options: WarmBrowserOptions) {\n this.createTool = options.create;\n this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;\n }\n\n /** True while a browser process is alive. */\n get isWarm(): boolean {\n return this.tool !== null;\n }\n\n /**\n * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.\n * Always pair with `release()`.\n */\n async acquire(): Promise<ScreenshotTool> {\n return this.serialize(async () => {\n if (this.closed) {\n throw new Error(\"WarmBrowser has been closed\");\n }\n\n this.cancelIdleTimer();\n this.inUse = true;\n\n if (this.tool) {\n // Reused browser: give the run a clean set of contexts.\n await this.tool.recycleContexts();\n return this.tool;\n }\n\n const tool = this.createTool();\n await tool.init();\n this.tool = tool;\n return tool;\n });\n }\n\n /**\n * Hand the browser back. It stays warm until the idle timeout elapses.\n */\n release(): void {\n this.inUse = false;\n\n if (this.closed || !this.tool) {\n return;\n }\n\n // A lease outranks the idle policy in both directions, including\n // `idleTimeoutMs: 0` — the CLI's one-shot setting, which watch mode\n // otherwise turns into a cold Chromium start on every save.\n if (this.holds > 0) {\n this.cancelIdleTimer();\n return;\n }\n\n if (this.idleTimeoutMs <= 0) {\n void this.close();\n return;\n }\n\n this.startIdleTimer();\n }\n\n /**\n * Suspend idle eviction until the returned function is called.\n *\n * Held by an active watch session. Without it, `WarmBrowser` closes the\n * browser between saves during a coffee break and the next save pays full\n * start-up — which is the entire premise of watch mode, defeated by its own\n * idle handling.\n */\n hold(): () => void {\n this.holds += 1;\n this.cancelIdleTimer();\n\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n this.holds -= 1;\n\n // Back to the normal idle policy for a browser nobody is using.\n if (this.holds === 0 && !this.inUse) {\n this.release();\n }\n };\n }\n\n /** True while at least one lease suspends idle eviction. */\n get isHeld(): boolean {\n return this.holds > 0;\n }\n\n /** Shut the browser down now. Safe to call repeatedly. */\n async close(): Promise<void> {\n this.closed = true;\n this.cancelIdleTimer();\n\n await this.serialize(async () => {\n const tool = this.tool;\n this.tool = null;\n this.inUse = false;\n\n if (tool) {\n await tool.close();\n }\n });\n }\n\n private startIdleTimer(): void {\n this.cancelIdleTimer();\n\n const timer = setTimeout(() => {\n this.idleTimer = null;\n if (this.inUse || this.closed || this.holds > 0 || !this.tool) {\n return;\n }\n\n void this.evict();\n }, this.idleTimeoutMs);\n\n // Never let an idle browser keep the process alive.\n if (typeof (timer as { unref?: () => void }).unref === \"function\") {\n (timer as { unref: () => void }).unref();\n }\n\n this.idleTimer = timer;\n }\n\n private cancelIdleTimer(): void {\n if (this.idleTimer !== null) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n }\n\n /** Shut the browser down but stay usable — the next acquire starts cold. */\n private async evict(): Promise<void> {\n await this.serialize(async () => {\n if (this.inUse || this.closed || this.holds > 0) {\n return;\n }\n\n const tool = this.tool;\n this.tool = null;\n\n if (tool) {\n await tool.close();\n }\n });\n }\n\n private serialize<T>(work: () => Promise<T>): Promise<T> {\n const next = this.pending.then(work, work);\n // Keep the chain alive even when a caller's promise rejects.\n this.pending = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n}\n","import path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type {\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n} from \"../runner/types\";\nimport type {\n EmittableWatchEvent,\n WatchChange,\n WatchScope,\n WatchStatus,\n} from \"./types\";\n\n/**\n * The slice of a file watcher this session uses.\n *\n * Structural rather than chokidar's own type, so a test can drive a session\n * with a stand-in instead of real filesystem events — which are slow, ordered\n * by the OS rather than by the test, and different on every platform.\n */\nexport interface FileWatcher {\n on(\n event: \"all\",\n listener: (event: string, changedPath: string) => void,\n ): unknown;\n on(event: \"ready\", listener: () => void): unknown;\n on(event: \"error\", listener: (error: unknown) => void): unknown;\n close(): Promise<void>;\n}\n\nexport type CreateFileWatcher = (\n roots: string[],\n options: { cwd: string; ignored: (candidate: string) => boolean },\n) => FileWatcher | Promise<FileWatcher>;\n\n/**\n * Directories no watch should ever descend into.\n *\n * `outputDir` is not here because it is not a fixed name — the engine passes it\n * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs\n * into it, every write is a change, and the session would trigger itself\n * forever.\n */\nexport const DEFAULT_IGNORED_DIRS = new Set([\n \".git\",\n \".cache\",\n \".next\",\n \".nuxt\",\n \".output\",\n \".parcel-cache\",\n \".svelte-kit\",\n \".turbo\",\n \".vercel\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n \"storybook-static\",\n]);\n\n/** Watch-mode defaults, exported so the CLI and docs can quote one source. */\nexport const DEFAULT_DEBOUNCE_MS = 300;\nexport const DEFAULT_MAX_TASKS = 200;\n/** How long `start()` waits for the initial filesystem scan before giving up on it. */\nconst READY_TIMEOUT_MS = 10_000;\n\nexport type WatchSessionOptions = {\n plugins: RunnablePlugin[];\n /** Discovered tasks per plugin name. Called once per settled batch. */\n discover: () => Promise<Map<string, PluginTask[]>>;\n /** Start a run. Resolves as soon as the run is registered. */\n startRun: (request: StartRunRequest) => Promise<RunSummary>;\n /** Resolve when the given run reaches a terminal event. */\n waitForRun: (runId: string) => Promise<void>;\n emit?: (event: EmittableWatchEvent) => void;\n cwd?: string;\n /** Roots to watch, relative to `cwd`. @default [\".\"] */\n paths?: string[];\n /** Absolute or `cwd`-relative paths never to watch (the output directory). */\n ignoredPaths?: string[];\n filter?: string;\n debounceMs?: number;\n maxTasks?: number;\n createWatcher?: CreateFileWatcher;\n now?: () => number;\n};\n\n/** What a settled batch of changes resolved to. */\ntype WatchResolution = {\n scope: WatchScope;\n taskIds?: string[];\n request: StartRunRequest;\n};\n\n/**\n * chokidar, loaded on first use.\n *\n * Imported lazily so that requiring `@cappa/core` — which the CLI does for\n * every command, and a plugin does just to get types — never starts a file\n * watcher's dependency tree for a process that will not watch anything.\n */\nconst defaultCreateWatcher: CreateFileWatcher = async (roots, options) => {\n const { watch } = await import(\"chokidar\");\n\n return watch(roots, {\n cwd: options.cwd,\n ignoreInitial: true,\n ignored: (candidate: string) => options.ignored(candidate),\n }) as unknown as FileWatcher;\n};\n\n/**\n * Re-captures affected tasks when files change.\n *\n * A scheduler for runs, deliberately not a second orchestrator: every iteration\n * goes through the engine's ordinary `startRun`, so watch-triggered captures\n * emit the same events, land in the same run store and honour the same\n * one-run-at-a-time rule as a capture somebody clicked.\n *\n * Two behaviours matter more than they look:\n *\n * - **`clearActual` is always false.** Clearing on every save would delete the\n * diffs the user is looking at for tasks they did not touch.\n * - **Changes during a run are queued, never rejected.** The engine's single-run\n * rule stays intact, and the user gets the run they expect rather than a\n * conflict error they did not cause.\n */\nexport class WatchSession {\n private readonly options: WatchSessionOptions;\n private readonly cwd: string;\n private readonly roots: string[];\n private readonly ignoredRoots: string[];\n private readonly debounceMs: number;\n private readonly maxTasks: number;\n private readonly now: () => number;\n\n private watcher: FileWatcher | null = null;\n private readonly pending = new Set<string>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private draining = false;\n private stopped = false;\n private startedAt: number | undefined;\n private lastChange: WatchChange | undefined;\n\n constructor(options: WatchSessionOptions) {\n this.options = options;\n this.cwd = options.cwd ?? process.cwd();\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.maxTasks = options.maxTasks ?? DEFAULT_MAX_TASKS;\n this.now = options.now ?? (() => Date.now());\n\n this.roots = resolveRoots(options.paths, options.plugins);\n this.ignoredRoots = (options.ignoredPaths ?? []).map((entry) =>\n path.resolve(this.cwd, entry),\n );\n }\n\n /** Begin watching. Resolves once the initial scan has settled. */\n async start(): Promise<WatchStatus> {\n if (this.watcher) {\n return this.getStatus();\n }\n\n const create = this.options.createWatcher ?? defaultCreateWatcher;\n const watcher = await create(this.roots, {\n cwd: this.cwd,\n ignored: (candidate) => this.isIgnored(candidate),\n });\n\n // `stop()` can land while the watcher is still being built; closing it here\n // is what stops that race leaving a watcher nobody holds a handle to.\n if (this.stopped) {\n await watcher.close();\n return this.getStatus();\n }\n\n this.watcher = watcher;\n\n watcher.on(\"all\", (event, changedPath) => {\n // Directory events say nothing about what a screenshot would look like;\n // the file events inside them do.\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n this.onFileChanged(changedPath);\n });\n\n // Swallowed on purpose: a watcher that reports an unreadable directory has\n // not stopped watching everything else, and taking the session down over it\n // would be worse than the noise.\n watcher.on(\"error\", () => {});\n\n await this.waitForReady(watcher);\n\n this.startedAt = this.now();\n this.emit({\n type: \"watch:start\",\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n });\n\n return this.getStatus();\n }\n\n /**\n * Stop watching.\n *\n * Deliberately does not cancel a run already in flight: that run is the\n * answer to a save the user made, and killing it half-way leaves `actual/`\n * holding a partial capture.\n */\n async stop(\n reason: \"requested\" | \"engine-closed\" = \"requested\",\n ): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.pending.clear();\n\n const watcher = this.watcher;\n this.watcher = null;\n\n try {\n await watcher?.close();\n } finally {\n this.emit({ type: \"watch:stop\", reason });\n }\n }\n\n getStatus(): WatchStatus {\n return {\n active: this.watcher !== null && !this.stopped,\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n startedAt: this.startedAt,\n lastChange: this.lastChange,\n };\n }\n\n private emit(event: EmittableWatchEvent): void {\n this.options.emit?.(event);\n }\n\n private async waitForReady(watcher: FileWatcher): Promise<void> {\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve();\n };\n\n // Bounded: a large tree can take a while to scan, but a `ready` that\n // never arrives must not leave `startWatch` hanging forever. Events flow\n // during the scan either way, so proceeding early costs nothing.\n const timer = setTimeout(finish, READY_TIMEOUT_MS);\n timer.unref?.();\n\n watcher.on(\"ready\", finish);\n watcher.on(\"error\", finish);\n });\n }\n\n private onFileChanged(changedPath: string): void {\n if (this.stopped) {\n return;\n }\n\n this.pending.add(toRelative(this.cwd, changedPath));\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n void this.drain();\n }, this.debounceMs);\n timer.unref?.();\n this.timer = timer;\n }\n\n /**\n * Capture for everything pending, one batch at a time.\n *\n * The loop re-reads `pending` after each iteration, which is what turns a\n * save arriving mid-run into the next iteration rather than into a `409`.\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n while (this.pending.size > 0 && !this.stopped) {\n const files = [...this.pending].sort();\n this.pending.clear();\n await this.captureFor(files);\n }\n } finally {\n this.draining = false;\n }\n }\n\n private async captureFor(files: string[]): Promise<void> {\n const resolution = await this.resolveFiles(files);\n\n if (resolution.scope === \"none\") {\n this.record({ files, scope: \"none\", taskIds: [], at: this.now() });\n return;\n }\n\n let runId: string | undefined;\n let error: string | undefined;\n\n try {\n const summary = await this.options.startRun(resolution.request);\n runId = summary.id;\n } catch (cause) {\n // Most likely a run somebody else started — the CLI in another terminal,\n // or the review UI. Say so and wait for the next save rather than\n // retrying into the same conflict.\n error = cause instanceof Error ? cause.message : String(cause);\n }\n\n this.record({\n files,\n scope: resolution.scope,\n taskIds: resolution.taskIds,\n runId,\n error,\n at: this.now(),\n });\n\n if (runId) {\n await this.options.waitForRun(runId);\n }\n }\n\n private record(change: WatchChange): void {\n this.lastChange = change;\n const { at: _at, ...rest } = change;\n this.emit({ type: \"watch:change\", ...rest });\n }\n\n /**\n * Ask every plugin what the changed files affect, and turn the answers into\n * one run request.\n */\n private async resolveFiles(files: string[]): Promise<WatchResolution> {\n const trigger = { source: \"watch\" as const, files };\n const everything: WatchResolution = {\n scope: \"all\",\n request: {\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n\n let tasksByPlugin: Map<string, PluginTask[]>;\n try {\n tasksByPlugin = await this.options.discover();\n } catch {\n // Discovery failing — a dev server mid-restart, most likely — is not a\n // reason to capture nothing. Run everything and let the run report it.\n return everything;\n }\n\n const fullPlugins = new Set<string>();\n const taskIds = new Set<string>();\n\n for (const plugin of this.options.plugins) {\n const tasks = tasksByPlugin.get(plugin.name) ?? [];\n\n if (!plugin.watch) {\n fullPlugins.add(plugin.name);\n continue;\n }\n\n for (const file of files) {\n let resolved: string[] | null;\n try {\n resolved = plugin.watch.resolve(file, tasks);\n } catch {\n // A plugin that throws is a plugin that cannot tell.\n resolved = null;\n }\n\n if (resolved === null) {\n fullPlugins.add(plugin.name);\n break;\n }\n\n for (const id of resolved) {\n taskIds.add(id);\n }\n }\n }\n\n if (fullPlugins.size === 0) {\n if (taskIds.size === 0) {\n return { scope: \"none\", request: {} };\n }\n return this.byTaskIds([...taskIds], trigger, everything);\n }\n\n if (taskIds.size === 0) {\n return {\n scope: \"plugins\",\n request: {\n plugins: [...fullPlugins],\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n // Mixed: some plugins named tasks, others need everything they own. A\n // request cannot express that directly — `plugins` and `taskIds` compose as\n // \"and\" — so the full plugins are expanded to the ids discovery just\n // produced. The one thing this misses is a task created since that\n // discovery, which the next iteration picks up.\n const expanded = new Set(taskIds);\n for (const name of fullPlugins) {\n for (const task of tasksByPlugin.get(name) ?? []) {\n expanded.add(task.id);\n }\n }\n\n return this.byTaskIds([...expanded], trigger, everything);\n }\n\n /**\n * A run of explicit ids, unless there are so many that naming them is\n * pointless — a branch switch or a formatter pass resolves half the project,\n * and a filtered full run is both cheaper to express and easier to read.\n */\n private byTaskIds(\n taskIds: string[],\n trigger: { source: \"watch\"; files: string[] },\n everything: WatchResolution,\n ): WatchResolution {\n if (taskIds.length > this.maxTasks) {\n return everything;\n }\n\n return {\n scope: \"tasks\",\n taskIds,\n request: {\n taskIds,\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n private isIgnored(candidate: string): boolean {\n const absolute = path.resolve(this.cwd, candidate);\n const relative = path.relative(this.cwd, absolute);\n\n // Outside the working directory: nothing here can be attributed to a task.\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n return true;\n }\n\n for (const ignored of this.ignoredRoots) {\n if (\n absolute === ignored ||\n absolute.startsWith(`${ignored}${path.sep}`)\n ) {\n return true;\n }\n }\n\n return relative\n .split(path.sep)\n .some((segment) => DEFAULT_IGNORED_DIRS.has(segment));\n }\n}\n\n/** The part of a glob before its first magic character — the directory to watch. */\nexport const globRoot = (pattern: string): string => {\n const segments = pattern.split(\"/\");\n const staticSegments: string[] = [];\n\n for (const segment of segments) {\n if (/[*?[\\]{}!+@(]/.test(segment)) {\n break;\n }\n staticSegments.push(segment);\n }\n\n // Drop the last static segment only when it is the file itself; a pattern\n // with no magic at all is a literal path and stays as it is.\n const root = staticSegments.join(\"/\");\n return root === \"\" ? \".\" : root;\n};\n\n/**\n * What to hand the watcher.\n *\n * The project root by default, plus the roots of whatever globs the plugins\n * declared. Plugin globs can only widen the set: a plugin that maps story files\n * precisely still has to be told about the component those stories render, and\n * that component is not in its globs.\n */\nconst resolveRoots = (\n paths: string[] | undefined,\n plugins: RunnablePlugin[],\n): string[] => {\n const roots = new Set(paths && paths.length > 0 ? paths : [\".\"]);\n\n for (const plugin of plugins) {\n for (const pattern of plugin.watch?.paths ?? []) {\n roots.add(globRoot(pattern));\n }\n }\n\n // \".\" subsumes everything else.\n if (roots.has(\".\")) {\n return [\".\"];\n }\n\n return [...roots];\n};\n\nconst toRelative = (cwd: string, changedPath: string): string => {\n if (!path.isAbsolute(changedPath)) {\n return changedPath.split(path.sep).join(\"/\");\n }\n return path.relative(cwd, changedPath).split(path.sep).join(\"/\");\n};\n","import { ScreenshotFileSystem } from \"../filesystem\";\nimport type { PluginTask } from \"../plugin\";\nimport { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type {\n RunDetail,\n RunEvent,\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport ScreenshotTool from \"../screenshot\";\nimport { collectScreenshots } from \"../screenshots/collectScreenshots\";\nimport type { DiffOptions, Screenshot, Viewport } from \"../types\";\nimport { RunStore, type RunStoreOptions } from \"./RunStore\";\nimport {\n type ApproveResult,\n type CaptureEngine,\n type EmittableWatchEvent,\n type ListTargetsOptions,\n type PluginInfo,\n RunInProgressError,\n type ScreenshotQuery,\n type StartWatchRequest,\n type SubscribeOptions,\n UnknownTargetsError,\n type WatchEvent,\n WatchInProgressError,\n type WatchStatus,\n} from \"./types\";\nimport { WarmBrowser } from \"./WarmBrowser\";\nimport {\n type CreateFileWatcher,\n DEFAULT_DEBOUNCE_MS,\n WatchSession,\n} from \"./WatchSession\";\n\nexport type LocalEngineOptions = {\n outputDir: string;\n plugins: RunnablePlugin[];\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: boolean;\n fullPage?: boolean;\n viewport?: Viewport;\n connectionTimeout?: number;\n /**\n * How long the browser stays warm between runs.\n * @default 300_000 (5 minutes)\n */\n browserIdleTimeoutMs?: number;\n runStore?: RunStoreOptions;\n /** Overrides the screenshot tool factory. Tests use this. */\n createScreenshotTool?: () => ScreenshotTool;\n /** Working directory a watch session watches. @default process.cwd() */\n cwd?: string;\n /** Overrides the file watcher factory. Tests use this. */\n createWatcher?: CreateFileWatcher;\n /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */\n maxWatchEvents?: number;\n};\n\n/**\n * `CaptureEngine` backed by an in-process Playwright browser.\n *\n * Holds the config's live plugin objects, so it must live in the process that\n * loaded `cappa.config.ts`. The server takes one of these by injection rather\n * than building it, which is what keeps `@cappa/server` free of config loading\n * and makes a remote engine a drop-in alternative.\n *\n * One run at a time. Queuing is deliberately not implemented: the browser pool\n * is the real constraint, and a second concurrent run would fight it.\n */\nexport class LocalEngine implements CaptureEngine {\n private readonly options: LocalEngineOptions;\n private readonly plugins: RunnablePlugin[];\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly browser: WarmBrowser;\n private readonly runs: RunStore;\n\n /**\n * Set synchronously the moment a run is claimed, before any `await`, so two\n * concurrent `startRun` calls cannot both pass the check and then fight over\n * the browser. Covers the window between claiming and the run finishing.\n */\n private busy = false;\n private activeRunId: string | null = null;\n private targetsCache: Target[] | null = null;\n /**\n * The tasks behind `targetsCache`, kept whole.\n *\n * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the\n * task it came from, `data` included — that is where a story's `importPath`\n * lives. Same discovery, two shapes, one cache lifetime.\n */\n private taskCache: Map<string, PluginTask[]> | null = null;\n private closed = false;\n\n private watchSession: WatchSession | null = null;\n private releaseBrowserHold: (() => void) | null = null;\n private readonly watchListeners = new Set<(event: WatchEvent) => void>();\n private watchEvents: WatchEvent[] = [];\n private watchSeq = 0;\n\n constructor(options: LocalEngineOptions) {\n this.options = options;\n this.plugins = options.plugins;\n this.fileSystem = new ScreenshotFileSystem(options.outputDir);\n this.runs = new RunStore(options.runStore);\n this.browser = new WarmBrowser({\n create: options.createScreenshotTool ?? (() => this.buildTool()),\n idleTimeoutMs: options.browserIdleTimeoutMs,\n });\n }\n\n private buildTool(): ScreenshotTool {\n return new ScreenshotTool({\n outputDir: this.options.outputDir,\n diff: this.options.diff,\n retries: this.options.retries,\n concurrency: this.options.concurrency,\n logConsoleEvents: this.options.logConsoleEvents,\n fullPage: this.options.fullPage ?? true,\n viewport: this.options.viewport ?? { width: 1920, height: 1080 },\n connectionTimeout: this.options.connectionTimeout,\n });\n }\n\n async listPlugins(): Promise<PluginInfo[]> {\n return this.plugins.map((plugin) => ({\n name: plugin.name,\n description: plugin.description,\n }));\n }\n\n /**\n * Discovery needs a browser (plugins query the app under test through it), so\n * this warms the browser on a cache miss.\n *\n * While a run holds the browser, only the cache can be served: discovering\n * would recycle the very contexts the run is capturing with.\n */\n async listTargets(options: ListTargetsOptions = {}): Promise<Target[]> {\n this.assertOpen();\n\n if (this.targetsCache && !options.refresh) {\n return this.targetsCache;\n }\n\n if (this.busy) {\n if (this.targetsCache) {\n return this.targetsCache;\n }\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n return this.discoverTargets();\n }\n\n async startRun(request: StartRunRequest = {}): Promise<RunSummary> {\n this.assertOpen();\n\n if (this.busy) {\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n // Claim before the first await — see the `busy` field comment.\n this.busy = true;\n\n try {\n await this.validateTaskIds(request);\n\n const tool = await this.browser.acquire();\n\n const runner = new CaptureRunner({\n screenshotTool: tool,\n plugins: this.plugins,\n outputDir: this.options.outputDir,\n fileSystem: this.fileSystem,\n });\n\n const finish = () => {\n if (this.activeRunId !== runner.id) {\n return;\n }\n\n // Discovery results may be stale after a run changed what exists.\n this.targetsCache = null;\n this.taskCache = null;\n this.runs.finalize(runner.id);\n this.activeRunId = null;\n this.busy = false;\n this.browser.release();\n };\n\n // Registered *before* the run store, so cleanup completes inside the same\n // synchronous emit as the terminal event and therefore before any\n // subscriber observes it. Without this, the obvious client behaviour —\n // \"the run finished, start the next one\" — races the engine's own\n // teardown and is rejected as though a run were still in progress.\n runner.on((event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n this.runs.add(runner);\n this.activeRunId = runner.id;\n\n // Deliberately not awaited: the caller gets the run id immediately and\n // follows progress through `subscribeRun`.\n void runner\n .run(request)\n .catch(() => {\n // The failure is already on the event stream as `run:error`, and is\n // readable via `getRun`. Swallow it so it is not an unhandled\n // rejection.\n })\n // Belt and braces: `finish` is idempotent, and this covers any terminal\n // path that somehow did not emit an event.\n .finally(finish);\n\n return runner.getSummary();\n } catch (error) {\n this.busy = false;\n this.activeRunId = null;\n throw error;\n }\n }\n\n async getRun(id: string): Promise<RunDetail | undefined> {\n return this.runs.get(id);\n }\n\n async listRuns(): Promise<RunSummary[]> {\n return this.runs.list();\n }\n\n async cancelRun(id: string): Promise<void> {\n this.runs.getRunner(id)?.abort();\n }\n\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n return this.runs.subscribe(id, onEvent, options);\n }\n\n /**\n * Read the screenshot index from disk.\n *\n * Always a fresh read rather than a cached snapshot — anything can write to\n * `outputDir` while the server is up, including a CLI run in another terminal.\n */\n async listScreenshots(query: ScreenshotQuery = {}): Promise<Screenshot[]> {\n let screenshots = await collectScreenshots(this.options.outputDir);\n\n if (query.category) {\n screenshots = screenshots.filter(\n (screenshot) => screenshot.category === query.category,\n );\n }\n\n if (query.search) {\n const term = query.search.toLowerCase();\n screenshots = screenshots.filter((screenshot) =>\n screenshot.name.toLowerCase().includes(term),\n );\n }\n\n return screenshots;\n }\n\n async approve(names: string[]): Promise<ApproveResult> {\n const screenshots = await this.listScreenshots();\n const approved: string[] = [];\n const errors: { name: string; error: string }[] = [];\n\n for (const name of names) {\n const screenshot = screenshots.find((entry) => entry.name === name);\n if (!screenshot) {\n errors.push({ name, error: \"Screenshot not found\" });\n continue;\n }\n\n try {\n await this.fileSystem.approveScreenshots(\n [screenshot],\n this.options.diff ?? { type: \"pixel\" },\n );\n approved.push(name);\n } catch (error) {\n errors.push({\n name,\n error: error instanceof Error ? error.message : \"Approval failed\",\n });\n }\n }\n\n return { approved, errors };\n }\n\n /**\n * Re-capture affected tasks on file change until `stopWatch`.\n *\n * Every iteration goes through `startRun`, so a watch-triggered capture is an\n * ordinary run: same events, same run store, same single-run rule, visible in\n * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.\n */\n async startWatch(request: StartWatchRequest = {}): Promise<WatchStatus> {\n this.assertOpen();\n\n if (this.watchSession) {\n throw new WatchInProgressError();\n }\n\n // Held for the session's whole life: without it the idle timer closes the\n // browser between saves, and the next save pays a cold start — the exact\n // cost watch mode exists to avoid.\n const release = this.browser.hold();\n\n const session = new WatchSession({\n plugins: this.plugins,\n cwd: this.options.cwd,\n paths: request.paths,\n // Captures write into `outputDir`. Watching it would make every run\n // trigger the next one, forever.\n ignoredPaths: [this.options.outputDir],\n filter: request.filter,\n debounceMs: request.debounceMs,\n maxTasks: request.maxTasks,\n createWatcher: this.options.createWatcher,\n discover: () => this.discoverTasks(),\n startRun: (runRequest) => this.startRun(runRequest),\n waitForRun: (runId) => this.waitForRun(runId),\n emit: (event) => this.emitWatchEvent(event),\n });\n\n this.watchSession = session;\n this.releaseBrowserHold = release;\n\n try {\n return await session.start();\n } catch (error) {\n this.watchSession = null;\n this.releaseBrowserHold = null;\n release();\n throw error;\n }\n }\n\n async stopWatch(): Promise<WatchStatus> {\n await this.endWatch(\"requested\");\n return this.getWatchStatus();\n }\n\n async getWatchStatus(): Promise<WatchStatus> {\n return (\n this.watchSession?.getStatus() ?? {\n active: false,\n paths: [],\n debounceMs: DEFAULT_DEBOUNCE_MS,\n }\n );\n }\n\n subscribeWatch(\n onEvent: (event: WatchEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of this.watchEvents) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n this.watchListeners.add(onEvent);\n return () => {\n this.watchListeners.delete(onEvent);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n\n await this.endWatch(\"engine-closed\");\n\n const runner = this.activeRunId\n ? this.runs.getRunner(this.activeRunId)\n : undefined;\n runner?.abort();\n\n await this.browser.close();\n }\n\n private async endWatch(reason: \"requested\" | \"engine-closed\"): Promise<void> {\n const session = this.watchSession;\n const release = this.releaseBrowserHold;\n this.watchSession = null;\n this.releaseBrowserHold = null;\n\n try {\n await session?.stop(reason);\n } finally {\n release?.();\n }\n }\n\n private emitWatchEvent(event: EmittableWatchEvent): void {\n this.watchSeq += 1;\n const full = { ...event, seq: this.watchSeq, at: Date.now() } as WatchEvent;\n\n this.watchEvents.push(full);\n const max = this.options.maxWatchEvents ?? 200;\n if (this.watchEvents.length > max) {\n this.watchEvents = this.watchEvents.slice(-max);\n }\n\n for (const listener of this.watchListeners) {\n try {\n listener(full);\n } catch {\n // A failing subscriber must not stop the watch session.\n }\n }\n }\n\n /** Resolve once a run reaches a terminal event. */\n private waitForRun(id: string): Promise<void> {\n return new Promise<void>((resolve) => {\n let unsubscribe: (() => void) | undefined;\n let finished = false;\n\n const finish = () => {\n if (finished) {\n return;\n }\n finished = true;\n unsubscribe?.();\n resolve();\n };\n\n unsubscribe = this.runs.subscribe(id, (event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n // Buffered events replay synchronously, so a run that is already over\n // finished before `unsubscribe` existed.\n if (finished) {\n unsubscribe();\n }\n });\n }\n\n /** True while a browser process is alive. Exposed for tests and diagnostics. */\n get isWarm(): boolean {\n return this.browser.isWarm;\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"Engine has been closed\");\n }\n }\n\n /**\n * A client may only ask for tasks that discovery produced.\n *\n * This is a security boundary as much as a correctness one: it is what stops\n * a request from steering the browser to an arbitrary URL.\n */\n private async validateTaskIds(request: StartRunRequest): Promise<void> {\n if (!request.taskIds || request.taskIds.length === 0) {\n return;\n }\n\n // Bypasses the public `listTargets` busy guard on purpose: this runs after\n // the run is claimed but before the browser is acquired, so discovery here\n // cannot disturb an in-flight capture.\n const targets = this.targetsCache ?? (await this.discoverTargets());\n const known = new Set(targets.map((target) => target.id));\n const unknown = request.taskIds.filter((id) => !known.has(id));\n\n if (unknown.length > 0) {\n throw new UnknownTargetsError(unknown);\n }\n }\n\n /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */\n private async discoverTasks(): Promise<Map<string, PluginTask[]>> {\n if (this.taskCache) {\n return this.taskCache;\n }\n\n await this.discoverTargets();\n return this.taskCache ?? new Map();\n }\n\n private async discoverTargets(): Promise<Target[]> {\n const tool = await this.browser.acquire();\n\n try {\n const discovered = await Promise.all(\n this.plugins.map(async (plugin) => {\n const tasks = await plugin.discover(tool);\n return { plugin: plugin.name, tasks };\n }),\n );\n\n this.taskCache = new Map(\n discovered.map(({ plugin, tasks }) => [plugin, tasks]),\n );\n\n this.targetsCache = discovered.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin,\n })),\n );\n return this.targetsCache;\n } finally {\n this.browser.release();\n }\n }\n}\n","import path from \"node:path\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type { DiffMetadata } from \"./types\";\n\n/** The three buckets a screenshot can live in. */\nexport type ScreenshotBucket = \"actual\" | \"expected\" | \"diff\";\n\n/**\n * Byte storage for screenshots, addressed by bucket + relative key\n * (`button--primary.png`, `nested/card.png`).\n *\n * `ScreenshotFileSystem` is local-disk by construction, which is correct for\n * the CLI and a local server but not for an engine running on a machine the\n * reviewer cannot reach. This interface is the seam: an object-store\n * implementation later is an implementation, not a fork.\n *\n * Only `FsScreenshotStore` exists today — nothing in the codebase depends on a\n * second implementation, and none is planned in this change.\n */\nexport interface ScreenshotStore {\n has(bucket: ScreenshotBucket, key: string): Promise<boolean>;\n read(bucket: ScreenshotBucket, key: string): Promise<Buffer>;\n write(bucket: ScreenshotBucket, key: string, data: Buffer): Promise<void>;\n /** Relative keys, recursively. */\n list(bucket: ScreenshotBucket): Promise<string[]>;\n remove(bucket: ScreenshotBucket, key: string): Promise<void>;\n /** Drop every object in a bucket. */\n clear(bucket: ScreenshotBucket): Promise<void>;\n readMeta(key: string): Promise<DiffMetadata | undefined>;\n writeMeta(key: string, meta: DiffMetadata): Promise<void>;\n}\n\n/**\n * `ScreenshotStore` over the local filesystem, delegating to\n * `ScreenshotFileSystem` so both views stay consistent.\n */\nexport class FsScreenshotStore implements ScreenshotStore {\n private readonly fs: ScreenshotFileSystem;\n\n constructor(outputDirOrFs: string | ScreenshotFileSystem) {\n this.fs =\n typeof outputDirOrFs === \"string\"\n ? new ScreenshotFileSystem(outputDirOrFs)\n : outputDirOrFs;\n }\n\n private dirFor(bucket: ScreenshotBucket): string {\n if (bucket === \"actual\") return this.fs.getActualDir();\n if (bucket === \"expected\") return this.fs.getExpectedDir();\n return this.fs.getDiffDir();\n }\n\n private pathFor(bucket: ScreenshotBucket, key: string): string {\n if (bucket === \"actual\") return this.fs.getActualFilePath(key);\n if (bucket === \"expected\") return this.fs.getExpectedFilePath(key);\n return this.fs.getDiffFilePath(key);\n }\n\n async has(bucket: ScreenshotBucket, key: string): Promise<boolean> {\n if (bucket === \"expected\") {\n return this.fs.hasExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n try {\n await fsp.access(this.pathFor(bucket, key));\n return true;\n } catch {\n return false;\n }\n }\n\n async read(bucket: ScreenshotBucket, key: string): Promise<Buffer> {\n if (bucket === \"expected\") {\n return this.fs.readExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n return fsp.readFile(this.pathFor(bucket, key));\n }\n\n async write(\n bucket: ScreenshotBucket,\n key: string,\n data: Buffer,\n ): Promise<void> {\n if (bucket === \"actual\") {\n await this.fs.writeActualFile(key, data);\n return;\n }\n if (bucket === \"diff\") {\n await this.fs.writeDiffFile(key, data);\n return;\n }\n\n const filePath = this.pathFor(bucket, key);\n await this.fs.ensureParentDir(filePath);\n const fsp = await import(\"node:fs/promises\");\n await fsp.writeFile(filePath, data);\n }\n\n async list(bucket: ScreenshotBucket): Promise<string[]> {\n const files =\n bucket === \"actual\"\n ? await this.fs.getActualScreenshots()\n : bucket === \"expected\"\n ? await this.fs.getExpectedScreenshots()\n : await this.fs.getDiffScreenshots();\n\n const dir = this.dirFor(bucket);\n return files.map((file) => path.relative(dir, file));\n }\n\n async remove(bucket: ScreenshotBucket, key: string): Promise<void> {\n const fsp = await import(\"node:fs/promises\");\n await fsp.rm(this.pathFor(bucket, key), { force: true });\n }\n\n async clear(bucket: ScreenshotBucket): Promise<void> {\n if (bucket === \"actual\") {\n this.fs.clearActual();\n return;\n }\n if (bucket === \"diff\") {\n this.fs.clearDiff();\n return;\n }\n\n throw new Error(\n \"Refusing to clear the expected/ bucket: it holds the approved baselines\",\n );\n }\n\n async readMeta(key: string): Promise<DiffMetadata | undefined> {\n const { readDiffMeta } = await import(\"./filesystem\");\n return readDiffMeta(this.fs.getDiffFilePath(key));\n }\n\n async writeMeta(key: string, meta: DiffMetadata): Promise<void> {\n await this.fs.writeDiffMetaFile(key, meta);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,eAAe,OAAO,KAAK;CAC/B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAC5C,CAAC;AAKD,MAAM,4BAAW,IAAI,YAAY,GAAG,EAAA,CAAE,KAAK,GAAG,UAAU;CACtD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;CAG7C,OAAO,MAAM;AACf,CAAC;;;;;;;;;;;AAYD,UAAU,WAAW,QAAwC;CAC3D,IAAI,SAAS,aAAa;CAE1B,OAAO,SAAS,KAAK,OAAO,QAAQ;EAClC,MAAM,SAAS,OAAO,aAAa,MAAM;EACzC,MAAM,OAAO,OAAO,SAAS,SAAS,SAAS,GAAG,SAAS,CAAC;EAC5D,MAAM,YAAY,SAAS;EAC3B,MAAM,UAAU,YAAY;EAE5B,IAAI,U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