@cappa/core 0.1.2 → 0.1.3

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.
@@ -1,11 +1,11 @@
1
1
 
2
2
 
3
- > @cappa/core@0.1.1 build /home/tim/cappa/packages/core
3
+ > @cappa/core@0.1.2 build /home/tim/cappa/packages/core
4
4
  > tsdown
5
5
 
6
6
  ℹ tsdown v0.14.1 powered by rolldown v1.0.0-beta.40
7
7
  ℹ Using tsdown config: /home/tim/cappa/packages/core/tsdown.config.ts
8
- (node:256487) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///home/tim/cappa/packages/core/tsdown.config.ts is not specified and it doesn't parse as CommonJS.
8
+ (node:287825) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///home/tim/cappa/packages/core/tsdown.config.ts is not specified and it doesn't parse as CommonJS.
9
9
  Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
10
10
  To eliminate this warning, add "type": "module" to /home/tim/cappa/packages/core/package.json.
11
11
  (Use `node --trace-warnings ...` to show where the warning was created)
@@ -17,15 +17,15 @@ To eliminate this warning, add "type": "module" to /home/tim/cappa/packages/core
17
17
  - For the "resolve.tsconfigFilename". It is deprecated. Please use the top-level `tsconfig` option instead. 
18
18
  Warning: Invalid input options (1 issue found)
19
19
  - For the "resolve.tsconfigFilename". It is deprecated. Please use the top-level `tsconfig` option instead. 
20
- ℹ [CJS] dist/index.js  9.57 kB │ gzip: 2.94 kB
21
- ℹ [CJS] dist/index.js.map 17.73 kB │ gzip: 5.11 kB
22
- ℹ [CJS] 2 files, total: 27.31 kB
20
+ ℹ [CJS] dist/index.js 10.91 kB │ gzip: 3.28 kB
21
+ ℹ [CJS] dist/index.js.map 20.29 kB │ gzip: 5.71 kB
22
+ ℹ [CJS] 2 files, total: 31.20 kB
23
23
  Warning: Invalid input options (1 issue found)
24
24
  - For the "resolve.tsconfigFilename". It is deprecated. Please use the top-level `tsconfig` option instead. 
25
- ℹ [ESM] dist/index.mjs  7.97 kB │ gzip: 2.44 kB
26
- ℹ [ESM] dist/index.mjs.map 17.66 kB │ gzip: 5.08 kB
27
- ℹ [ESM] dist/index.d.mts  5.99 kB │ gzip: 2.09 kB
28
- ℹ [ESM] 3 files, total: 31.61 kB
29
- ℹ [CJS] dist/index.d.ts 5.99 kB │ gzip: 2.09 kB
30
- ℹ [CJS] 1 files, total: 5.99 kB
31
- ✔ Build complete in 1205ms
25
+ ℹ [ESM] dist/index.mjs  9.30 kB │ gzip: 2.79 kB
26
+ ℹ [ESM] dist/index.mjs.map 20.21 kB │ gzip: 5.67 kB
27
+ ℹ [ESM] dist/index.d.mts  6.36 kB │ gzip: 2.15 kB
28
+ ℹ [ESM] 3 files, total: 35.88 kB
29
+ ℹ [CJS] dist/index.d.ts 6.36 kB │ gzip: 2.14 kB
30
+ ℹ [CJS] 1 files, total: 6.36 kB
31
+ ✔ Build complete in 1271ms
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @cappa/core
2
2
 
3
+ ## 0.1.3
4
+
5
+ ### Patch Changes
6
+
7
+ - f6456fb: feat: add retry functionality
8
+ - Updated dependencies [f6456fb]
9
+ - @cappa/logger@0.0.3
10
+
3
11
  ## 0.1.2
4
12
 
5
13
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,9 +1,7 @@
1
1
  import { Logger } from "@cappa/logger";
2
2
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
3
- import { BlazeDiffOptions } from "@blazediff/types";
4
3
 
5
4
  //#region src/compare.d.ts
