@cappa/core 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +13 -19
- package/.turbo/turbo-test.log +53 -0
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +20 -0
- package/dist/index.d.mts +190 -38
- package/dist/index.d.ts +190 -38
- package/dist/index.js +430 -88
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +430 -89
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -12
- package/src/compare.test.ts +9 -4
- package/src/compare.ts +76 -23
- package/src/filesystem.test.ts +83 -0
- package/src/filesystem.ts +202 -0
- package/src/index.ts +23 -2
- package/src/plugin.ts +26 -3
- package/src/screenshot.test.ts +40 -0
- package/src/screenshot.ts +425 -119
- package/src/types.ts +23 -1
package/dist/index.mjs
CHANGED
|
@@ -13,6 +13,167 @@ function defineConfig(options) {
|
|
|
13
13
|
return options;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/filesystem.ts
|
|
18
|
+
/**
|
|
19
|
+
* Class for interacting with the local file system to store the screenshots.
|
|
20
|
+
*/
|
|
21
|
+
var ScreenshotFileSystem = class {
|
|
22
|
+
actualDir;
|
|
23
|
+
expectedDir;
|
|
24
|
+
diffDir;
|
|
25
|
+
constructor(outputDir) {
|
|
26
|
+
this.actualDir = path.resolve(outputDir, "actual");
|
|
27
|
+
this.expectedDir = path.resolve(outputDir, "expected");
|
|
28
|
+
this.diffDir = path.resolve(outputDir, "diff");
|
|
29
|
+
this.ensureParentDir(this.actualDir);
|
|
30
|
+
this.ensureParentDir(this.expectedDir);
|
|
31
|
+
this.ensureParentDir(this.diffDir);
|
|
32
|
+
}
|
|
33
|
+
clearActual() {
|
|
34
|
+
this.removeDir(this.actualDir);
|
|
35
|
+
}
|
|
36
|
+
clearDiff() {
|
|
37
|
+
this.removeDir(this.diffDir);
|
|
38
|
+
}
|
|
39
|
+
clearActualAndDiff() {
|
|
40
|
+
this.clearActual();
|
|
41
|
+
this.clearDiff();
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Approve a screenshot based on its actual file path.
|
|
45
|
+
* @param actualFilePath - The path to the actual screenshot file.
|
|
46
|
+
* @returns The paths to the actual, expected, and diff screenshot files.
|
|
47
|
+
*/
|
|
48
|
+
approveFromActualPath(actualFilePath) {
|
|
49
|
+
const actualAbsolute = this.resolveActualPath(actualFilePath);
|
|
50
|
+
const relativePath = path.relative(this.actualDir, actualAbsolute);
|
|
51
|
+
if (relativePath.startsWith("..")) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
|
|
52
|
+
return this.approveRelative(relativePath);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Approve a screenshot based on its name.
|
|
56
|
+
* @param name - The name of the screenshot. Can include '.png' extension.
|
|
57
|
+
* @returns The paths to the actual, expected, and diff screenshot files.
|
|
58
|
+
*/
|
|
59
|
+
approveByName(name) {
|
|
60
|
+
const relativeWithExtension = name.endsWith(".png") ? name : `${name}.png`;
|
|
61
|
+
return this.approveRelative(relativeWithExtension);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Approve a screenshot based on a relative path.
|
|
65
|
+
* @param relativePath - The relative path to the screenshot.
|
|
66
|
+
* @returns The paths to the actual, expected, and diff screenshot files.
|
|
67
|
+
*/
|
|
68
|
+
approveRelative(relativePath) {
|
|
69
|
+
const actualPath = path.resolve(this.actualDir, relativePath);
|
|
70
|
+
const expectedPath = path.resolve(this.expectedDir, relativePath);
|
|
71
|
+
const diffPath = path.resolve(this.diffDir, relativePath);
|
|
72
|
+
this.ensureParentDir(expectedPath);
|
|
73
|
+
fs.copyFileSync(actualPath, expectedPath);
|
|
74
|
+
if (fs.existsSync(diffPath)) fs.unlinkSync(diffPath);
|
|
75
|
+
return {
|
|
76
|
+
actualPath,
|
|
77
|
+
expectedPath,
|
|
78
|
+
diffPath
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Ensure the parent directory of a file exists. If not, it creates it.
|
|
83
|
+
* @param filePath - The path to the file.
|
|
84
|
+
*/
|
|
85
|
+
ensureParentDir(filePath) {
|
|
86
|
+
const dir = path.dirname(filePath);
|
|
87
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Remove a directory and all its contents.
|
|
91
|
+
* @param dir - The path to the directory.
|
|
92
|
+
*/
|
|
93
|
+
removeDir(dir) {
|
|
94
|
+
if (fs.existsSync(dir)) fs.rmSync(dir, {
|
|
95
|
+
recursive: true,
|
|
96
|
+
force: true
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Get the actual directory path
|
|
101
|
+
*/
|
|
102
|
+
getActualDir() {
|
|
103
|
+
return this.actualDir;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Get the expected directory path
|
|
107
|
+
*/
|
|
108
|
+
getExpectedDir() {
|
|
109
|
+
return this.expectedDir;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Get the diff directory path
|
|
113
|
+
*/
|
|
114
|
+
getDiffDir() {
|
|
115
|
+
return this.diffDir;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Get the path to an actual screenshot file
|
|
119
|
+
*/
|
|
120
|
+
getActualFilePath(filename) {
|
|
121
|
+
return path.resolve(this.actualDir, filename);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Get the path to an expected screenshot file
|
|
125
|
+
*/
|
|
126
|
+
getExpectedFilePath(filename) {
|
|
127
|
+
return path.resolve(this.expectedDir, filename);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Get the path to a diff screenshot file
|
|
131
|
+
*/
|
|
132
|
+
getDiffFilePath(filename) {
|
|
133
|
+
return path.resolve(this.diffDir, filename);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Write a file to the actual directory
|
|
137
|
+
*/
|
|
138
|
+
writeActualFile(filename, data) {
|
|
139
|
+
const filepath = this.getActualFilePath(filename);
|
|
140
|
+
this.ensureParentDir(filepath);
|
|
141
|
+
fs.writeFileSync(filepath, data);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Write a file to the diff directory
|
|
145
|
+
*/
|
|
146
|
+
writeDiffFile(filename, data) {
|
|
147
|
+
const filepath = this.getDiffFilePath(filename);
|
|
148
|
+
this.ensureParentDir(filepath);
|
|
149
|
+
fs.writeFileSync(filepath, data);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Check if an expected file exists
|
|
153
|
+
*/
|
|
154
|
+
hasExpectedFile(filename) {
|
|
155
|
+
const expectedPath = this.getExpectedFilePath(filename);
|
|
156
|
+
return fs.existsSync(expectedPath);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Read an expected file
|
|
160
|
+
*/
|
|
161
|
+
readExpectedFile(filename) {
|
|
162
|
+
const expectedPath = this.getExpectedFilePath(filename);
|
|
163
|
+
if (!fs.existsSync(expectedPath)) throw new Error(`Expected image not found: ${expectedPath}`);
|
|
164
|
+
return fs.readFileSync(expectedPath);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Resolve the actual path of a screenshot file.
|
|
168
|
+
* @param filePath - The path to the screenshot file.
|
|
169
|
+
* @returns The actual path of the screenshot file.
|
|
170
|
+
*/
|
|
171
|
+
resolveActualPath(filePath) {
|
|
172
|
+
if (path.isAbsolute(filePath)) return filePath;
|
|
173
|
+
return path.resolve(this.actualDir, filePath);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
16
177
|
//#endregion
|
|
17
178
|
//#region src/compare.ts
|
|
18
179
|
const compare = (image1, image2, diff, width, height, options) => {
|
|
@@ -30,21 +191,40 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
|
30
191
|
const png1 = await loadPNG(image1);
|
|
31
192
|
const png2 = await loadPNG(image2);
|
|
32
193
|
const { width, height } = png1;
|
|
194
|
+
if (width !== png2.width || height !== png2.height) return {
|
|
195
|
+
numDiffPixels: 0,
|
|
196
|
+
totalPixels: 0,
|
|
197
|
+
percentDifference: 0,
|
|
198
|
+
passed: false,
|
|
199
|
+
differentSizes: true
|
|
200
|
+
};
|
|
33
201
|
const diff = withDiff ? new PNG({
|
|
34
202
|
width,
|
|
35
203
|
height
|
|
36
204
|
}) : void 0;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
205
|
+
try {
|
|
206
|
+
const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
|
|
207
|
+
const totalPixels = width * height;
|
|
208
|
+
const percentDifference = numDiffPixels / totalPixels * 100;
|
|
209
|
+
return {
|
|
210
|
+
numDiffPixels,
|
|
211
|
+
totalPixels,
|
|
212
|
+
percentDifference,
|
|
213
|
+
diffBuffer: diff ? PNG.sync.write(diff) : void 0,
|
|
214
|
+
passed: isPassed(percentDifference, numDiffPixels, options),
|
|
215
|
+
differentSizes: false
|
|
216
|
+
};
|
|
217
|
+
} catch (error) {
|
|
218
|
+
getLogger().error(error.message || "Unknown error");
|
|
219
|
+
return {
|
|
220
|
+
numDiffPixels: 0,
|
|
221
|
+
totalPixels: 0,
|
|
222
|
+
percentDifference: 0,
|
|
223
|
+
passed: false,
|
|
224
|
+
differentSizes: false,
|
|
225
|
+
error: error.message || "Unknown error"
|
|
226
|
+
};
|
|
227
|
+
}
|
|
48
228
|
}
|
|
49
229
|
/**
|
|
50
230
|
* Load a PNG image from file path or Buffer
|
|
@@ -56,12 +236,37 @@ async function loadPNG(source) {
|
|
|
56
236
|
return PNG.sync.read(buffer);
|
|
57
237
|
}
|
|
58
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Check if the comparison passed based on the options
|
|
241
|
+
* @param percentDifference - Percentage difference between the images
|
|
242
|
+
* @param numDiffPixels - Number of different pixels
|
|
243
|
+
* @param options - Comparison options
|
|
244
|
+
* @returns Whether the comparison passed
|
|
245
|
+
*/
|
|
59
246
|
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
60
247
|
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
61
248
|
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
62
249
|
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
63
250
|
return numDiffPixels === 0;
|
|
64
251
|
};
|
|
252
|
+
/**
|
|
253
|
+
* Create different size png image with all pixels red
|
|
254
|
+
* @returns
|
|
255
|
+
*/
|
|
256
|
+
function createDiffSizePngImage(width, height) {
|
|
257
|
+
const png = new PNG({
|
|
258
|
+
width,
|
|
259
|
+
height
|
|
260
|
+
});
|
|
261
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
262
|
+
const idx = width * y + x << 2;
|
|
263
|
+
png.data[idx] = 255;
|
|
264
|
+
png.data[idx + 1] = 0;
|
|
265
|
+
png.data[idx + 2] = 0;
|
|
266
|
+
png.data[idx + 3] = 255;
|
|
267
|
+
}
|
|
268
|
+
return PNG.sync.write(png);
|
|
269
|
+
}
|
|
65
270
|
|
|
66
271
|
//#endregion
|
|
67
272
|
//#region src/screenshot.ts
|
|
@@ -77,14 +282,16 @@ var ScreenshotTool = class {
|
|
|
77
282
|
headless;
|
|
78
283
|
viewport;
|
|
79
284
|
outputDir;
|
|
80
|
-
actualDir;
|
|
81
|
-
diffDir;
|
|
82
|
-
expectedDir;
|
|
83
285
|
browser = null;
|
|
84
286
|
context = null;
|
|
85
287
|
page = null;
|
|
288
|
+
concurrency;
|
|
289
|
+
contexts = [];
|
|
290
|
+
pages = [];
|
|
86
291
|
diff;
|
|
87
292
|
logger;
|
|
293
|
+
retries;
|
|
294
|
+
filesystem;
|
|
88
295
|
constructor(options) {
|
|
89
296
|
this.browserType = options.browserType || "chromium";
|
|
90
297
|
this.headless = options.headless !== false;
|
|
@@ -97,16 +304,15 @@ var ScreenshotTool = class {
|
|
|
97
304
|
...defaultDiffConfig,
|
|
98
305
|
...options.diff
|
|
99
306
|
};
|
|
100
|
-
this.
|
|
101
|
-
this.diffDir = path.join(this.outputDir, "diff");
|
|
102
|
-
this.expectedDir = path.join(this.outputDir, "expected");
|
|
307
|
+
this.concurrency = Math.max(1, options.concurrency || 1);
|
|
103
308
|
this.logger = getLogger();
|
|
309
|
+
this.retries = options.retries || 2;
|
|
310
|
+
this.filesystem = new ScreenshotFileSystem(this.outputDir);
|
|
104
311
|
}
|
|
105
312
|
/**
|
|
106
313
|
* Initialize playwright and page
|
|
107
314
|
*/
|
|
108
315
|
async init() {
|
|
109
|
-
this.createDirectories();
|
|
110
316
|
const browserClass = {
|
|
111
317
|
chromium,
|
|
112
318
|
firefox,
|
|
@@ -115,20 +321,28 @@ var ScreenshotTool = class {
|
|
|
115
321
|
if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
|
|
116
322
|
this.browser = await browserClass.launch({ headless: this.headless });
|
|
117
323
|
const defaultUserAgent = (await this.browser.newContext()).newPage().then((page) => page.evaluate(() => navigator.userAgent));
|
|
118
|
-
this.
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
324
|
+
this.contexts = [];
|
|
325
|
+
this.pages = [];
|
|
326
|
+
for (let i = 0; i < this.concurrency; i++) {
|
|
327
|
+
const context = await this.browser.newContext({
|
|
328
|
+
reducedMotion: "reduce",
|
|
329
|
+
deviceScaleFactor: 2,
|
|
330
|
+
userAgent: `${await defaultUserAgent} CappaStorybook`,
|
|
331
|
+
viewport: this.viewport
|
|
332
|
+
});
|
|
333
|
+
const page = await context.newPage();
|
|
334
|
+
this.contexts.push(context);
|
|
335
|
+
this.pages.push(page);
|
|
336
|
+
}
|
|
337
|
+
this.context = this.contexts[0] ?? null;
|
|
338
|
+
this.page = this.pages[0] ?? null;
|
|
125
339
|
}
|
|
126
340
|
/**
|
|
127
341
|
* Closes browser
|
|
128
342
|
* If not closed, the process will not exit
|
|
129
343
|
*/
|
|
130
344
|
async close() {
|
|
131
|
-
|
|
345
|
+
for (const context of this.contexts) await context.close();
|
|
132
346
|
if (this.browser) await this.browser.close();
|
|
133
347
|
}
|
|
134
348
|
/**
|
|
@@ -139,46 +353,13 @@ var ScreenshotTool = class {
|
|
|
139
353
|
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
140
354
|
}
|
|
141
355
|
/**
|
|
142
|
-
* Creates directories for screenshots and other files
|
|
143
|
-
*/
|
|
144
|
-
createDirectories() {
|
|
145
|
-
const directories = [
|
|
146
|
-
this.outputDir,
|
|
147
|
-
this.actualDir,
|
|
148
|
-
this.diffDir,
|
|
149
|
-
this.expectedDir
|
|
150
|
-
];
|
|
151
|
-
for (const dir of directories) if (!fs.existsSync(dir)) {
|
|
152
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
153
|
-
this.logger.debug(`Initialized directory: ${dir}`);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Gets the path to the actual screenshot file
|
|
158
|
-
*/
|
|
159
|
-
getActualFilePath(filename) {
|
|
160
|
-
return path.join(this.actualDir, filename);
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Gets the path to the diff screenshot file
|
|
164
|
-
*/
|
|
165
|
-
getDiffFilePath(filename) {
|
|
166
|
-
return path.join(this.diffDir, filename);
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Gets the path to the expected screenshot file
|
|
170
|
-
*/
|
|
171
|
-
getExpectedFilePath(filename) {
|
|
172
|
-
return path.join(this.expectedDir, filename);
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
356
|
* Takes a screenshot of the page
|
|
176
357
|
*/
|
|
177
358
|
async takeScreenshot(page, filename, options) {
|
|
178
359
|
if (!this.browser) throw new Error("Browser not initialized");
|
|
179
360
|
if (options.skip) return;
|
|
180
361
|
try {
|
|
181
|
-
const filepath = this.getActualFilePath(filename);
|
|
362
|
+
const filepath = this.filesystem.getActualFilePath(filename);
|
|
182
363
|
const screenshotOptions = {
|
|
183
364
|
path: filepath,
|
|
184
365
|
fullPage: options.fullPage,
|
|
@@ -186,51 +367,96 @@ var ScreenshotTool = class {
|
|
|
186
367
|
timeout: 6e4,
|
|
187
368
|
mask: options.mask,
|
|
188
369
|
omitBackground: options.omitBackground,
|
|
189
|
-
scale: "css"
|
|
370
|
+
scale: "css",
|
|
371
|
+
animations: "disabled",
|
|
372
|
+
caret: "hide"
|
|
190
373
|
};
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
374
|
+
await this.withViewport(page, options.viewport, async () => {
|
|
375
|
+
if (options.delay) await page.waitForTimeout(options.delay);
|
|
376
|
+
await page.screenshot(screenshotOptions);
|
|
377
|
+
});
|
|
194
378
|
return filepath;
|
|
195
379
|
} catch (error) {
|
|
196
380
|
this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
|
|
197
381
|
throw error;
|
|
198
382
|
}
|
|
199
383
|
}
|
|
200
|
-
|
|
384
|
+
/**
|
|
385
|
+
* Sets the viewport size and executes the action, ensuring the original viewport is restored
|
|
386
|
+
* even if the action throws an error.
|
|
387
|
+
*/
|
|
388
|
+
async withViewport(page, viewport, action) {
|
|
389
|
+
if (!viewport) return action();
|
|
390
|
+
const previousViewport = page.viewportSize();
|
|
391
|
+
if (previousViewport && previousViewport.width === viewport.width && previousViewport.height === viewport.height) return action();
|
|
392
|
+
await page.setViewportSize(viewport);
|
|
393
|
+
try {
|
|
394
|
+
return await action();
|
|
395
|
+
} finally {
|
|
396
|
+
if (previousViewport) await page.setViewportSize(previousViewport);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Takes a screenshot and returns the buffer (for comparison purposes)
|
|
401
|
+
*/
|
|
402
|
+
async takeScreenshotBuffer(page, options) {
|
|
201
403
|
if (!this.browser) throw new Error("Browser not initialized");
|
|
404
|
+
if (options.skip) throw new Error("Screenshot skipped");
|
|
202
405
|
try {
|
|
203
|
-
const filepath = this.getActualFilePath(filename);
|
|
204
|
-
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
|
205
406
|
const screenshotOptions = {
|
|
206
407
|
fullPage: options.fullPage,
|
|
207
408
|
type: "png",
|
|
208
409
|
timeout: 6e4,
|
|
209
410
|
mask: options.mask,
|
|
210
411
|
omitBackground: options.omitBackground,
|
|
211
|
-
scale: "css"
|
|
412
|
+
scale: "css",
|
|
413
|
+
animations: "disabled",
|
|
414
|
+
caret: "hide"
|
|
212
415
|
};
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
|
|
217
|
-
...this.diff,
|
|
218
|
-
...options.compareOptions
|
|
416
|
+
return await this.withViewport(page, options.viewport, async () => {
|
|
417
|
+
if (options.delay) await page.waitForTimeout(options.delay);
|
|
418
|
+
return page.screenshot(screenshotOptions);
|
|
219
419
|
});
|
|
220
|
-
|
|
221
|
-
|
|
420
|
+
} catch (error) {
|
|
421
|
+
this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async takeScreenshotWithComparison(page, filename, referenceImage, options) {
|
|
426
|
+
if (!this.browser) throw new Error("Browser not initialized");
|
|
427
|
+
try {
|
|
428
|
+
const filepath = this.filesystem.getActualFilePath(filename);
|
|
429
|
+
const screenshotSettings = {
|
|
430
|
+
fullPage: options.fullPage,
|
|
431
|
+
mask: options.mask,
|
|
432
|
+
omitBackground: options.omitBackground,
|
|
433
|
+
delay: options.delay,
|
|
434
|
+
viewport: options.viewport
|
|
435
|
+
};
|
|
436
|
+
const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings);
|
|
437
|
+
if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
|
|
438
|
+
this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
|
|
439
|
+
this.logger.success(`Screenshot saved: ${filepath}`);
|
|
440
|
+
if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
|
|
222
441
|
else this.logger.error(`Screenshot failed visual comparison`);
|
|
223
442
|
let diffImagePath;
|
|
224
|
-
if (options.saveDiffImage && comparisonResult.diffBuffer && !
|
|
443
|
+
if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
|
|
225
444
|
const diffFilename = options.diffImageFilename || filename;
|
|
226
|
-
diffImagePath = this.getDiffFilePath(diffFilename);
|
|
227
|
-
|
|
228
|
-
fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
|
|
445
|
+
diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
|
|
446
|
+
this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
|
|
229
447
|
this.logger.debug(`Diff image saved: ${diffImagePath}`);
|
|
230
448
|
}
|
|
449
|
+
if (retryScreenshot.comparisonResult.differentSizes) {
|
|
450
|
+
this.logger.warn(`Screenshot has different sizes than reference image`);
|
|
451
|
+
const diffFilename = options.diffImageFilename || filename;
|
|
452
|
+
diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
|
|
453
|
+
const diffBuffer = createDiffSizePngImage(200, 200);
|
|
454
|
+
this.filesystem.writeDiffFile(diffFilename, diffBuffer);
|
|
455
|
+
this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
|
|
456
|
+
}
|
|
231
457
|
return {
|
|
232
458
|
screenshotPath: filepath,
|
|
233
|
-
comparisonResult,
|
|
459
|
+
comparisonResult: retryScreenshot.comparisonResult,
|
|
234
460
|
diffImagePath
|
|
235
461
|
};
|
|
236
462
|
} catch (error) {
|
|
@@ -238,18 +464,133 @@ var ScreenshotTool = class {
|
|
|
238
464
|
throw error;
|
|
239
465
|
}
|
|
240
466
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
467
|
+
async retryScreenshot(page, referenceImage, options) {
|
|
468
|
+
for (let i = 0; i < this.retries; i++) try {
|
|
469
|
+
const screenshotBuffer = await this.takeScreenshotBuffer(page, {
|
|
470
|
+
...options,
|
|
471
|
+
delay: this.getIncBackoffDelay(i, options.delay || 0)
|
|
472
|
+
});
|
|
473
|
+
if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
|
|
474
|
+
const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, this.diff);
|
|
475
|
+
if (comparisonResult.differentSizes) return {
|
|
476
|
+
screenshotPath: screenshotBuffer,
|
|
477
|
+
comparisonResult,
|
|
478
|
+
passed: false
|
|
479
|
+
};
|
|
480
|
+
if (i === this.retries - 1 && !comparisonResult.passed) {
|
|
481
|
+
this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
|
|
482
|
+
return {
|
|
483
|
+
screenshotPath: screenshotBuffer,
|
|
484
|
+
comparisonResult,
|
|
485
|
+
passed: false
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
if (comparisonResult.passed) return {
|
|
489
|
+
screenshotPath: screenshotBuffer,
|
|
490
|
+
comparisonResult,
|
|
491
|
+
passed: true
|
|
492
|
+
};
|
|
493
|
+
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)}%)`);
|
|
494
|
+
} catch (error) {
|
|
495
|
+
this.logger.error(`Error taking screenshot after ${i + 1} retries:`, error.message);
|
|
496
|
+
}
|
|
497
|
+
return {
|
|
498
|
+
screenshotPath: null,
|
|
499
|
+
comparisonResult: null,
|
|
500
|
+
passed: false
|
|
501
|
+
};
|
|
244
502
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
503
|
+
getVariantFilename(filename, variant) {
|
|
504
|
+
if (variant.filename) return variant.filename;
|
|
505
|
+
const parsed = path.parse(filename);
|
|
506
|
+
const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
|
|
507
|
+
const ext = parsed.ext || ".png";
|
|
508
|
+
const variantName = `${parsed.name}--${suffix}${ext}`;
|
|
509
|
+
return parsed.dir ? path.join(parsed.dir, variantName) : variantName;
|
|
510
|
+
}
|
|
511
|
+
async capture(page, filename, options, extras = {}) {
|
|
512
|
+
if (!this.browser) throw new Error("Browser not initialized");
|
|
513
|
+
const { variants = [],...baseOptions } = options;
|
|
514
|
+
const baseResult = { filename };
|
|
515
|
+
const variantResults = [];
|
|
516
|
+
const baseSaveDiff = extras.saveDiffImage ?? false;
|
|
517
|
+
const baseDiffFilename = extras.diffImageFilename ?? filename;
|
|
518
|
+
if (baseOptions.skip) return {
|
|
519
|
+
base: {
|
|
520
|
+
...baseResult,
|
|
521
|
+
skipped: true
|
|
522
|
+
},
|
|
523
|
+
variants: variants.map((variant) => ({
|
|
524
|
+
id: variant.id,
|
|
525
|
+
label: variant.label,
|
|
526
|
+
filename: this.getVariantFilename(filename, variant),
|
|
527
|
+
skipped: true
|
|
528
|
+
}))
|
|
529
|
+
};
|
|
530
|
+
if (this.filesystem.hasExpectedFile(filename)) {
|
|
531
|
+
const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.readExpectedFile(filename), {
|
|
532
|
+
...baseOptions,
|
|
533
|
+
saveDiffImage: baseSaveDiff,
|
|
534
|
+
diffImageFilename: baseDiffFilename
|
|
535
|
+
});
|
|
536
|
+
baseResult.filepath = screenshotPath;
|
|
537
|
+
baseResult.comparisonResult = comparisonResult;
|
|
538
|
+
baseResult.diffImagePath = diffImagePath;
|
|
539
|
+
} else baseResult.filepath = await this.takeScreenshot(page, filename, baseOptions);
|
|
540
|
+
for (const variant of variants) {
|
|
541
|
+
const variantFilename = this.getVariantFilename(filename, variant);
|
|
542
|
+
const variantOptions = {
|
|
543
|
+
...baseOptions,
|
|
544
|
+
...variant.options
|
|
545
|
+
};
|
|
546
|
+
const variantResult = {
|
|
547
|
+
id: variant.id,
|
|
548
|
+
label: variant.label,
|
|
549
|
+
filename: variantFilename
|
|
550
|
+
};
|
|
551
|
+
if (variantOptions.skip) {
|
|
552
|
+
variantResult.skipped = true;
|
|
553
|
+
variantResults.push(variantResult);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
const variantExtra = extras.variants?.[variant.id];
|
|
557
|
+
const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
|
|
558
|
+
const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
|
|
559
|
+
if (this.filesystem.hasExpectedFile(variantFilename)) {
|
|
560
|
+
const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, variantFilename, this.filesystem.readExpectedFile(variantFilename), {
|
|
561
|
+
...variantOptions,
|
|
562
|
+
saveDiffImage: variantSaveDiff,
|
|
563
|
+
diffImageFilename: variantDiffFilename
|
|
564
|
+
});
|
|
565
|
+
variantResult.filepath = screenshotPath;
|
|
566
|
+
variantResult.comparisonResult = comparisonResult;
|
|
567
|
+
variantResult.diffImagePath = diffImagePath;
|
|
568
|
+
} else variantResult.filepath = await this.takeScreenshot(page, variantFilename, variantOptions);
|
|
569
|
+
variantResults.push(variantResult);
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
base: baseResult,
|
|
573
|
+
variants: variantResults
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Gets the exponential backoff delay
|
|
578
|
+
*/
|
|
579
|
+
getIncBackoffDelay(i, delay) {
|
|
580
|
+
return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Get a page from the pool by index
|
|
584
|
+
*/
|
|
585
|
+
getPageFromPool(index) {
|
|
586
|
+
if (index < 0) throw new Error(`Page index ${index} must be non-negative`);
|
|
587
|
+
if (index >= this.pages.length) throw new Error(`Page index ${index} exceeds pool size ${this.pages.length}`);
|
|
588
|
+
if (!this.pages[index]) throw new Error(`Page index ${index} is undefined`);
|
|
589
|
+
return this.pages[index];
|
|
249
590
|
}
|
|
250
591
|
};
|
|
251
592
|
var screenshot_default = ScreenshotTool;
|
|
252
593
|
|
|
253
594
|
//#endregion
|
|
254
|
-
export { screenshot_default as ScreenshotTool, defineConfig };
|
|
595
|
+
export { ScreenshotFileSystem, screenshot_default as ScreenshotTool, defineConfig };
|
|
255
596
|
//# sourceMappingURL=index.mjs.map
|