@cappa/core 0.1.0 → 0.1.2

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.js CHANGED
@@ -25,6 +25,8 @@ let node_fs = require("node:fs");
25
25
  node_fs = __toESM(node_fs);
26
26
  let node_path = require("node:path");
27
27
  node_path = __toESM(node_path);
28
+ let __cappa_logger = require("@cappa/logger");
29
+ __cappa_logger = __toESM(__cappa_logger);
28
30
  let playwright_core = require("playwright-core");
29
31
  playwright_core = __toESM(playwright_core);
30
32
  let __blazediff_core = require("@blazediff/core");
@@ -34,7 +36,7 @@ pngjs = __toESM(pngjs);
34
36
 
35
37
  //#region src/config.ts
36
38
  /**
37
- * Type helper to make it easier to use vite.config.ts accepts a direct UserConfig object, or a function that returns it. The function receives a ConfigEnv object.
39
+ * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
38
40
  */
39
41
  function defineConfig(options) {
40
42
  return options;
@@ -51,10 +53,9 @@ const compare = (image1, image2, diff, width, height, options) => {
51
53
  * @param image2 - Second image (file path or Buffer)
52
54
  * @param withDiff - Whether to create a diff image
53
55
  * @param options - Comparison options
54
- * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
55
56
  * @returns Comparison result
56
57
  */
57
- async function compareImages(image1, image2, withDiff = false, options) {
58
+ async function compareImages(image1, image2, withDiff = false, options = {}) {
58
59
  const png1 = await loadPNG(image1);
59
60
  const png2 = await loadPNG(image2);
60
61
  const { width, height } = png1;
@@ -65,14 +66,13 @@ async function compareImages(image1, image2, withDiff = false, options) {
65
66
  const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
66
67
  const totalPixels = width * height;
67
68
  const percentDifference = numDiffPixels / totalPixels * 100;
68
- const passed = percentDifference <= (options.maxDiffPercentage || 0);
69
69
  const diffBuffer = diff ? pngjs.PNG.sync.write(diff) : void 0;
70
70
  return {
71
71
  numDiffPixels,
72
72
  totalPixels,
73
73
  percentDifference,
74
74
  diffBuffer,
75
- passed
75
+ passed: isPassed(percentDifference, numDiffPixels, options)
76
76
  };
77
77
  }
78
78
  /**
@@ -85,6 +85,12 @@ async function loadPNG(source) {
85
85
  return pngjs.PNG.sync.read(buffer);
86
86
  }
87
87
  }
88
+ const isPassed = (percentDifference, numDiffPixels, options) => {
89
+ if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
90
+ if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
91
+ if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
92
+ return numDiffPixels === 0;
93
+ };
88
94
 
89
95
  //#endregion
90
96
  //#region src/screenshot.ts
@@ -103,11 +109,11 @@ var ScreenshotTool = class {
103
109
  actualDir;
104
110
  diffDir;
105
111
  expectedDir;
106
- fullPage;
107
112
  browser = null;
108
113
  context = null;
109
114
  page = null;
110
115
  diff;
116
+ logger;
111
117
  constructor(options) {
112
118
  this.browserType = options.browserType || "chromium";
113
119
  this.headless = options.headless !== false;
@@ -116,7 +122,6 @@ var ScreenshotTool = class {
116
122
  height: 1080
117
123
  };
118
124
  this.outputDir = options.outputDir || "./screenshots";
119
- this.fullPage = options.fullPage !== false;
120
125
  this.diff = {
121
126
  ...defaultDiffConfig,
122
127
  ...options.diff
@@ -124,7 +129,11 @@ var ScreenshotTool = class {
124
129
  this.actualDir = node_path.default.join(this.outputDir, "actual");
125
130
  this.diffDir = node_path.default.join(this.outputDir, "diff");
126
131
  this.expectedDir = node_path.default.join(this.outputDir, "expected");
132
+ this.logger = (0, __cappa_logger.getLogger)();
127
133
  }
134
+ /**
135
+ * Initialize playwright and page
136
+ */
128
137
  async init() {
129
138
  this.createDirectories();
130
139
  const browserClass = {
@@ -138,19 +147,29 @@ var ScreenshotTool = class {
138
147
  this.context = await this.browser.newContext({
139
148
  reducedMotion: "reduce",
140
149
  deviceScaleFactor: 2,
141
- userAgent: `${await defaultUserAgent} CappaStorybook`
150
+ userAgent: `${await defaultUserAgent} CappaStorybook`,
151
+ viewport: this.viewport
142
152
  });
143
153
  this.page = await this.context?.newPage();
144
- this.page?.setViewportSize(this.viewport);
145
154
  }
155
+ /**
156
+ * Closes browser
157
+ * If not closed, the process will not exit
158
+ */
146
159
  async close() {
147
160
  if (this.context) await this.context.close();
148
161
  if (this.browser) await this.browser.close();
149
162
  }
163
+ /**
164
+ * Navigates to a URL with "domcontentloaded" waitUntil
165
+ */
150
166
  async goTo(page, url) {
151
167
  if (!this.context) throw new Error("Browser not initialized");
152
168
  await page.goto(url, { waitUntil: "domcontentloaded" });
153
169
  }
170
+ /**
171
+ * Creates directories for screenshots and other files
172
+ */
154
173
  createDirectories() {
155
174
  const directories = [
156
175
  this.outputDir,
@@ -160,62 +179,51 @@ var ScreenshotTool = class {
160
179
  ];
161
180
  for (const dir of directories) if (!node_fs.default.existsSync(dir)) {
162
181
  node_fs.default.mkdirSync(dir, { recursive: true });
163
- console.log(`Created directory: ${dir}`);
182
+ this.logger.debug(`Initialized directory: ${dir}`);
164
183
  }
165
184
  }
185
+ /**
186
+ * Gets the path to the actual screenshot file
187
+ */
166
188
  getActualFilePath(filename) {
167
189
  return node_path.default.join(this.actualDir, filename);
168
190
  }
191
+ /**
192
+ * Gets the path to the diff screenshot file
193
+ */
169
194
  getDiffFilePath(filename) {
170
195
  return node_path.default.join(this.diffDir, filename);
171
196
  }
197
+ /**
198
+ * Gets the path to the expected screenshot file
199
+ */
172
200
  getExpectedFilePath(filename) {
173
201
  return node_path.default.join(this.expectedDir, filename);
174
202
  }
175
- getFilePath(filename) {
176
- return this.getActualFilePath(filename);
177
- }
178
- async takeScreenshot(page, filename, options = {}) {
203
+ /**
204
+ * Takes a screenshot of the page
205
+ */
206
+ async takeScreenshot(page, filename, options) {
179
207
  if (!this.browser) throw new Error("Browser not initialized");
208
+ if (options.skip) return;
180
209
  try {
181
210
  const filepath = this.getActualFilePath(filename);
182
211
  const screenshotOptions = {
183
212
  path: filepath,
184
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
213
+ fullPage: options.fullPage,
185
214
  type: "png",
186
215
  timeout: 6e4,
187
216
  mask: options.mask,
188
217
  omitBackground: options.omitBackground,
189
218
  scale: "css"
190
219
  };
220
+ if (options.delay) await page.waitForTimeout(options.delay);
191
221
  await page.screenshot(screenshotOptions);
192
- console.log(`Screenshot saved: ${filepath}`);
193
- return filepath;
194
- } catch (error) {
195
- console.error(`Error taking screenshot of ${page.url()}:`, error.message);
196
- throw error;
197
- }
198
- }
199
- async takeElementScreenshot(page, selector, options = {}) {
200
- if (!this.browser) throw new Error("Browser not initialized");
201
- try {
202
- await page.waitForSelector(selector, { timeout: 1e4 });
203
- const element = await page.$(selector);
204
- if (!element) throw new Error(`Element not found: ${selector}`);
205
- const filename = options.filename || `${selector.replace(/[^a-zA-Z0-9]/g, "_")}.png`;
206
- const filepath = this.getActualFilePath(filename);
207
- const elementScreenshotOptions = {
208
- path: filepath,
209
- type: "png"
210
- };
211
- await element.screenshot(elementScreenshotOptions);
212
- console.log(`Element screenshot saved: ${filepath}`);
222
+ this.logger.success(`Screenshot saved: ${filepath}`);
213
223
  return filepath;
214
224
  } catch (error) {
215
- console.error(`Error taking element screenshot of ${page.url()}:`, error.message);
225
+ this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
216
226
  throw error;
217
- } finally {
218
- await page.close();
219
227
  }
220
228
  }
221
229
  async takeScreenshotWithComparison(page, filename, referenceImage, options = {}) {
@@ -224,7 +232,7 @@ var ScreenshotTool = class {
224
232
  const filepath = this.getActualFilePath(filename);
225
233
  node_fs.default.mkdirSync(node_path.default.dirname(filepath), { recursive: true });
226
234
  const screenshotOptions = {
227
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
235
+ fullPage: options.fullPage,
228
236
  type: "png",
229
237
  timeout: 6e4,
230
238
  mask: options.mask,
@@ -233,18 +241,21 @@ var ScreenshotTool = class {
233
241
  };
234
242
  const screenshotBuffer = await page.screenshot(screenshotOptions);
235
243
  node_fs.default.writeFileSync(filepath, screenshotBuffer);
236
- console.log(`Screenshot saved: ${filepath}`);
244
+ this.logger.success(`Screenshot saved: ${filepath}`);
237
245
  const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
238
246
  ...this.diff,
239
247
  ...options.compareOptions
240
248
  });
241
- console.log(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${comparisonResult.passed ? "PASSED" : "FAILED"})`);
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`);
251
+ else this.logger.error(`Screenshot failed visual comparison`);
242
252
  let diffImagePath;
243
253
  if (options.saveDiffImage && comparisonResult.diffBuffer && !comparisonResult.passed) {
244
254
  const diffFilename = options.diffImageFilename || filename;
245
255
  diffImagePath = this.getDiffFilePath(diffFilename);
246
256
  node_fs.default.mkdirSync(node_path.default.dirname(diffImagePath), { recursive: true });
247
257
  node_fs.default.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
258
+ this.logger.debug(`Diff image saved: ${diffImagePath}`);
248
259
  }
249
260
  return {
250
261
  screenshotPath: filepath,
@@ -252,82 +263,10 @@ var ScreenshotTool = class {
252
263
  diffImagePath
253
264
  };
254
265
  } catch (error) {
255
- console.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
266
+ this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
256
267
  throw error;
257
268
  }
258
269
  }
259
- async batchScreenshots(urls, options = {}) {
260
- const results = [];
261
- for (const url of urls) try {
262
- const page = this.page;
263
- if (!page) throw new Error("Page not initialized");
264
- await this.goTo(page, url);
265
- const filepath = await this.takeScreenshot(page, url, options);
266
- results.push({
267
- url,
268
- success: true,
269
- filepath
270
- });
271
- } catch (error) {
272
- results.push({
273
- url,
274
- success: false,
275
- error: error.message,
276
- filepath: ""
277
- });
278
- }
279
- return results;
280
- }
281
- async takeResponsiveScreenshots(url, viewports = [
282
- {
283
- width: 1920,
284
- height: 1080,
285
- name: "desktop"
286
- },
287
- {
288
- width: 768,
289
- height: 1024,
290
- name: "tablet"
291
- },
292
- {
293
- width: 375,
294
- height: 667,
295
- name: "mobile"
296
- }
297
- ], options = {}) {
298
- if (!this.context) throw new Error("Browser not initialized");
299
- const results = [];
300
- for (const viewport of viewports) try {
301
- const page = await this.context?.newPage();
302
- await page.setViewportSize(viewport);
303
- await page.goto(url, { waitUntil: "domcontentloaded" });
304
- await page.waitForTimeout(2e3);
305
- const filename = `${viewport.name}.png`;
306
- const filepath = this.getActualFilePath(filename);
307
- const responsiveScreenshotOptions = {
308
- path: filepath,
309
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
310
- type: "png"
311
- };
312
- await page.screenshot(responsiveScreenshotOptions);
313
- await page.close();
314
- console.log(`Responsive screenshot saved: ${filepath}`);
315
- results.push({
316
- viewport: viewport.name,
317
- success: true,
318
- filepath
319
- });
320
- } catch (error) {
321
- console.error(`Error taking responsive screenshot for ${viewport.name}:`, error.message);
322
- results.push({
323
- viewport: viewport.name,
324
- success: false,
325
- error: error.message,
326
- filepath: ""
327
- });
328
- }
329
- return results;
330
- }
331
270
  hasExpectedImage(filename) {
332
271
  const expectedPath = this.getExpectedFilePath(filename);
333
272
  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","results: {\n url: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[]","results: {\n viewport: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[]"],"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 vite.config.ts accepts a direct UserConfig object, 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 * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)\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 // Create diff image\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n // Compare images using pixelmatch\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 const passed = percentDifference <= (options.maxDiffPercentage || 0);\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,\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 maxDifferencePercent - Maximum allowed difference percentage (0-100)\n * @param options - Comparison options\n * @returns Whether the images are similar enough\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 return result.passed;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\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 } 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: string;\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n fullPage: boolean;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n\n constructor(options: {\n browserType?: string;\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n fullPage?: boolean;\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.fullPage = options.fullPage !== false; // Default to full page\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\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 =\n browserMap[this.browserType as keyof typeof browserMap];\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 });\n\n this.page = await this.context?.newPage();\n this.page?.setViewportSize(this.viewport);\n }\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 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 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 console.log(`Created directory: ${dir}`);\n }\n }\n }\n\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n // Keep original method for backward compatibility\n getFilePath(filename: string) {\n return this.getActualFilePath(filename);\n }\n\n async takeScreenshot(\n page: Page,\n filename: string,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n } = {},\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\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:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.fullPage,\n type: \"png\",\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n await page.screenshot(screenshotOptions);\n\n console.log(`Screenshot saved: ${filepath}`);\n return filepath;\n } catch (error) {\n console.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeElementScreenshot(\n page: Page,\n selector: string,\n options: {\n filename?: string;\n fullPage?: boolean;\n } = {},\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Wait for element to be visible\n await page.waitForSelector(selector, { timeout: 10000 });\n\n const element = await page.$(selector);\n if (!element) {\n throw new Error(`Element not found: ${selector}`);\n }\n\n const filename =\n (options.filename as string | undefined) ||\n `${selector.replace(/[^a-zA-Z0-9]/g, \"_\")}.png`;\n // Save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n const elementScreenshotOptions = {\n path: filepath,\n type: \"png\",\n } satisfies PageScreenshotOptions;\n\n await element.screenshot(elementScreenshotOptions);\n\n console.log(`Element screenshot saved: ${filepath}`);\n return filepath;\n } catch (error) {\n console.error(\n `Error taking element screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n } finally {\n await page.close();\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:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.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 console.log(`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 console.log(\n `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${\n comparisonResult.passed ? \"PASSED\" : \"FAILED\"\n })`,\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\n return {\n screenshotPath: filepath,\n comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n console.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async batchScreenshots(urls: string[], options = {}) {\n const results: {\n url: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[] = [];\n\n for (const url of urls) {\n try {\n const page = this.page;\n if (!page) {\n throw new Error(\"Page not initialized\");\n }\n await this.goTo(page, url);\n const filepath = await this.takeScreenshot(page, url, options);\n results.push({ url, success: true, filepath });\n } catch (error) {\n results.push({\n url,\n success: false,\n error: (error as Error).message,\n filepath: \"\",\n });\n }\n }\n\n return results;\n }\n\n async takeResponsiveScreenshots(\n url: string,\n viewports: { width: number; height: number; name: string }[] = [\n { width: 1920, height: 1080, name: \"desktop\" },\n { width: 768, height: 1024, name: \"tablet\" },\n { width: 375, height: 667, name: \"mobile\" },\n ],\n options: {\n fullPage?: boolean;\n } = {},\n ) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n\n const results: {\n viewport: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[] = [];\n\n for (const viewport of viewports) {\n try {\n const page = await this.context?.newPage();\n await page.setViewportSize(viewport);\n\n await page.goto(url, { waitUntil: \"domcontentloaded\" });\n await page.waitForTimeout(2000);\n\n const filename = `${viewport.name}.png`;\n // Save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n const responsiveScreenshotOptions = {\n path: filepath,\n fullPage:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.fullPage,\n type: \"png\" as const,\n };\n\n await page.screenshot(responsiveScreenshotOptions);\n\n await page.close();\n\n console.log(`Responsive screenshot saved: ${filepath}`);\n results.push({ viewport: viewport.name, success: true, filepath });\n } catch (error) {\n console.error(\n `Error taking responsive screenshot for ${viewport.name}:`,\n (error as Error).message,\n );\n results.push({\n viewport: viewport.name,\n success: false,\n error: (error as Error).message,\n filepath: \"\",\n });\n }\n }\n\n return results;\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,sCAAiB,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;;AAYhE,eAAsB,cACpB,QACA,QACA,WAAoB,OACpB,SACwB;CAExB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;CAG1B,MAAM,OAAO,WAAW,IAAIA,UAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAGrD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;CAC5B,MAAM,oBAAqB,gBAAgB,cAAe;CAC1D,MAAM,SAAS,sBAAsB,QAAQ,qBAAqB;CAGlE,MAAM,aAAa,OAAOA,UAAI,KAAK,MAAM,KAAK,GAAG;AAEjD,QAAO;EACL;EACA;EACA;EACA;EACA;EACD;;;;;AAMH,eAAe,QAAQ,QAAuC;AAC5D,KAAI,OAAO,SAAS,OAAO,CACzB,QAAOA,UAAI,KAAK,KAAK,OAAO;MACvB;EACL,MAAM,SAASC,gBAAG,aAAa,OAAO;AACtC,SAAOD,UAAI,KAAK,KAAK,OAAO;;;;;;AClEhC,MAAME,oBAAgC;CACpC,WAAW;CACX,WAAW;CACX,iBAAiB;CACjB,eAAe;CACf,mBAAmB;CACpB;AAED,IAAM,iBAAN,MAAqB;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,UAA0B;CAC1B,UAAiC;CACjC,OAAoB;CACpB;CAEA,YAAY,SAOT;AACD,OAAK,cAAc,QA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AQ,WACR,KAAK;IACX,MAAM;IACP;AAED,SAAM,KAAK,WAAW,4BAA4B;AAElD,SAAM,KAAK,OAAO;AAElB,WAAQ,IAAI,gCAAgC,WAAW;AACvD,WAAQ,KAAK;IAAE,UAAU,SAAS;IAAM,SAAS;IAAM;IAAU,CAAC;WAC3D,OAAO;AACd,WAAQ,MACN,0CAA0C,SAAS,KAAK,IACvD,MAAgB,QAClB;AACD,WAAQ,KAAK;IACX,UAAU,SAAS;IACnB,SAAS;IACT,OAAQ,MAAgB;IACxB,UAAU;IACX,CAAC;;AAIN,SAAO;;CAIT,iBAAiB,UAA2B;EAC1C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,SAAOH,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"}
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;ACMT,MAAM,WACJ,QACA,QACA,MACA,OACA,QACA,YACG;AACH,sCAAiB,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;AAWhE,eAAsB,cACpB,QACA,Q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