@cappa/core 0.1.1 → 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/.turbo/turbo-build.log +12 -12
- package/CHANGELOG.md +8 -0
- package/dist/index.d.mts +44 -52
- package/dist/index.d.ts +44 -52
- package/dist/index.js +54 -115
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +53 -115
- 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 +61 -180
- package/src/types.ts +12 -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,11 @@ 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;
|
|
83
88
|
constructor(options) {
|
|
84
89
|
this.browserType = options.browserType || "chromium";
|
|
85
90
|
this.headless = options.headless !== false;
|
|
@@ -88,7 +93,6 @@ var ScreenshotTool = class {
|
|
|
88
93
|
height: 1080
|
|
89
94
|
};
|
|
90
95
|
this.outputDir = options.outputDir || "./screenshots";
|
|
91
|
-
this.fullPage = options.fullPage !== false;
|
|
92
96
|
this.diff = {
|
|
93
97
|
...defaultDiffConfig,
|
|
94
98
|
...options.diff
|
|
@@ -96,7 +100,11 @@ var ScreenshotTool = class {
|
|
|
96
100
|
this.actualDir = path.join(this.outputDir, "actual");
|
|
97
101
|
this.diffDir = path.join(this.outputDir, "diff");
|
|
98
102
|
this.expectedDir = path.join(this.outputDir, "expected");
|
|
103
|
+
this.logger = getLogger();
|
|
99
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Initialize playwright and page
|
|
107
|
+
*/
|
|
100
108
|
async init() {
|
|
101
109
|
this.createDirectories();
|
|
102
110
|
const browserClass = {
|
|
@@ -110,19 +118,29 @@ var ScreenshotTool = class {
|
|
|
110
118
|
this.context = await this.browser.newContext({
|
|
111
119
|
reducedMotion: "reduce",
|
|
112
120
|
deviceScaleFactor: 2,
|
|
113
|
-
userAgent: `${await defaultUserAgent} CappaStorybook
|
|
121
|
+
userAgent: `${await defaultUserAgent} CappaStorybook`,
|
|
122
|
+
viewport: this.viewport
|
|
114
123
|
});
|
|
115
124
|
this.page = await this.context?.newPage();
|
|
116
|
-
this.page?.setViewportSize(this.viewport);
|
|
117
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* Closes browser
|
|
128
|
+
* If not closed, the process will not exit
|
|
129
|
+
*/
|
|
118
130
|
async close() {
|
|
119
131
|
if (this.context) await this.context.close();
|
|
120
132
|
if (this.browser) await this.browser.close();
|
|
121
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* Navigates to a URL with "domcontentloaded" waitUntil
|
|
136
|
+
*/
|
|
122
137
|
async goTo(page, url) {
|
|
123
138
|
if (!this.context) throw new Error("Browser not initialized");
|
|
124
139
|
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
125
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* Creates directories for screenshots and other files
|
|
143
|
+
*/
|
|
126
144
|
createDirectories() {
|
|
127
145
|
const directories = [
|
|
128
146
|
this.outputDir,
|
|
@@ -132,62 +150,51 @@ var ScreenshotTool = class {
|
|
|
132
150
|
];
|
|
133
151
|
for (const dir of directories) if (!fs.existsSync(dir)) {
|
|
134
152
|
fs.mkdirSync(dir, { recursive: true });
|
|
135
|
-
|
|
153
|
+
this.logger.debug(`Initialized directory: ${dir}`);
|
|
136
154
|
}
|
|
137
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Gets the path to the actual screenshot file
|
|
158
|
+
*/
|
|
138
159
|
getActualFilePath(filename) {
|
|
139
160
|
return path.join(this.actualDir, filename);
|
|
140
161
|
}
|
|
162
|
+
/**
|
|
163
|
+
* Gets the path to the diff screenshot file
|
|
164
|
+
*/
|
|
141
165
|
getDiffFilePath(filename) {
|
|
142
166
|
return path.join(this.diffDir, filename);
|
|
143
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* Gets the path to the expected screenshot file
|
|
170
|
+
*/
|
|
144
171
|
getExpectedFilePath(filename) {
|
|
145
172
|
return path.join(this.expectedDir, filename);
|
|
146
173
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
async takeScreenshot(page, filename, options
|
|
174
|
+
/**
|
|
175
|
+
* Takes a screenshot of the page
|
|
176
|
+
*/
|
|
177
|
+
async takeScreenshot(page, filename, options) {
|
|
151
178
|
if (!this.browser) throw new Error("Browser not initialized");
|
|
179
|
+
if (options.skip) return;
|
|
152
180
|
try {
|
|
153
181
|
const filepath = this.getActualFilePath(filename);
|
|
154
182
|
const screenshotOptions = {
|
|
155
183
|
path: filepath,
|
|
156
|
-
fullPage: options.fullPage
|
|
184
|
+
fullPage: options.fullPage,
|
|
157
185
|
type: "png",
|
|
158
186
|
timeout: 6e4,
|
|
159
187
|
mask: options.mask,
|
|
160
188
|
omitBackground: options.omitBackground,
|
|
161
189
|
scale: "css"
|
|
162
190
|
};
|
|
191
|
+
if (options.delay) await page.waitForTimeout(options.delay);
|
|
163
192
|
await page.screenshot(screenshotOptions);
|
|
164
|
-
|
|
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}`);
|
|
193
|
+
this.logger.success(`Screenshot saved: ${filepath}`);
|
|
185
194
|
return filepath;
|
|
186
195
|
} catch (error) {
|
|
187
|
-
|
|
196
|
+
this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
|
|
188
197
|
throw error;
|
|
189
|
-
} finally {
|
|
190
|
-
await page.close();
|
|
191
198
|
}
|
|
192
199
|
}
|
|
193
200
|
async takeScreenshotWithComparison(page, filename, referenceImage, options = {}) {
|
|
@@ -196,7 +203,7 @@ var ScreenshotTool = class {
|
|
|
196
203
|
const filepath = this.getActualFilePath(filename);
|
|
197
204
|
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
|
198
205
|
const screenshotOptions = {
|
|
199
|
-
fullPage: options.fullPage
|
|
206
|
+
fullPage: options.fullPage,
|
|
200
207
|
type: "png",
|
|
201
208
|
timeout: 6e4,
|
|
202
209
|
mask: options.mask,
|
|
@@ -205,18 +212,21 @@ var ScreenshotTool = class {
|
|
|
205
212
|
};
|
|
206
213
|
const screenshotBuffer = await page.screenshot(screenshotOptions);
|
|
207
214
|
fs.writeFileSync(filepath, screenshotBuffer);
|
|
208
|
-
|
|
215
|
+
this.logger.success(`Screenshot saved: ${filepath}`);
|
|
209
216
|
const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
|
|
210
217
|
...this.diff,
|
|
211
218
|
...options.compareOptions
|
|
212
219
|
});
|
|
213
|
-
|
|
220
|
+
this.logger.debug(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
|
|
221
|
+
if (comparisonResult.passed) this.logger.success(`Screenshot passed visual comparison`);
|
|
222
|
+
else this.logger.error(`Screenshot failed visual comparison`);
|
|
214
223
|
let diffImagePath;
|
|
215
224
|
if (options.saveDiffImage && comparisonResult.diffBuffer && !comparisonResult.passed) {
|
|
216
225
|
const diffFilename = options.diffImageFilename || filename;
|
|
217
226
|
diffImagePath = this.getDiffFilePath(diffFilename);
|
|
218
227
|
fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
|
|
219
228
|
fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
|
|
229
|
+
this.logger.debug(`Diff image saved: ${diffImagePath}`);
|
|
220
230
|
}
|
|
221
231
|
return {
|
|
222
232
|
screenshotPath: filepath,
|
|
@@ -224,82 +234,10 @@ var ScreenshotTool = class {
|
|
|
224
234
|
diffImagePath
|
|
225
235
|
};
|
|
226
236
|
} catch (error) {
|
|
227
|
-
|
|
237
|
+
this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
|
|
228
238
|
throw error;
|
|
229
239
|
}
|
|
230
240
|
}
|
|
231
|
-
async batchScreenshots(urls, options = {}) {
|
|
232
|
-
const results = [];
|
|
233
|
-
for (const url of urls) try {
|
|
234
|
-
const page = this.page;
|
|
235
|
-
if (!page) throw new Error("Page not initialized");
|
|
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
|
|
242
|
-
});
|
|
243
|
-
} catch (error) {
|
|
244
|
-
results.push({
|
|
245
|
-
url,
|
|
246
|
-
success: false,
|
|
247
|
-
error: error.message,
|
|
248
|
-
filepath: ""
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
return results;
|
|
252
|
-
}
|
|
253
|
-
async takeResponsiveScreenshots(url, viewports = [
|
|
254
|
-
{
|
|
255
|
-
width: 1920,
|
|
256
|
-
height: 1080,
|
|
257
|
-
name: "desktop"
|
|
258
|
-
},
|
|
259
|
-
{
|
|
260
|
-
width: 768,
|
|
261
|
-
height: 1024,
|
|
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"
|
|
283
|
-
};
|
|
284
|
-
await page.screenshot(responsiveScreenshotOptions);
|
|
285
|
-
await page.close();
|
|
286
|
-
console.log(`Responsive screenshot saved: ${filepath}`);
|
|
287
|
-
results.push({
|
|
288
|
-
viewport: viewport.name,
|
|
289
|
-
success: true,
|
|
290
|
-
filepath
|
|
291
|
-
});
|
|
292
|
-
} catch (error) {
|
|
293
|
-
console.error(`Error taking responsive screenshot for ${viewport.name}:`, error.message);
|
|
294
|
-
results.push({
|
|
295
|
-
viewport: viewport.name,
|
|
296
|
-
success: false,
|
|
297
|
-
error: error.message,
|
|
298
|
-
filepath: ""
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
return results;
|
|
302
|
-
}
|
|
303
241
|
hasExpectedImage(filename) {
|
|
304
242
|
const expectedPath = this.getExpectedFilePath(filename);
|
|
305
243
|
return fs.existsSync(expectedPath);
|
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;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C,GAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,6BAA6B,eAAe;AAE9D,SAAO,GAAG,aAAa,aAAa;;;AAIxC,yBAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.context.close();\n }\n if (this.browser) {\n await this.browser.close();\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n // Comparison options\n compareOptions?: CompareOptions;\n maxDifferencePercent?: number;\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n // Get screenshot as buffer for comparison\n const screenshotBuffer = await page.screenshot(screenshotOptions);\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, screenshotBuffer);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n // Perform comparison\n const comparisonResult = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options.compareOptions },\n );\n\n this.logger.debug(\n `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\n );\n\n if (comparisonResult.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n comparisonResult.diffBuffer &&\n !comparisonResult.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;ACMT,MAAM,WACJ,QACA,QACA,MACA,OACA,QACA,YACG;AACH,QAAO,UAAU,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;AAWhE,eAAsB,cACpB,QACA,QACA,WAAoB,OACpB,UAAsB,EAAE,EACA;CAExB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;CAE1B,MAAM,OAAO,WAAW,IAAI,IAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAErD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;CAC5B,MAAM,oBAAqB,gBAAgB,cAAe;CAG1D,MAAM,aAAa,OAAO,IAAI,KAAK,MAAM,KAAK,GAAG;AAEjD,QAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,mBAAmB,eAAe,QAAQ;EAC5D;;;;;AAMH,eAAe,QAAQ,QAAuC;AAC5D,KAAI,OAAO,SAAS,OAAO,CACzB,QAAO,IAAI,KAAK,KAAK,OAAO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,SAAK,OAAO,MAAM,qBAAqB,gBAAgB;;AAGzD,UAAO;IACL,gBAAgB;IAChB;IACA;IACD;WACM,OAAO;AACd,QAAK,OAAO,MACV,8CAA8C,KAAK,KAAK,CAAC,IACxD,MAAgB,QAClB;AACD,SAAM;;;CAKV,iBAAiB,UAA2B;EAC1C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,SAAO,GAAG,WAAW,aAAa;;CAIpC,uBAAuB,UAA0B;EAC/C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,MAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,6BAA6B,eAAe;AAE9D,SAAO,GAAG,aAAa,aAAa;;;AAIxC,yBAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cappa/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
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.2"
|
|
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:
|
package/src/index.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import { defineConfig } from "./config";
|
|
2
2
|
import type { Plugin, PluginDef, PluginFunction } from "./plugin";
|
|
3
3
|
import ScreenshotTool from "./screenshot";
|
|
4
|
-
import type {
|
|
5
|
-
Exposed,
|
|
6
|
-
Screenshot,
|
|
7
|
-
ScreenshotOptions,
|
|
8
|
-
UserConfig,
|
|
9
|
-
} from "./types";
|
|
4
|
+
import type { Screenshot, ScreenshotOptions, UserConfig } from "./types";
|
|
10
5
|
|
|
11
6
|
export {
|
|
12
7
|
ScreenshotTool,
|
|
@@ -16,6 +11,5 @@ export {
|
|
|
16
11
|
type PluginDef,
|
|
17
12
|
type UserConfig,
|
|
18
13
|
type ScreenshotOptions,
|
|
19
|
-
type Exposed,
|
|
20
14
|
type Screenshot,
|
|
21
15
|
};
|
package/src/plugin.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import type { ConsolaInstance } from "consola";
|
|
2
1
|
import type ScreenshotTool from "./screenshot";
|
|
3
2
|
|
|
4
3
|
/**
|
|
5
4
|
* Plugin function type definition
|
|
6
5
|
*/
|
|
7
|
-
export type PluginFunction = (
|
|
8
|
-
screenshotTool: ScreenshotTool,
|
|
9
|
-
logger: ConsolaInstance,
|
|
10
|
-
) => Promise<any[]>;
|
|
6
|
+
export type PluginFunction = (screenshotTool: ScreenshotTool) => Promise<any[]>;
|
|
11
7
|
|
|
12
8
|
/**
|
|
13
9
|
* Plugin definition interface
|
|
@@ -15,9 +11,7 @@ export type PluginFunction = (
|
|
|
15
11
|
export type PluginDef = {
|
|
16
12
|
name: string;
|
|
17
13
|
description: string;
|
|
18
|
-
version: string;
|
|
19
14
|
execute: PluginFunction;
|
|
20
|
-
validateOptions?: (options: any) => boolean;
|
|
21
15
|
};
|
|
22
16
|
|
|
23
17
|
/**
|