@cappa/core 0.1.1 → 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.
- package/.turbo/turbo-build.log +12 -12
- package/CHANGELOG.md +16 -0
- package/dist/index.d.mts +66 -59
- package/dist/index.d.ts +66 -59
- package/dist/index.js +95 -119
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +94 -119
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/compare.test.ts +21 -9
- package/src/compare.ts +29 -9
- package/src/config.ts +1 -1
- package/src/index.ts +1 -7
- package/src/plugin.ts +1 -7
- package/src/screenshot.ts +138 -191
- package/src/types.ts +16 -14
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { getLogger } from "@cappa/logger";
|
|
3
4
|
import { chromium, firefox, webkit } from "playwright-core";
|
|
4
5
|
import blazediff from "@blazediff/core";
|
|
5
6
|
import { PNG } from "pngjs";
|
|
6
7
|
|
|
7
8
|
//#region src/config.ts
|
|
8
9
|
/**
|
|
9
|
-
* Type helper to make it easier to use
|
|
10
|
+
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
10
11
|
*/
|
|
11
12
|
function defineConfig(options) {
|
|
12
13
|
return options;
|
|
@@ -23,10 +24,9 @@ const compare = (image1, image2, diff, width, height, options) => {
|
|
|
23
24
|
* @param image2 - Second image (file path or Buffer)
|
|
24
25
|
* @param withDiff - Whether to create a diff image
|
|
25
26
|
* @param options - Comparison options
|
|
26
|
-
* @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
|
|
27
27
|
* @returns Comparison result
|
|
28
28
|
*/
|
|
29
|
-
async function compareImages(image1, image2, withDiff = false, options) {
|
|
29
|
+
async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
30
30
|
const png1 = await loadPNG(image1);
|
|
31
31
|
const png2 = await loadPNG(image2);
|
|
32
32
|
const { width, height } = png1;
|
|
@@ -37,14 +37,13 @@ async function compareImages(image1, image2, withDiff = false, options) {
|
|
|
37
37
|
const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
|
|
38
38
|
const totalPixels = width * height;
|
|
39
39
|
const percentDifference = numDiffPixels / totalPixels * 100;
|
|
40
|
-
const passed = percentDifference <= (options.maxDiffPercentage || 0);
|
|
41
40
|
const diffBuffer = diff ? PNG.sync.write(diff) : void 0;
|
|
42
41
|
return {
|
|
43
42
|
numDiffPixels,
|
|
44
43
|
totalPixels,
|
|
45
44
|
percentDifference,
|
|
46
45
|
diffBuffer,
|
|
47
|
-
passed
|
|
46
|
+
passed: isPassed(percentDifference, numDiffPixels, options)
|
|
48
47
|
};
|
|
49
48
|
}
|
|
50
49
|
/**
|
|
@@ -57,6 +56,12 @@ async function loadPNG(source) {
|
|
|
57
56
|
return PNG.sync.read(buffer);
|
|
58
57
|
}
|
|
59
58
|
}
|
|
59
|
+
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
60
|
+
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
61
|
+
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
62
|
+
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
63
|
+
return numDiffPixels === 0;
|
|
64
|
+
};
|
|
60
65
|
|
|
61
66
|
//#endregion
|
|
62
67
|
//#region src/screenshot.ts
|
|
@@ -75,11 +80,12 @@ var ScreenshotTool = class {
|
|
|
75
80
|
actualDir;
|
|
76
81
|
diffDir;
|
|
77
82
|
expectedDir;
|
|
78
|
-
fullPage;
|
|
79
83
|
browser = null;
|
|
80
84
|
context = null;
|
|
81
85
|
page = null;
|
|
82
86
|
diff;
|
|
87
|
+
logger;
|
|
88
|
+
retries;
|
|
83
89
|
constructor(options) {
|
|
84
90
|
this.browserType = options.browserType || "chromium";
|
|
85
91
|
this.headless = options.headless !== false;
|
|
@@ -88,7 +94,6 @@ var ScreenshotTool = class {
|
|
|
88
94
|
height: 1080
|
|
89
95
|
};
|
|
90
96
|
this.outputDir = options.outputDir || "./screenshots";
|
|
91
|
-
this.fullPage = options.fullPage !== false;
|
|
92
97
|
this.diff = {
|
|
93
98
|
...defaultDiffConfig,
|
|
94
99
|
...options.diff
|
|
@@ -96,7 +101,12 @@ var ScreenshotTool = class {
|
|
|
96
101
|
this.actualDir = path.join(this.outputDir, "actual");
|
|
97
102
|
this.diffDir = path.join(this.outputDir, "diff");
|
|
98
103
|
this.expectedDir = path.join(this.outputDir, "expected");
|
|
104
|
+
this.logger = getLogger();
|
|
105
|
+
this.retries = options.retries || 2;
|
|
99
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Initialize playwright and page
|
|
109
|
+
*/
|
|
100
110
|
async init() {
|
|
101
111
|
this.createDirectories();
|
|
102
112
|
const browserClass = {
|
|
@@ -110,19 +120,29 @@ var ScreenshotTool = class {
|
|
|
110
120
|
this.context = await this.browser.newContext({
|
|
111
121
|
reducedMotion: "reduce",
|
|
112
122
|
deviceScaleFactor: 2,
|
|
113
|
-
userAgent: `${await defaultUserAgent} CappaStorybook
|
|
123
|
+
userAgent: `${await defaultUserAgent} CappaStorybook`,
|
|
124
|
+
viewport: this.viewport
|
|
114
125
|
});
|
|
115
126
|
this.page = await this.context?.newPage();
|
|
116
|
-
this.page?.setViewportSize(this.viewport);
|
|
117
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Closes browser
|
|
130
|
+
* If not closed, the process will not exit
|
|
131
|
+
*/
|
|
118
132
|
async close() {
|
|
119
133
|
if (this.context) await this.context.close();
|
|
120
134
|
if (this.browser) await this.browser.close();
|
|
121
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Navigates to a URL with "domcontentloaded" waitUntil
|
|
138
|
+
*/
|
|
122
139
|
async goTo(page, url) {
|
|
123
140
|
if (!this.context) throw new Error("Browser not initialized");
|
|
124
141
|
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
125
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Creates directories for screenshots and other files
|
|
145
|
+
*/
|
|
126
146
|
createDirectories() {
|
|
127
147
|
const directories = [
|
|
128
148
|
this.outputDir,
|
|
@@ -132,173 +152,128 @@ var ScreenshotTool = class {
|
|
|
132
152
|
];
|
|
133
153
|
for (const dir of directories) if (!fs.existsSync(dir)) {
|
|
134
154
|
fs.mkdirSync(dir, { recursive: true });
|
|
135
|
-
|
|
155
|
+
this.logger.debug(`Initialized directory: ${dir}`);
|
|
136
156
|
}
|
|
137
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Gets the path to the actual screenshot file
|
|
160
|
+
*/
|
|
138
161
|
getActualFilePath(filename) {
|
|
139
162
|
return path.join(this.actualDir, filename);
|
|
140
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Gets the path to the diff screenshot file
|
|
166
|
+
*/
|
|
141
167
|
getDiffFilePath(filename) {
|
|
142
168
|
return path.join(this.diffDir, filename);
|
|
143
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* Gets the path to the expected screenshot file
|
|
172
|
+
*/
|
|
144
173
|
getExpectedFilePath(filename) {
|
|
145
174
|
return path.join(this.expectedDir, filename);
|
|
146
175
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
async takeScreenshot(page, filename, options
|
|
176
|
+
/**
|
|
177
|
+
* Takes a screenshot of the page
|
|
178
|
+
*/
|
|
179
|
+
async takeScreenshot(page, filename, options) {
|
|
151
180
|
if (!this.browser) throw new Error("Browser not initialized");
|
|
181
|
+
if (options.skip) return;
|
|
152
182
|
try {
|
|
153
183
|
const filepath = this.getActualFilePath(filename);
|
|
154
184
|
const screenshotOptions = {
|
|
155
185
|
path: filepath,
|
|
156
|
-
fullPage: options.fullPage
|
|
186
|
+
fullPage: options.fullPage,
|
|
157
187
|
type: "png",
|
|
158
188
|
timeout: 6e4,
|
|
159
189
|
mask: options.mask,
|
|
160
190
|
omitBackground: options.omitBackground,
|
|
161
191
|
scale: "css"
|
|
162
192
|
};
|
|
193
|
+
if (options.delay) await page.waitForTimeout(options.delay);
|
|
163
194
|
await page.screenshot(screenshotOptions);
|
|
164
|
-
console.log(`Screenshot saved: ${filepath}`);
|
|
165
|
-
return filepath;
|
|
166
|
-
} catch (error) {
|
|
167
|
-
console.error(`Error taking screenshot of ${page.url()}:`, error.message);
|
|
168
|
-
throw error;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
async takeElementScreenshot(page, selector, options = {}) {
|
|
172
|
-
if (!this.browser) throw new Error("Browser not initialized");
|
|
173
|
-
try {
|
|
174
|
-
await page.waitForSelector(selector, { timeout: 1e4 });
|
|
175
|
-
const element = await page.$(selector);
|
|
176
|
-
if (!element) throw new Error(`Element not found: ${selector}`);
|
|
177
|
-
const filename = options.filename || `${selector.replace(/[^a-zA-Z0-9]/g, "_")}.png`;
|
|
178
|
-
const filepath = this.getActualFilePath(filename);
|
|
179
|
-
const elementScreenshotOptions = {
|
|
180
|
-
path: filepath,
|
|
181
|
-
type: "png"
|
|
182
|
-
};
|
|
183
|
-
await element.screenshot(elementScreenshotOptions);
|
|
184
|
-
console.log(`Element screenshot saved: ${filepath}`);
|
|
185
195
|
return filepath;
|
|
186
196
|
} catch (error) {
|
|
187
|
-
|
|
197
|
+
this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
|
|
188
198
|
throw error;
|
|
189
|
-
} finally {
|
|
190
|
-
await page.close();
|
|
191
199
|
}
|
|
192
200
|
}
|
|
193
|
-
async takeScreenshotWithComparison(page, filename, referenceImage, options
|
|
201
|
+
async takeScreenshotWithComparison(page, filename, referenceImage, options) {
|
|
194
202
|
if (!this.browser) throw new Error("Browser not initialized");
|
|
195
203
|
try {
|
|
196
204
|
const filepath = this.getActualFilePath(filename);
|
|
197
205
|
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
|
198
206
|
const screenshotOptions = {
|
|
199
|
-
fullPage: options.fullPage
|
|
207
|
+
fullPage: options.fullPage,
|
|
200
208
|
type: "png",
|
|
201
209
|
timeout: 6e4,
|
|
202
210
|
mask: options.mask,
|
|
203
211
|
omitBackground: options.omitBackground,
|
|
204
212
|
scale: "css"
|
|
205
213
|
};
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
});
|
|
213
|
-
console.log(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${comparisonResult.passed ? "PASSED" : "FAILED"})`);
|
|
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);
|
|
217
|
+
this.logger.success(`Screenshot saved: ${filepath}`);
|
|
218
|
+
if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
|
|
219
|
+
else this.logger.error(`Screenshot failed visual comparison`);
|
|
214
220
|
let diffImagePath;
|
|
215
|
-
if (options.saveDiffImage && comparisonResult.diffBuffer && !
|
|
221
|
+
if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
|
|
216
222
|
const diffFilename = options.diffImageFilename || filename;
|
|
217
223
|
diffImagePath = this.getDiffFilePath(diffFilename);
|
|
218
224
|
fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
|
|
219
|
-
fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
|
|
225
|
+
fs.writeFileSync(diffImagePath, retryScreenshot.comparisonResult.diffBuffer);
|
|
226
|
+
this.logger.debug(`Diff image saved: ${diffImagePath}`);
|
|
220
227
|
}
|
|
221
228
|
return {
|
|
222
229
|
screenshotPath: filepath,
|
|
223
|
-
comparisonResult,
|
|
230
|
+
comparisonResult: retryScreenshot.comparisonResult,
|
|
224
231
|
diffImagePath
|
|
225
232
|
};
|
|
226
233
|
} catch (error) {
|
|
227
|
-
|
|
234
|
+
this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
|
|
228
235
|
throw error;
|
|
229
236
|
}
|
|
230
237
|
}
|
|
231
|
-
async
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
await this.goTo(page, url);
|
|
237
|
-
const filepath = await this.takeScreenshot(page, url, options);
|
|
238
|
-
results.push({
|
|
239
|
-
url,
|
|
240
|
-
success: true,
|
|
241
|
-
filepath
|
|
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)
|
|
242
243
|
});
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
error: error.message,
|
|
248
|
-
filepath: ""
|
|
244
|
+
if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
|
|
245
|
+
const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
|
|
246
|
+
...this.diff,
|
|
247
|
+
...options
|
|
249
248
|
});
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
name: "tablet"
|
|
263
|
-
},
|
|
264
|
-
{
|
|
265
|
-
width: 375,
|
|
266
|
-
height: 667,
|
|
267
|
-
name: "mobile"
|
|
268
|
-
}
|
|
269
|
-
], options = {}) {
|
|
270
|
-
if (!this.context) throw new Error("Browser not initialized");
|
|
271
|
-
const results = [];
|
|
272
|
-
for (const viewport of viewports) try {
|
|
273
|
-
const page = await this.context?.newPage();
|
|
274
|
-
await page.setViewportSize(viewport);
|
|
275
|
-
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
276
|
-
await page.waitForTimeout(2e3);
|
|
277
|
-
const filename = `${viewport.name}.png`;
|
|
278
|
-
const filepath = this.getActualFilePath(filename);
|
|
279
|
-
const responsiveScreenshotOptions = {
|
|
280
|
-
path: filepath,
|
|
281
|
-
fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
|
|
282
|
-
type: "png"
|
|
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
|
|
283
261
|
};
|
|
284
|
-
|
|
285
|
-
await page.close();
|
|
286
|
-
console.log(`Responsive screenshot saved: ${filepath}`);
|
|
287
|
-
results.push({
|
|
288
|
-
viewport: viewport.name,
|
|
289
|
-
success: true,
|
|
290
|
-
filepath
|
|
291
|
-
});
|
|
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)}%)`);
|
|
292
263
|
} catch (error) {
|
|
293
|
-
|
|
294
|
-
results.push({
|
|
295
|
-
viewport: viewport.name,
|
|
296
|
-
success: false,
|
|
297
|
-
error: error.message,
|
|
298
|
-
filepath: ""
|
|
299
|
-
});
|
|
264
|
+
this.logger.error(`Error taking screenshot after ${i + 1} retries:`, error.message);
|
|
300
265
|
}
|
|
301
|
-
return
|
|
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;
|
|
302
277
|
}
|
|
303
278
|
hasExpectedImage(filename) {
|
|
304
279
|
const expectedPath = this.getExpectedFilePath(filename);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","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,QAAO,UAAU,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,IAAI,IAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAGrD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;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"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;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AgB;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,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cappa/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Core Playwright screenshot functionality for Cappa",
|
|
5
5
|
"author": "tim-richter",
|
|
6
6
|
"license": "MIT",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"@blazediff/types": "^1.1.0",
|
|
23
23
|
"pixelmatch": "^6.0.0",
|
|
24
24
|
"playwright-core": "^1.55.0",
|
|
25
|
-
"pngjs": "^7.0.0"
|
|
25
|
+
"pngjs": "^7.0.0",
|
|
26
|
+
"@cappa/logger": "0.0.3"
|
|
26
27
|
},
|
|
27
28
|
"devDependencies": {
|
|
28
29
|
"@types/node": "22.13.10",
|
|
@@ -30,7 +31,6 @@
|
|
|
30
31
|
"@types/pngjs": "^6.0.4",
|
|
31
32
|
"@vitest/coverage-v8": "3.2.4",
|
|
32
33
|
"@vitest/ui": "3.2.4",
|
|
33
|
-
"consola": "3.4.2",
|
|
34
34
|
"tsdown": "0.14.1",
|
|
35
35
|
"typescript": "5.7.3",
|
|
36
36
|
"vitest": "3.2.4"
|
package/src/compare.test.ts
CHANGED
|
@@ -149,15 +149,19 @@ describe("compare", () => {
|
|
|
149
149
|
expect(result.passed).toBe(false);
|
|
150
150
|
});
|
|
151
151
|
|
|
152
|
-
it("should respect
|
|
152
|
+
it("should respect maxDiffPercentage parameter", async () => {
|
|
153
153
|
const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
|
|
154
154
|
const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
|
|
155
155
|
|
|
156
|
-
const result1 = await compareImages(redImage, blueImage, false, {
|
|
157
|
-
|
|
156
|
+
const result1 = await compareImages(redImage, blueImage, false, {
|
|
157
|
+
maxDiffPercentage: 50,
|
|
158
|
+
});
|
|
159
|
+
const result2 = await compareImages(redImage, blueImage, false, {
|
|
160
|
+
maxDiffPercentage: 100,
|
|
161
|
+
});
|
|
158
162
|
|
|
159
163
|
expect(result1.passed).toBe(false); // 100% > 50%
|
|
160
|
-
expect(result2.passed).toBe(true); // 100% <
|
|
164
|
+
expect(result2.passed).toBe(true); // 100% < 100%
|
|
161
165
|
});
|
|
162
166
|
|
|
163
167
|
it("should apply threshold option correctly", async () => {
|
|
@@ -238,8 +242,12 @@ describe("compare", () => {
|
|
|
238
242
|
const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
|
|
239
243
|
const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
|
|
240
244
|
|
|
241
|
-
const strictMatch = await imagesMatch(redImage, blueImage,
|
|
242
|
-
|
|
245
|
+
const strictMatch = await imagesMatch(redImage, blueImage, {
|
|
246
|
+
maxDiffPercentage: 50,
|
|
247
|
+
});
|
|
248
|
+
const lenientMatch = await imagesMatch(redImage, blueImage, {
|
|
249
|
+
maxDiffPercentage: 150,
|
|
250
|
+
});
|
|
243
251
|
|
|
244
252
|
expect(strictMatch).toBe(false);
|
|
245
253
|
expect(lenientMatch).toBe(true);
|
|
@@ -258,10 +266,12 @@ describe("compare", () => {
|
|
|
258
266
|
const image1 = createSolidColorPNG(50, 50, [100, 100, 100, 255]);
|
|
259
267
|
const image2 = createSolidColorPNG(50, 50, [105, 105, 105, 255]);
|
|
260
268
|
|
|
261
|
-
const strictMatch = await imagesMatch(image1, image2,
|
|
269
|
+
const strictMatch = await imagesMatch(image1, image2, {
|
|
270
|
+
maxDiffPercentage: 50,
|
|
262
271
|
threshold: 0.01,
|
|
263
272
|
});
|
|
264
|
-
const lenientMatch = await imagesMatch(image1, image2,
|
|
273
|
+
const lenientMatch = await imagesMatch(image1, image2, {
|
|
274
|
+
maxDiffPercentage: 50,
|
|
265
275
|
threshold: 0.5,
|
|
266
276
|
});
|
|
267
277
|
|
|
@@ -349,7 +359,9 @@ describe("compare", () => {
|
|
|
349
359
|
it("should handle zero difference threshold", async () => {
|
|
350
360
|
const image = createSolidColorPNG(10, 10, [255, 0, 0, 255]);
|
|
351
361
|
|
|
352
|
-
const result = await compareImages(image, image, false, {
|
|
362
|
+
const result = await compareImages(image, image, false, {
|
|
363
|
+
maxDiffPercentage: 0,
|
|
364
|
+
});
|
|
353
365
|
|
|
354
366
|
expect(result.passed).toBe(true);
|
|
355
367
|
expect(result.percentDifference).toBe(0);
|
package/src/compare.ts
CHANGED
|
@@ -31,14 +31,13 @@ const compare = (
|
|
|
31
31
|
* @param image2 - Second image (file path or Buffer)
|
|
32
32
|
* @param withDiff - Whether to create a diff image
|
|
33
33
|
* @param options - Comparison options
|
|
34
|
-
* @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
|
|
35
34
|
* @returns Comparison result
|
|
36
35
|
*/
|
|
37
36
|
export async function compareImages(
|
|
38
37
|
image1: string | Buffer,
|
|
39
38
|
image2: string | Buffer,
|
|
40
39
|
withDiff: boolean = false,
|
|
41
|
-
options: DiffConfig,
|
|
40
|
+
options: DiffConfig = {},
|
|
42
41
|
): Promise<CompareResult> {
|
|
43
42
|
// Load images as PNG objects
|
|
44
43
|
const png1 = await loadPNG(image1);
|
|
@@ -46,10 +45,8 @@ export async function compareImages(
|
|
|
46
45
|
|
|
47
46
|
const { width, height } = png1;
|
|
48
47
|
|
|
49
|
-
// Create diff image
|
|
50
48
|
const diff = withDiff ? new PNG({ width, height }) : undefined;
|
|
51
49
|
|
|
52
|
-
// Compare images using pixelmatch
|
|
53
50
|
const numDiffPixels = compare(
|
|
54
51
|
png1.data,
|
|
55
52
|
png2.data,
|
|
@@ -61,7 +58,6 @@ export async function compareImages(
|
|
|
61
58
|
|
|
62
59
|
const totalPixels = width * height;
|
|
63
60
|
const percentDifference = (numDiffPixels / totalPixels) * 100;
|
|
64
|
-
const passed = percentDifference <= (options.maxDiffPercentage || 0);
|
|
65
61
|
|
|
66
62
|
// Convert diff image to buffer
|
|
67
63
|
const diffBuffer = diff ? PNG.sync.write(diff) : undefined;
|
|
@@ -71,7 +67,7 @@ export async function compareImages(
|
|
|
71
67
|
totalPixels,
|
|
72
68
|
percentDifference,
|
|
73
69
|
diffBuffer,
|
|
74
|
-
passed,
|
|
70
|
+
passed: isPassed(percentDifference, numDiffPixels, options),
|
|
75
71
|
};
|
|
76
72
|
}
|
|
77
73
|
|
|
@@ -104,15 +100,39 @@ export function saveDiffImage(result: CompareResult, outputPath: string): void {
|
|
|
104
100
|
* Quick comparison function that returns only pass/fail
|
|
105
101
|
* @param image1 - First image (file path or Buffer)
|
|
106
102
|
* @param image2 - Second image (file path or Buffer)
|
|
107
|
-
* @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
|
|
108
103
|
* @param options - Comparison options
|
|
109
|
-
* @returns Whether the images
|
|
104
|
+
* @returns Whether the images match
|
|
110
105
|
*/
|
|
111
106
|
export async function imagesMatch(
|
|
112
107
|
image1: string | Buffer,
|
|
113
108
|
image2: string | Buffer,
|
|
114
|
-
options: DiffConfig,
|
|
109
|
+
options: DiffConfig = {},
|
|
115
110
|
): Promise<boolean> {
|
|
116
111
|
const result = await compareImages(image1, image2, false, options);
|
|
112
|
+
|
|
117
113
|
return result.passed;
|
|
118
114
|
}
|
|
115
|
+
|
|
116
|
+
const isPassed = (
|
|
117
|
+
percentDifference: number,
|
|
118
|
+
numDiffPixels: number,
|
|
119
|
+
options: DiffConfig,
|
|
120
|
+
) => {
|
|
121
|
+
if (options.maxDiffPercentage && options.maxDiffPixels) {
|
|
122
|
+
return (
|
|
123
|
+
percentDifference <= options.maxDiffPercentage &&
|
|
124
|
+
numDiffPixels <= options.maxDiffPixels
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (options.maxDiffPercentage) {
|
|
129
|
+
return percentDifference <= options.maxDiffPercentage;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (options.maxDiffPixels) {
|
|
133
|
+
return numDiffPixels <= options.maxDiffPixels;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// fallback to 0 pixels
|
|
137
|
+
return numDiffPixels === 0;
|
|
138
|
+
};
|
package/src/config.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PossiblePromise, UserConfig } from "./types";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Type helper to make it easier to use
|
|
4
|
+
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
5
5
|
*/
|
|
6
6
|
export function defineConfig(
|
|
7
7
|
options:
|