6
- type CompareOptions = BlazeDiffOptions;
7
5
  interface CompareResult {
8
6
  numDiffPixels: number;
9
7
  totalPixels: number;
@@ -37,6 +35,7 @@ declare class ScreenshotTool {
37
35
  page: Page | null;
38
36
  diff: DiffConfig;
39
37
  logger: Logger;
38
+ retries: number;
40
39
  constructor(options: {
41
40
  browserType?: "chromium" | "firefox" | "webkit";
42
41
  headless?: boolean;
@@ -46,6 +45,7 @@ declare class ScreenshotTool {
46
45
  };
47
46
  outputDir?: string;
48
47
  diff?: DiffConfig;
48
+ retries?: number;
49
49
  });
50
50
  /**
51
51
  * Initialize playwright and page
@@ -80,12 +80,7 @@ declare class ScreenshotTool {
80
80
  * Takes a screenshot of the page
81
81
  */
82
82
  takeScreenshot(page: Page, filename: string, options: ScreenshotOptions): Promise<string | undefined>;
83
- takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options?: {
84
- fullPage?: boolean;
85
- mask?: Locator[];
86
- omitBackground?: boolean;
87
- compareOptions?: CompareOptions;
88
- maxDifferencePercent?: number;
83
+ takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotOptions & {
89
84
  saveDiffImage?: boolean;
90
85
  diffImageFilename?: string;
91
86
  }): Promise<{
@@ -93,6 +88,22 @@ declare class ScreenshotTool {
93
88
  comparisonResult: CompareResult;
94
89
  diffImagePath?: string;
95
90
  }>;
91
+ retryScreenshot(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotOptions & {
92
+ saveDiffImage?: boolean;
93
+ diffImageFilename?: string;
94
+ }): Promise<{
95
+ screenshotPath: string;
96
+ comparisonResult: CompareResult;
97
+ passed: boolean;
98
+ } | {
99
+ screenshotPath: null;
100
+ comparisonResult: null;
101
+ passed: boolean;
102
+ }>;
103
+ /**
104
+ * Gets the exponential backoff delay
105
+ */
106
+ getIncBackoffDelay(i: number, delay: number): number;
96
107
  hasExpectedImage(filename: string): boolean;
97
108
  getExpectedImageBuffer(filename: string): Buffer;
98
109
  }
@@ -179,6 +190,10 @@ type UserConfig = {
179
190
  * Configuration for the comparison of images
180
191
  */
181
192
  diff?: DiffConfig;
193
+ /**
194
+ * The number of times to retry a screenshot if it fails
195
+ */
196
+ retries?: number;
182
197
  /**
183
198
  * An array of Cappa plugins used for generation.
184
199
  * Each plugin may have additional configurable options (defined within the plugin itself).
package/dist/index.d.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
2
2
  import { Logger } from "@cappa/logger";
3
- import { BlazeDiffOptions } from "@blazediff/types";
4
3
 
5
4
  //#region src/compare.d.ts
6
- type CompareOptions = BlazeDiffOptions;
7
5
  interface CompareResult {
8
6
  numDiffPixels: number;
9
7
  totalPixels: number;
@@ -37,6 +35,7 @@ declare class ScreenshotTool {
37
35
  page: Page | null;
38
36
  diff: DiffConfig;
39
37
  logger: Logger;
38
+ retries: number;
40
39
  constructor(options: {
41
40
  browserType?: "chromium" | "firefox" | "webkit";
42
41
  headless?: boolean;
@@ -46,6 +45,7 @@ declare class ScreenshotTool {
46
45
  };
47
46
  outputDir?: string;
48
47
  diff?: DiffConfig;
48
+ retries?: number;
49
49
  });
50
50
  /**
51
51
  * Initialize playwright and page
@@ -80,12 +80,7 @@ declare class ScreenshotTool {
80
80
  * Takes a screenshot of the page
81
81
  */
82
82
  takeScreenshot(page: Page, filename: string, options: ScreenshotOptions): Promise<string | undefined>;
83
- takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options?: {
84
- fullPage?: boolean;
85
- mask?: Locator[];
86
- omitBackground?: boolean;
87
- compareOptions?: CompareOptions;
88
- maxDifferencePercent?: number;
83
+ takeScreenshotWithComparison(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotOptions & {
89
84
  saveDiffImage?: boolean;
90
85
  diffImageFilename?: string;
91
86
  }): Promise<{
@@ -93,6 +88,22 @@ declare class ScreenshotTool {
93
88
  comparisonResult: CompareResult;
94
89
  diffImagePath?: string;
95
90
  }>;
91
+ retryScreenshot(page: Page, filename: string, referenceImage: Buffer, options: ScreenshotOptions & {
92
+ saveDiffImage?: boolean;
93
+ diffImageFilename?: string;
94
+ }): Promise<{
95
+ screenshotPath: string;
96
+ comparisonResult: CompareResult;
97
+ passed: boolean;
98
+ } | {
99
+ screenshotPath: null;
100
+ comparisonResult: null;
101
+ passed: boolean;
102
+ }>;
103
+ /**
104
+ * Gets the exponential backoff delay
105
+ */
106
+ getIncBackoffDelay(i: number, delay: number): number;
96
107
  hasExpectedImage(filename: string): boolean;
97
108
  getExpectedImageBuffer(filename: string): Buffer;
98
109
  }
@@ -179,6 +190,10 @@ type UserConfig = {
179
190
  * Configuration for the comparison of images
180
191
  */
181
192
  diff?: DiffConfig;
193
+ /**
194
+ * The number of times to retry a screenshot if it fails
195
+ */
196
+ retries?: number;
182
197
  /**
183
198
  * An array of Cappa plugins used for generation.
184
199
  * Each plugin may have additional configurable options (defined within the plugin itself).
package/dist/index.js CHANGED
@@ -114,6 +114,7 @@ var ScreenshotTool = class {
114
114
  page = null;
115
115
  diff;
116
116
  logger;
117
+ retries;
117
118
  constructor(options) {
118
119
  this.browserType = options.browserType || "chromium";
119
120
  this.headless = options.headless !== false;
@@ -130,6 +131,7 @@ var ScreenshotTool = class {
130
131
  this.diffDir = node_path.default.join(this.outputDir, "diff");
131
132
  this.expectedDir = node_path.default.join(this.outputDir, "expected");
132
133
  this.logger = (0, __cappa_logger.getLogger)();
134
+ this.retries = options.retries || 2;
133
135
  }
134
136
  /**
135
137
  * Initialize playwright and page
@@ -219,14 +221,13 @@ var ScreenshotTool = class {
219
221
  };
220
222
  if (options.delay) await page.waitForTimeout(options.delay);
221
223
  await page.screenshot(screenshotOptions);
222
- this.logger.success(`Screenshot saved: ${filepath}`);
223
224
  return filepath;
224
225
  } catch (error) {
225
226
  this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
226
227
  throw error;
227
228
  }
228
229
  }
229
- async takeScreenshotWithComparison(page, filename, referenceImage, options = {}) {
230
+ async takeScreenshotWithComparison(page, filename, referenceImage, options) {
230
231
  if (!this.browser) throw new Error("Browser not initialized");
231
232
  try {
232
233
  const filepath = this.getActualFilePath(filename);
@@ -239,27 +240,23 @@ var ScreenshotTool = class {
239
240
  omitBackground: options.omitBackground,
240
241
  scale: "css"
241
242
  };
242
- const screenshotBuffer = await page.screenshot(screenshotOptions);
243
- node_fs.default.writeFileSync(filepath, screenshotBuffer);
243
+ const retryScreenshot = await this.retryScreenshot(page, filename, referenceImage, screenshotOptions);
244
+ if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
245
+ node_fs.default.writeFileSync(filepath, retryScreenshot.screenshotPath);
244
246
  this.logger.success(`Screenshot saved: ${filepath}`);
245
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
246
- ...this.diff,
247
- ...options.compareOptions
248
- });
249
- this.logger.debug(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
250
- if (comparisonResult.passed) this.logger.success(`Screenshot passed visual comparison`);
247
+ if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
251
248
  else this.logger.error(`Screenshot failed visual comparison`);
252
249
  let diffImagePath;
253
- if (options.saveDiffImage && comparisonResult.diffBuffer && !comparisonResult.passed) {
250
+ if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
254
251
  const diffFilename = options.diffImageFilename || filename;
255
252
  diffImagePath = this.getDiffFilePath(diffFilename);
256
253
  node_fs.default.mkdirSync(node_path.default.dirname(diffImagePath), { recursive: true });
257
- node_fs.default.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
254
+ node_fs.default.writeFileSync(diffImagePath, retryScreenshot.comparisonResult.diffBuffer);
258
255
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
259
256
  }
260
257
  return {
261
258
  screenshotPath: filepath,
262
- comparisonResult,
259
+ comparisonResult: retryScreenshot.comparisonResult,
263
260
  diffImagePath
264
261
  };
265
262
  } catch (error) {
@@ -267,6 +264,46 @@ var ScreenshotTool = class {
267
264
  throw error;
268
265
  }
269
266
  }
267
+ async retryScreenshot(page, filename, referenceImage, options) {
268
+ for (let i = 0; i < this.retries; i++) try {
269
+ const screenshotBuffer = await this.takeScreenshot(page, filename, {
270
+ ...options,
271
+ delay: this.getIncBackoffDelay(i, options.delay || 0)
272
+ });
273
+ if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
274
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
275
+ ...this.diff,
276
+ ...options
277
+ });
278
+ if (i === this.retries - 1 && !comparisonResult.passed) {
279
+ this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
280
+ return {
281
+ screenshotPath: screenshotBuffer,
282
+ comparisonResult,
283
+ passed: false
284
+ };
285
+ }
286
+ if (comparisonResult.passed) return {
287
+ screenshotPath: screenshotBuffer,
288
+ comparisonResult,
289
+ passed: true
290
+ };
291
+ else this.logger.warn(`Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
292
+ } catch (error) {
293
+ this.logger.error(`Error taking screenshot after ${i + 1} retries:`, error.message);
294
+ }
295
+ return {
296
+ screenshotPath: null,
297
+ comparisonResult: null,
298
+ passed: false
299
+ };
300
+ }
301
+ /**
302
+ * Gets the exponential backoff delay
303
+ */
304
+ getIncBackoffDelay(i, delay) {
305
+ return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
306
+ }
270
307
  hasExpectedImage(filename) {
271
308
  const expectedPath = this.getExpectedFilePath(filename);
272
309
  return node_fs.default.existsSync(expectedPath);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["PNG","fs","defaultDiffConfig: DiffConfig","path","fs","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { 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 | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\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}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(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 compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\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\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\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.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\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 this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.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, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\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.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n // Comparison options\n compareOptions?: CompareOptions;\n maxDifferencePercent?: number;\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\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.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n // Get screenshot as buffer for comparison\n const screenshotBuffer = await page.screenshot(screenshotOptions);\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, screenshotBuffer);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n // Perform comparison\n const comparisonResult = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options.compareOptions },\n );\n\n this.logger.debug(\n `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\n );\n\n if (comparisonResult.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 comparisonResult.diffBuffer &&\n !comparisonResult.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n 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 // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AIxC,yBAAe"}
1
+ {"version":3,"file":"index.js","names":["PNG","fs","defaultDiffConfig: DiffConfig","path","fs","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { 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 | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\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}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(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 compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\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\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\n retries?: 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.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\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 this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.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, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\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.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\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 async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\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.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n filename,\n referenceImage,\n screenshotOptions,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, retryScreenshot.screenshotPath);\n this.logger.success(`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.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(\n diffImagePath,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff 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 filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshot(page, filename, {\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 = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options },\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 this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\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 /**\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 // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,a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,KAAK,CAAC,iBAAiB,QAAQ;AACtD,SAAK,OAAO,MACV,oCAAoC,KAAK,QAAQ,UAClD;AACD,WAAO;KACL,gBAAgB;KAChB;KACA,QAAQ;KACT;;AAGH,OAAI,iBAAiB,OACnB,QAAO;IACL,gBAAgB;IAChB;IACA,QAAQ;IACT;OAED,MAAK,OAAO,KACV,yCAAyC,KAAK,mBAAmB,IAAI,GAAG,QAAQ,SAAS,EAAE,CAAC,6BAA6B,iBAAiB,cAAc,qBAAqB,iBAAiB,kBAAkB,QAAQ,EAAE,CAAC,IAC5N;WAEI,OAAO;AACd,QAAK,OAAO,MACV,iCAAiC,IAAI,EAAE,YACtC,MAAgB,QAClB;;AAIL,SAAO;GACL,gBAAgB;GAChB,kBAAkB;GAClB,QAAQ;GACT;;;;;CAMH,mBAAmB,GAAW,OAAuB;AACnD,SAAO,IAAI,IAAI,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK;;CAIrD,iBAAiB,UAA2B;EAC1C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,SAAOC,gBAAG,WAAW,aAAa;;CAIpC,uBAAuB,UAA0B;EAC/C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,MAAI,CAACA,gBAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,6BAA6B,eAAe;AAE9D,SAAOA,gBAAG,aAAa,aAAa;;;AAIxC,yBAAe"}
package/dist/index.mjs CHANGED
@@ -85,6 +85,7 @@ var ScreenshotTool = class {
85
85
  page = null;
86
86
  diff;
87
87
  logger;
88
+ retries;
88
89
  constructor(options) {
89
90
  this.browserType = options.browserType || "chromium";
90
91
  this.headless = options.headless !== false;
@@ -101,6 +102,7 @@ var ScreenshotTool = class {
101
102
  this.diffDir = path.join(this.outputDir, "diff");
102
103
  this.expectedDir = path.join(this.outputDir, "expected");
103
104
  this.logger = getLogger();
105
+ this.retries = options.retries || 2;
104
106
  }
105
107
  /**
106
108
  * Initialize playwright and page
@@ -190,14 +192,13 @@ var ScreenshotTool = class {
190
192
  };
191
193
  if (options.delay) await page.waitForTimeout(options.delay);
192
194
  await page.screenshot(screenshotOptions);
193
- this.logger.success(`Screenshot saved: ${filepath}`);
194
195
  return filepath;
195
196
  } catch (error) {
196
197
  this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
197
198
  throw error;
198
199
  }
199
200
  }
200
- async takeScreenshotWithComparison(page, filename, referenceImage, options = {}) {
201
+ async takeScreenshotWithComparison(page, filename, referenceImage, options) {
201
202
  if (!this.browser) throw new Error("Browser not initialized");
202
203
  try {
203
204
  const filepath = this.getActualFilePath(filename);
@@ -210,27 +211,23 @@ var ScreenshotTool = class {
210
211
  omitBackground: options.omitBackground,
211
212
  scale: "css"
212
213
  };
213
- const screenshotBuffer = await page.screenshot(screenshotOptions);
214
- fs.writeFileSync(filepath, screenshotBuffer);
214
+ const retryScreenshot = await this.retryScreenshot(page, filename, referenceImage, screenshotOptions);
215
+ if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
216
+ fs.writeFileSync(filepath, retryScreenshot.screenshotPath);
215
217
  this.logger.success(`Screenshot saved: ${filepath}`);
216
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
217
- ...this.diff,
218
- ...options.compareOptions
219
- });
220
- this.logger.debug(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
221
- if (comparisonResult.passed) this.logger.success(`Screenshot passed visual comparison`);
218
+ if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
222
219
  else this.logger.error(`Screenshot failed visual comparison`);
223
220
  let diffImagePath;
224
- if (options.saveDiffImage && comparisonResult.diffBuffer && !comparisonResult.passed) {
221
+ if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
225
222
  const diffFilename = options.diffImageFilename || filename;
226
223
  diffImagePath = this.getDiffFilePath(diffFilename);
227
224
  fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
228
- fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
225
+ fs.writeFileSync(diffImagePath, retryScreenshot.comparisonResult.diffBuffer);
229
226
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
230
227
  }
231
228
  return {
232
229
  screenshotPath: filepath,
233
- comparisonResult,
230
+ comparisonResult: retryScreenshot.comparisonResult,
234
231
  diffImagePath
235
232
  };
236
233
  } catch (error) {
@@ -238,6 +235,46 @@ var ScreenshotTool = class {
238
235
  throw error;
239
236
  }
240
237
  }
238
+ async retryScreenshot(page, filename, referenceImage, options) {
239
+ for (let i = 0; i < this.retries; i++) try {
240
+ const screenshotBuffer = await this.takeScreenshot(page, filename, {
241
+ ...options,
242
+ delay: this.getIncBackoffDelay(i, options.delay || 0)
243
+ });
244
+ if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
245
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
246
+ ...this.diff,
247
+ ...options
248
+ });
249
+ if (i === this.retries - 1 && !comparisonResult.passed) {
250
+ this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
251
+ return {
252
+ screenshotPath: screenshotBuffer,
253
+ comparisonResult,
254
+ passed: false
255
+ };
256
+ }
257
+ if (comparisonResult.passed) return {
258
+ screenshotPath: screenshotBuffer,
259
+ comparisonResult,
260
+ passed: true
261
+ };
262
+ else this.logger.warn(`Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
263
+ } catch (error) {
264
+ this.logger.error(`Error taking screenshot after ${i + 1} retries:`, error.message);
265
+ }
266
+ return {
267
+ screenshotPath: null,
268
+ comparisonResult: null,
269
+ passed: false
270
+ };
271
+ }
272
+ /**
273
+ * Gets the exponential backoff delay
274
+ */
275
+ getIncBackoffDelay(i, delay) {
276
+ return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
277
+ }
241
278
  hasExpectedImage(filename) {
242
279
  const expectedPath = this.getExpectedFilePath(filename);
243
280
  return fs.existsSync(expectedPath);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { 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 | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\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}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(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 compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\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\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\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.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\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 this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.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, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\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.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n // Comparison options\n compareOptions?: CompareOptions;\n maxDifferencePercent?: number;\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\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.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n // Get screenshot as buffer for comparison\n const screenshotBuffer = await page.screenshot(screenshotOptions);\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, screenshotBuffer);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n // Perform comparison\n const comparisonResult = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options.compareOptions },\n );\n\n this.logger.debug(\n `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\n );\n\n if (comparisonResult.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 comparisonResult.diffBuffer &&\n !comparisonResult.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n 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 // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;ACMT,MAAM,WACJ,QACA,QACA,MACA,OACA,QACA,YACG;AACH,QAAO,UAAU,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;AAWhE,eAAsB,cACpB,QACA,QACA,WAAoB,OACpB,UAAsB,EAAE,EACA;CAExB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;CAE1B,MAAM,OAAO,WAAW,IAAI,IAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAErD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;CAC5B,MAAM,oBAAqB,gBAAgB,cAAe;CAG1D,MAAM,aAAa,OAAO,IAAI,KAAK,MAAM,KAAK,GAAG;AAEjD,QAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,mBAAmB,eAAe,QAAQ;EAC5D;;;;;AAMH,eAAe,QAAQ,QAAuC;AAC5D,KAAI,OAAO,SAAS,OAAO,CACzB,QAAO,IAAI,KAAK,KAAK,OAAO;MACvB;EACL,MAAM,SAAS,GAAG,a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AgB;;AAGzD,UAAO;IACL,gBAAgB;IAChB;IACA;IACD;WACM,OAAO;AACd,QAAK,OAAO,MACV,8CAA8C,KAAK,KAAK,CAAC,IACxD,MAAgB,QAClB;AACD,SAAM;;;CAKV,iBAAiB,UAA2B;EAC1C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,SAAO,GAAG,WAAW,aAAa;;CAIpC,uBAAuB,UAA0B;EAC/C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,MAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,6BAA6B,eAAe;AAE9D,SAAO,GAAG,aAAa,aAAa;;;AAIxC,yBAAe"}
1
+ {"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { 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 | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\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}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(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 compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\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\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\n retries?: 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.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\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 this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.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, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\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.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\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 async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\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.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n filename,\n referenceImage,\n screenshotOptions,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, retryScreenshot.screenshotPath);\n this.logger.success(`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.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(\n diffImagePath,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff 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 filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshot(page, filename, {\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 = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options },\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 this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\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 /**\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 // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;ACMT,MAAM,WACJ,QACA,QACA,MACA,OACA,QACA,YACG;AACH,QAAO,UAAU,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;AAWhE,eAAsB,cACpB,QACA,QACA,WAAoB,OACpB,UAAsB,EAAE,EACA;CAExB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;CAE1B,MAAM,OAAO,WAAW,IAAI,IAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAErD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;CAC5B,MAAM,oBAAqB,gBAAgB,cAAe;CAG1D,MAAM,aAAa,OAAO,IAAI,KAAK,MAAM,KAAK,GAAG;AAEjD,QAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,mBAAmB,eAAe,QAAQ;EAC5D;;;;;AAMH,eAAe,QAAQ,QAAuC;AAC5D,KAAI,OAAO,SAAS,OAAO,CACzB,QAAO,IAAI,KAAK,KAAK,OAAO;MACvB;EACL,MAAM,SAAS,GAAG,aAAa,OAAO;AACtC,SAAO,IAAI,KAAK,KAAK,OAAO;;;AAkChC,MAAM,YACJ,mBACA,eACA,YACG;AACH,KAAI,QAA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
  {
2
2
  "name": "@cappa/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Core Playwright screenshot functionality for Cappa",
5
5
  "author": "tim-richter",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  "pixelmatch": "^6.0.0",
24
24
  "playwright-core": "^1.55.0",
25
25
  "pngjs": "^7.0.0",
26
- "@cappa/logger": "0.0.2"
26
+ "@cappa/logger": "0.0.3"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/node": "22.13.10",
package/src/screenshot.ts CHANGED
@@ -39,6 +39,7 @@ class ScreenshotTool {
39
39
  page: Page | null = null;
40
40
  diff: DiffConfig;
41
41
  logger: Logger;
42
+ retries: number;
42
43
 
43
44
  constructor(options: {
44
45
  browserType?: "chromium" | "firefox" | "webkit";
@@ -46,6 +47,7 @@ class ScreenshotTool {
46
47
  viewport?: { width: number; height: number };
47
48
  outputDir?: string;
48
49
  diff?: DiffConfig;
50
+ retries?: number;
49
51
  }) {
50
52
  this.browserType = options.browserType || "chromium";
51
53
  this.headless = options.headless !== false; // Default to headless
@@ -58,6 +60,7 @@ class ScreenshotTool {
58
60
  this.expectedDir = path.join(this.outputDir, "expected");
59
61
 
60
62
  this.logger = getLogger();
63
+ this.retries = options.retries || 2;
61
64
  }
62
65
 
63
66
  /**
@@ -198,7 +201,6 @@ class ScreenshotTool {
198
201
 
199
202
  await page.screenshot(screenshotOptions);
200
203
 
201
- this.logger.success(`Screenshot saved: ${filepath}`);
202
204
  return filepath;
203
205
  } catch (error) {
204
206
  this.logger.error(
@@ -213,16 +215,10 @@ class ScreenshotTool {
213
215
  page: Page,
214
216
  filename: string,
215
217
  referenceImage: Buffer,
216
- options: {
217
- fullPage?: boolean;
218
- mask?: Locator[];
219
- omitBackground?: boolean;
220
- // Comparison options
221
- compareOptions?: CompareOptions;
222
- maxDifferencePercent?: number;
218
+ options: ScreenshotOptions & {
223
219
  saveDiffImage?: boolean;
224
220
  diffImageFilename?: string;
225
- } = {},
221
+ },
226
222
  ): Promise<{
227
223
  screenshotPath: string;
228
224
  comparisonResult: CompareResult;
@@ -247,27 +243,22 @@ class ScreenshotTool {
247
243
  scale: "css" as const,
248
244
  } satisfies PageScreenshotOptions;
249
245
 
250
- // Get screenshot as buffer for comparison
251
- const screenshotBuffer = await page.screenshot(screenshotOptions);
252
-
253
- // Save screenshot to actual directory
254
- fs.writeFileSync(filepath, screenshotBuffer);
255
-
256
- this.logger.success(`Screenshot saved: ${filepath}`);
257
-
258
- // Perform comparison
259
- const comparisonResult = await compareImages(
260
- screenshotBuffer,
246
+ const retryScreenshot = await this.retryScreenshot(
247
+ page,
248
+ filename,
261
249
  referenceImage,
262
- true,
263
- { ...this.diff, ...options.compareOptions },
250
+ screenshotOptions,
264
251
  );
265
252
 
266
- this.logger.debug(
267
- `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,
268
- );
253
+ if (!retryScreenshot.screenshotPath) {
254
+ throw new Error("Screenshot buffer is undefined");
255
+ }
256
+
257
+ // Save screenshot to actual directory
258
+ fs.writeFileSync(filepath, retryScreenshot.screenshotPath);
259
+ this.logger.success(`Screenshot saved: ${filepath}`);
269
260
 
270
- if (comparisonResult.passed) {
261
+ if (retryScreenshot.passed) {
271
262
  this.logger.success(`Screenshot passed visual comparison`);
272
263
  } else {
273
264
  this.logger.error(`Screenshot failed visual comparison`);
@@ -278,22 +269,25 @@ class ScreenshotTool {
278
269
  // Save diff image if requested and there are differences
279
270
  if (
280
271
  options.saveDiffImage &&
281
- comparisonResult.diffBuffer &&
282
- !comparisonResult.passed
272
+ retryScreenshot.comparisonResult.diffBuffer &&
273
+ !retryScreenshot.passed
283
274
  ) {
284
275
  const diffFilename = options.diffImageFilename || filename;
285
276
  // Save to diff directory
286
277
  diffImagePath = this.getDiffFilePath(diffFilename);
287
278
 
288
279
  fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
289
- fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
280
+ fs.writeFileSync(
281
+ diffImagePath,
282
+ retryScreenshot.comparisonResult.diffBuffer,
283
+ );
290
284
 
291
285
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
292
286
  }
293
287
 
294
288
  return {
295
289
  screenshotPath: filepath,
296
- comparisonResult,
290
+ comparisonResult: retryScreenshot.comparisonResult,
297
291
  diffImagePath,
298
292
  };
299
293
  } catch (error) {
@@ -305,6 +299,78 @@ class ScreenshotTool {
305
299
  }
306
300
  }
307
301
 
302
+ async retryScreenshot(
303
+ page: Page,
304
+ filename: string,
305
+ referenceImage: Buffer,
306
+ options: ScreenshotOptions & {
307
+ saveDiffImage?: boolean;
308
+ diffImageFilename?: string;
309
+ },
310
+ ) {
311
+ for (let i = 0; i < this.retries; i++) {
312
+ try {
313
+ const screenshotBuffer = await this.takeScreenshot(page, filename, {
314
+ ...options,
315
+ delay: this.getIncBackoffDelay(i, options.delay || 0),
316
+ });
317
+
318
+ if (!screenshotBuffer) {
319
+ throw new Error("Screenshot buffer is undefined");
320
+ }
321
+
322
+ const comparisonResult = await compareImages(
323
+ screenshotBuffer,
324
+ referenceImage,
325
+ true,
326
+ { ...this.diff, ...options },
327
+ );
328
+
329
+ // last retry
330
+ if (i === this.retries - 1 && !comparisonResult.passed) {
331
+ this.logger.error(
332
+ `Failed to match screenshot after ${this.retries} retries`,
333
+ );
334
+ return {
335
+ screenshotPath: screenshotBuffer,
336
+ comparisonResult,
337
+ passed: false,
338
+ };
339
+ }
340
+
341
+ if (comparisonResult.passed) {
342
+ return {
343
+ screenshotPath: screenshotBuffer,
344
+ comparisonResult,
345
+ passed: true,
346
+ };
347
+ } else {
348
+ this.logger.warn(
349
+ `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,
350
+ );
351
+ }
352
+ } catch (error) {
353
+ this.logger.error(
354
+ `Error taking screenshot after ${i + 1} retries:`,
355
+ (error as Error).message,
356
+ );
357
+ }
358
+ }
359
+
360
+ return {
361
+ screenshotPath: null,
362
+ comparisonResult: null,
363
+ passed: false,
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Gets the exponential backoff delay
369
+ */
370
+ getIncBackoffDelay(i: number, delay: number): number {
371
+ return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
372
+ }
373
+
308
374
  // Utility method to check if expected image exists
309
375
  hasExpectedImage(filename: string): boolean {
310
376
  const expectedPath = this.getExpectedFilePath(filename);
package/src/types.ts CHANGED
@@ -66,6 +66,10 @@ export type UserConfig = {
66
66
  * Configuration for the comparison of images
67
67
  */
68
68
  diff?: DiffConfig;
69
+ /**
70
+ * The number of times to retry a screenshot if it fails
71
+ */
72
+ retries?: number;
69
73
  /**
70
74
  * An array of Cappa plugins used for generation.
71
75
  * Each plugin may have additional configurable options (defined within the plugin itself).