@cappa/core 0.3.0 → 0.4.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/CHANGELOG.md +18 -0
- package/dist/index.d.mts +38 -12
- package/dist/index.d.ts +38 -12
- package/dist/index.js +114 -100
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +110 -98
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -9
- package/src/index.ts +3 -0
- package/src/screenshot.ts +3 -0
- package/src/types.ts +7 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,29 +1,23 @@
|
|
|
1
1
|
|
|
2
|
-
> @cappa/core@0.
|
|
2
|
+
> @cappa/core@0.4.0 build /home/runner/work/cappa/cappa/packages/core
|
|
3
3
|
> tsdown
|
|
4
4
|
|
|
5
|
-
[34mℹ[39m tsdown [2mv0.15.
|
|
5
|
+
[34mℹ[39m tsdown [2mv0.15.12[22m powered by rolldown [2mv1.0.0-beta.45[22m
|
|
6
6
|
[34mℹ[39m Using tsdown config: [4m/home/runner/work/cappa/cappa/packages/core/tsdown.config.ts[24m
|
|
7
|
-
(node:
|
|
7
|
+
(node:2382) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///home/runner/work/cappa/cappa/packages/core/tsdown.config.ts is not specified and it doesn't parse as CommonJS.
|
|
8
8
|
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
|
|
9
9
|
To eliminate this warning, add "type": "module" to /home/runner/work/cappa/cappa/packages/core/package.json.
|
|
10
10
|
(Use `node --trace-warnings ...` to show where the warning was created)
|
|
11
11
|
[34mℹ[39m entry: [34msrc/index.ts[39m
|
|
12
12
|
[34mℹ[39m tsconfig: [34mtsconfig.json[39m
|
|
13
13
|
[34mℹ[39m Build start
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
[34mℹ[39m [
|
|
19
|
-
[34mℹ[39m [
|
|
20
|
-
[34mℹ[39m [
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
[
|
|
24
|
-
[34mℹ[39m [34m[ESM][39m [2mdist/[22mindex.mjs.map [2m46.14 kB[22m [2m│ gzip: 10.82 kB[22m
|
|
25
|
-
[34mℹ[39m [34m[ESM][39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m12.13 kB[22m [2m│ gzip: 3.47 kB[22m
|
|
26
|
-
[34mℹ[39m [34m[ESM][39m 3 files, total: 81.66 kB
|
|
27
|
-
[34mℹ[39m [33m[CJS][39m [2mdist/[22m[32m[1mindex.d.ts[22m[39m [2m12.13 kB[22m [2m│ gzip: 3.47 kB[22m
|
|
28
|
-
[34mℹ[39m [33m[CJS][39m 1 files, total: 12.13 kB
|
|
29
|
-
[32m✔[39m Build complete in [32m2381ms[39m
|
|
14
|
+
[34mℹ[39m [33m[CJS][39m [2mdist/[22m[1mindex.js[22m [2m25.76 kB[22m [2m│ gzip: 6.25 kB[22m
|
|
15
|
+
[34mℹ[39m [33m[CJS][39m [2mdist/[22mindex.js.map [2m46.51 kB[22m [2m│ gzip: 10.96 kB[22m
|
|
16
|
+
[34mℹ[39m [33m[CJS][39m 2 files, total: 72.27 kB
|
|
17
|
+
[34mℹ[39m [34m[ESM][39m [2mdist/[22m[1mindex.mjs[22m [2m23.88 kB[22m [2m│ gzip: 5.73 kB[22m
|
|
18
|
+
[34mℹ[39m [34m[ESM][39m [2mdist/[22mindex.mjs.map [2m46.40 kB[22m [2m│ gzip: 10.92 kB[22m
|
|
19
|
+
[34mℹ[39m [34m[ESM][39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m13.28 kB[22m [2m│ gzip: 3.78 kB[22m
|
|
20
|
+
[34mℹ[39m [34m[ESM][39m 3 files, total: 83.56 kB
|
|
21
|
+
[34mℹ[39m [33m[CJS][39m [2mdist/[22m[32m[1mindex.d.ts[22m[39m [2m13.28 kB[22m [2m│ gzip: 3.78 kB[22m
|
|
22
|
+
[34mℹ[39m [33m[CJS][39m 1 files, total: 13.28 kB
|
|
23
|
+
[32m✔[39m Build complete in [32m2838ms[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @cappa/core
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 915be10: Add a `logConsoleEvents` base configuration option that controls whether Playwright console
|
|
8
|
+
messages are logged during captures, and have the Storybook plugin respect the global setting.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- Updated dependencies [1e8f301]
|
|
13
|
+
- @cappa/logger@0.0.5
|
|
14
|
+
|
|
15
|
+
## 0.3.1
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 772d0f6: Ensure approving screenshots only updates baselines when actual and expected images differ.
|
|
20
|
+
|
|
3
21
|
## 0.3.0
|
|
4
22
|
|
|
5
23
|
### Minor Changes
|
package/dist/index.d.mts
CHANGED
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import { Logger } from "@cappa/logger";
|
|
2
2
|
import { Browser, BrowserContext, Locator, Page } from "playwright-core";
|
|
3
3
|
|
|
4
|
-
//#region src/compare.d.ts
|
|
5
|
-
interface CompareResult {
|
|
6
|
-
numDiffPixels: number;
|
|
7
|
-
totalPixels: number;
|
|
8
|
-
percentDifference: number;
|
|
9
|
-
diffBuffer?: Buffer;
|
|
10
|
-
passed: boolean;
|
|
11
|
-
error?: string;
|
|
12
|
-
differentSizes: boolean;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
4
|
//#region src/filesystem.d.ts
|
|
16
5
|
/**
|
|
17
6
|
* Class for interacting with the local file system to store the screenshots.
|
|
@@ -150,6 +139,7 @@ declare class ScreenshotTool {
|
|
|
150
139
|
logger: Logger;
|
|
151
140
|
retries: number;
|
|
152
141
|
filesystem: ScreenshotFileSystem;
|
|
142
|
+
logConsoleEvents: boolean;
|
|
153
143
|
constructor(options: {
|
|
154
144
|
browserType?: "chromium" | "firefox" | "webkit";
|
|
155
145
|
headless?: boolean;
|
|
@@ -161,6 +151,7 @@ declare class ScreenshotTool {
|
|
|
161
151
|
diff?: DiffConfig;
|
|
162
152
|
retries?: number;
|
|
163
153
|
concurrency?: number;
|
|
154
|
+
logConsoleEvents?: boolean;
|
|
164
155
|
});
|
|
165
156
|
/**
|
|
166
157
|
* Initialize playwright and page
|
|
@@ -343,6 +334,13 @@ type UserConfig = {
|
|
|
343
334
|
* The number of parallel browser contexts to use for taking screenshots
|
|
344
335
|
*/
|
|
345
336
|
concurrency?: number;
|
|
337
|
+
/**
|
|
338
|
+
* Whether to log Playwright console events while executing capture tasks.
|
|
339
|
+
*
|
|
340
|
+
* Enabled by default to aid in debugging. Disable to reduce noise in the
|
|
341
|
+
* console output when you do not need the additional details.
|
|
342
|
+
*/
|
|
343
|
+
logConsoleEvents?: boolean;
|
|
346
344
|
/**
|
|
347
345
|
* An array of Cappa plugins used for generation.
|
|
348
346
|
* Each plugin may have additional configurable options (defined within the plugin itself).
|
|
@@ -406,11 +404,39 @@ type FailedScreenshot = Screenshot & {
|
|
|
406
404
|
absoluteDiffPath?: string;
|
|
407
405
|
};
|
|
408
406
|
//#endregion
|
|
407
|
+
//#region src/compare.d.ts
|
|
408
|
+
interface CompareResult {
|
|
409
|
+
numDiffPixels: number;
|
|
410
|
+
totalPixels: number;
|
|
411
|
+
percentDifference: number;
|
|
412
|
+
diffBuffer?: Buffer;
|
|
413
|
+
passed: boolean;
|
|
414
|
+
error?: string;
|
|
415
|
+
differentSizes: boolean;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Compare two PNG images and return the difference
|
|
419
|
+
* @param image1 - First image (file path or Buffer)
|
|
420
|
+
* @param image2 - Second image (file path or Buffer)
|
|
421
|
+
* @param withDiff - Whether to create a diff image
|
|
422
|
+
* @param options - Comparison options
|
|
423
|
+
* @returns Comparison result
|
|
424
|
+
*/
|
|
425
|
+
declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult>;
|
|
426
|
+
/**
|
|
427
|
+
* Quick comparison function that returns only pass/fail
|
|
428
|
+
* @param image1 - First image (file path or Buffer)
|
|
429
|
+
* @param image2 - Second image (file path or Buffer)
|
|
430
|
+
* @param options - Comparison options
|
|
431
|
+
* @returns Whether the images match
|
|
432
|
+
*/
|
|
433
|
+
declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
|
|
434
|
+
//#endregion
|
|
409
435
|
//#region src/config.d.ts
|
|
410
436
|
/**
|
|
411
437
|
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
412
438
|
*/
|
|
413
439
|
declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
|
|
414
440
|
//#endregion
|
|
415
|
-
export { type ConfigEnv, type FailedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, defineConfig };
|
|
441
|
+
export { type ConfigEnv, type FailedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, compareImages, defineConfig, imagesMatch };
|
|
416
442
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import { Browser, BrowserContext, Locator, Page } from "playwright-core";
|
|
2
2
|
import { Logger } from "@cappa/logger";
|
|
3
3
|
|
|
4
|
-
//#region src/compare.d.ts
|
|
5
|
-
interface CompareResult {
|
|
6
|
-
numDiffPixels: number;
|
|
7
|
-
totalPixels: number;
|
|
8
|
-
percentDifference: number;
|
|
9
|
-
diffBuffer?: Buffer;
|
|
10
|
-
passed: boolean;
|
|
11
|
-
error?: string;
|
|
12
|
-
differentSizes: boolean;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
4
|
//#region src/filesystem.d.ts
|
|
16
5
|
/**
|
|
17
6
|
* Class for interacting with the local file system to store the screenshots.
|
|
@@ -150,6 +139,7 @@ declare class ScreenshotTool {
|
|
|
150
139
|
logger: Logger;
|
|
151
140
|
retries: number;
|
|
152
141
|
filesystem: ScreenshotFileSystem;
|
|
142
|
+
logConsoleEvents: boolean;
|
|
153
143
|
constructor(options: {
|
|
154
144
|
browserType?: "chromium" | "firefox" | "webkit";
|
|
155
145
|
headless?: boolean;
|
|
@@ -161,6 +151,7 @@ declare class ScreenshotTool {
|
|
|
161
151
|
diff?: DiffConfig;
|
|
162
152
|
retries?: number;
|
|
163
153
|
concurrency?: number;
|
|
154
|
+
logConsoleEvents?: boolean;
|
|
164
155
|
});
|
|
165
156
|
/**
|
|
166
157
|
* Initialize playwright and page
|
|
@@ -343,6 +334,13 @@ type UserConfig = {
|
|
|
343
334
|
* The number of parallel browser contexts to use for taking screenshots
|
|
344
335
|
*/
|
|
345
336
|
concurrency?: number;
|
|
337
|
+
/**
|
|
338
|
+
* Whether to log Playwright console events while executing capture tasks.
|
|
339
|
+
*
|
|
340
|
+
* Enabled by default to aid in debugging. Disable to reduce noise in the
|
|
341
|
+
* console output when you do not need the additional details.
|
|
342
|
+
*/
|
|
343
|
+
logConsoleEvents?: boolean;
|
|
346
344
|
/**
|
|
347
345
|
* An array of Cappa plugins used for generation.
|
|
348
346
|
* Each plugin may have additional configurable options (defined within the plugin itself).
|
|
@@ -406,11 +404,39 @@ type FailedScreenshot = Screenshot & {
|
|
|
406
404
|
absoluteDiffPath?: string;
|
|
407
405
|
};
|
|
408
406
|
//#endregion
|
|
407
|
+
//#region src/compare.d.ts
|
|
408
|
+
interface CompareResult {
|
|
409
|
+
numDiffPixels: number;
|
|
410
|
+
totalPixels: number;
|
|
411
|
+
percentDifference: number;
|
|
412
|
+
diffBuffer?: Buffer;
|
|
413
|
+
passed: boolean;
|
|
414
|
+
error?: string;
|
|
415
|
+
differentSizes: boolean;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Compare two PNG images and return the difference
|
|
419
|
+
* @param image1 - First image (file path or Buffer)
|
|
420
|
+
* @param image2 - Second image (file path or Buffer)
|
|
421
|
+
* @param withDiff - Whether to create a diff image
|
|
422
|
+
* @param options - Comparison options
|
|
423
|
+
* @returns Comparison result
|
|
424
|
+
*/
|
|
425
|
+
declare function compareImages(image1: string | Buffer, image2: string | Buffer, withDiff?: boolean, options?: DiffConfig): Promise<CompareResult>;
|
|
426
|
+
/**
|
|
427
|
+
* Quick comparison function that returns only pass/fail
|
|
428
|
+
* @param image1 - First image (file path or Buffer)
|
|
429
|
+
* @param image2 - Second image (file path or Buffer)
|
|
430
|
+
* @param options - Comparison options
|
|
431
|
+
* @returns Whether the images match
|
|
432
|
+
*/
|
|
433
|
+
declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
|
|
434
|
+
//#endregion
|
|
409
435
|
//#region src/config.d.ts
|
|
410
436
|
/**
|
|
411
437
|
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
412
438
|
*/
|
|
413
439
|
declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
|
|
414
440
|
//#endregion
|
|
415
|
-
export { type ConfigEnv, type FailedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, defineConfig };
|
|
441
|
+
export { type ConfigEnv, type FailedScreenshot, type Plugin, type PluginDef, type PluginFunction, type Screenshot, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, ScreenshotFileSystem, type ScreenshotOptions, type ScreenshotSettings, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type UserConfig, type Viewport, compareImages, defineConfig, imagesMatch };
|
|
416
442
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -23,17 +23,121 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
23
23
|
//#endregion
|
|
24
24
|
let node_fs = require("node:fs");
|
|
25
25
|
node_fs = __toESM(node_fs);
|
|
26
|
-
let node_path = require("node:path");
|
|
27
|
-
node_path = __toESM(node_path);
|
|
28
|
-
let __cappa_logger = require("@cappa/logger");
|
|
29
|
-
__cappa_logger = __toESM(__cappa_logger);
|
|
30
|
-
let playwright_core = require("playwright-core");
|
|
31
|
-
playwright_core = __toESM(playwright_core);
|
|
32
26
|
let __blazediff_core = require("@blazediff/core");
|
|
33
27
|
__blazediff_core = __toESM(__blazediff_core);
|
|
28
|
+
let __cappa_logger = require("@cappa/logger");
|
|
29
|
+
__cappa_logger = __toESM(__cappa_logger);
|
|
34
30
|
let pngjs = require("pngjs");
|
|
35
31
|
pngjs = __toESM(pngjs);
|
|
32
|
+
let node_path = require("node:path");
|
|
33
|
+
node_path = __toESM(node_path);
|
|
34
|
+
let playwright_core = require("playwright-core");
|
|
35
|
+
playwright_core = __toESM(playwright_core);
|
|
36
|
+
|
|
37
|
+
//#region src/compare.ts
|
|
38
|
+
const compare = (image1, image2, diff, width, height, options) => {
|
|
39
|
+
return (0, __blazediff_core.default)(image1, image2, diff, width, height, options);
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Compare two PNG images and return the difference
|
|
43
|
+
* @param image1 - First image (file path or Buffer)
|
|
44
|
+
* @param image2 - Second image (file path or Buffer)
|
|
45
|
+
* @param withDiff - Whether to create a diff image
|
|
46
|
+
* @param options - Comparison options
|
|
47
|
+
* @returns Comparison result
|
|
48
|
+
*/
|
|
49
|
+
async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
50
|
+
const png1 = await loadPNG(image1);
|
|
51
|
+
const png2 = await loadPNG(image2);
|
|
52
|
+
const { width, height } = png1;
|
|
53
|
+
if (width !== png2.width || height !== png2.height) return {
|
|
54
|
+
numDiffPixels: 0,
|
|
55
|
+
totalPixels: 0,
|
|
56
|
+
percentDifference: 0,
|
|
57
|
+
passed: false,
|
|
58
|
+
differentSizes: true
|
|
59
|
+
};
|
|
60
|
+
const diff = withDiff ? new pngjs.PNG({
|
|
61
|
+
width,
|
|
62
|
+
height
|
|
63
|
+
}) : void 0;
|
|
64
|
+
try {
|
|
65
|
+
const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
|
|
66
|
+
const totalPixels = width * height;
|
|
67
|
+
const percentDifference = numDiffPixels / totalPixels * 100;
|
|
68
|
+
return {
|
|
69
|
+
numDiffPixels,
|
|
70
|
+
totalPixels,
|
|
71
|
+
percentDifference,
|
|
72
|
+
diffBuffer: diff ? pngjs.PNG.sync.write(diff) : void 0,
|
|
73
|
+
passed: isPassed(percentDifference, numDiffPixels, options),
|
|
74
|
+
differentSizes: false
|
|
75
|
+
};
|
|
76
|
+
} catch (error) {
|
|
77
|
+
(0, __cappa_logger.getLogger)().error(error.message || "Unknown error");
|
|
78
|
+
return {
|
|
79
|
+
numDiffPixels: 0,
|
|
80
|
+
totalPixels: 0,
|
|
81
|
+
percentDifference: 0,
|
|
82
|
+
passed: false,
|
|
83
|
+
differentSizes: false,
|
|
84
|
+
error: error.message || "Unknown error"
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Load a PNG image from file path or Buffer
|
|
90
|
+
*/
|
|
91
|
+
async function loadPNG(source) {
|
|
92
|
+
if (Buffer.isBuffer(source)) return pngjs.PNG.sync.read(source);
|
|
93
|
+
else {
|
|
94
|
+
const buffer = node_fs.default.readFileSync(source);
|
|
95
|
+
return pngjs.PNG.sync.read(buffer);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Quick comparison function that returns only pass/fail
|
|
100
|
+
* @param image1 - First image (file path or Buffer)
|
|
101
|
+
* @param image2 - Second image (file path or Buffer)
|
|
102
|
+
* @param options - Comparison options
|
|
103
|
+
* @returns Whether the images match
|
|
104
|
+
*/
|
|
105
|
+
async function imagesMatch(image1, image2, options = {}) {
|
|
106
|
+
return (await compareImages(image1, image2, false, options)).passed;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Check if the comparison passed based on the options
|
|
110
|
+
* @param percentDifference - Percentage difference between the images
|
|
111
|
+
* @param numDiffPixels - Number of different pixels
|
|
112
|
+
* @param options - Comparison options
|
|
113
|
+
* @returns Whether the comparison passed
|
|
114
|
+
*/
|
|
115
|
+
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
116
|
+
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
117
|
+
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
118
|
+
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
119
|
+
return numDiffPixels === 0;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Create different size png image with all pixels red
|
|
123
|
+
* @returns
|
|
124
|
+
*/
|
|
125
|
+
function createDiffSizePngImage(width, height) {
|
|
126
|
+
const png = new pngjs.PNG({
|
|
127
|
+
width,
|
|
128
|
+
height
|
|
129
|
+
});
|
|
130
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
131
|
+
const idx = width * y + x << 2;
|
|
132
|
+
png.data[idx] = 255;
|
|
133
|
+
png.data[idx + 1] = 0;
|
|
134
|
+
png.data[idx + 2] = 0;
|
|
135
|
+
png.data[idx + 3] = 255;
|
|
136
|
+
}
|
|
137
|
+
return pngjs.PNG.sync.write(png);
|
|
138
|
+
}
|
|
36
139
|
|
|
140
|
+
//#endregion
|
|
37
141
|
//#region src/config.ts
|
|
38
142
|
/**
|
|
39
143
|
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
@@ -203,100 +307,6 @@ var ScreenshotFileSystem = class {
|
|
|
203
307
|
}
|
|
204
308
|
};
|
|
205
309
|
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region src/compare.ts
|
|
208
|
-
const compare = (image1, image2, diff, width, height, options) => {
|
|
209
|
-
return (0, __blazediff_core.default)(image1, image2, diff, width, height, options);
|
|
210
|
-
};
|
|
211
|
-
/**
|
|
212
|
-
* Compare two PNG images and return the difference
|
|
213
|
-
* @param image1 - First image (file path or Buffer)
|
|
214
|
-
* @param image2 - Second image (file path or Buffer)
|
|
215
|
-
* @param withDiff - Whether to create a diff image
|
|
216
|
-
* @param options - Comparison options
|
|
217
|
-
* @returns Comparison result
|
|
218
|
-
*/
|
|
219
|
-
async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
220
|
-
const png1 = await loadPNG(image1);
|
|
221
|
-
const png2 = await loadPNG(image2);
|
|
222
|
-
const { width, height } = png1;
|
|
223
|
-
if (width !== png2.width || height !== png2.height) return {
|
|
224
|
-
numDiffPixels: 0,
|
|
225
|
-
totalPixels: 0,
|
|
226
|
-
percentDifference: 0,
|
|
227
|
-
passed: false,
|
|
228
|
-
differentSizes: true
|
|
229
|
-
};
|
|
230
|
-
const diff = withDiff ? new pngjs.PNG({
|
|
231
|
-
width,
|
|
232
|
-
height
|
|
233
|
-
}) : void 0;
|
|
234
|
-
try {
|
|
235
|
-
const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
|
|
236
|
-
const totalPixels = width * height;
|
|
237
|
-
const percentDifference = numDiffPixels / totalPixels * 100;
|
|
238
|
-
return {
|
|
239
|
-
numDiffPixels,
|
|
240
|
-
totalPixels,
|
|
241
|
-
percentDifference,
|
|
242
|
-
diffBuffer: diff ? pngjs.PNG.sync.write(diff) : void 0,
|
|
243
|
-
passed: isPassed(percentDifference, numDiffPixels, options),
|
|
244
|
-
differentSizes: false
|
|
245
|
-
};
|
|
246
|
-
} catch (error) {
|
|
247
|
-
(0, __cappa_logger.getLogger)().error(error.message || "Unknown error");
|
|
248
|
-
return {
|
|
249
|
-
numDiffPixels: 0,
|
|
250
|
-
totalPixels: 0,
|
|
251
|
-
percentDifference: 0,
|
|
252
|
-
passed: false,
|
|
253
|
-
differentSizes: false,
|
|
254
|
-
error: error.message || "Unknown error"
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Load a PNG image from file path or Buffer
|
|
260
|
-
*/
|
|
261
|
-
async function loadPNG(source) {
|
|
262
|
-
if (Buffer.isBuffer(source)) return pngjs.PNG.sync.read(source);
|
|
263
|
-
else {
|
|
264
|
-
const buffer = node_fs.default.readFileSync(source);
|
|
265
|
-
return pngjs.PNG.sync.read(buffer);
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Check if the comparison passed based on the options
|
|
270
|
-
* @param percentDifference - Percentage difference between the images
|
|
271
|
-
* @param numDiffPixels - Number of different pixels
|
|
272
|
-
* @param options - Comparison options
|
|
273
|
-
* @returns Whether the comparison passed
|
|
274
|
-
*/
|
|
275
|
-
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
276
|
-
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
277
|
-
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
278
|
-
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
279
|
-
return numDiffPixels === 0;
|
|
280
|
-
};
|
|
281
|
-
/**
|
|
282
|
-
* Create different size png image with all pixels red
|
|
283
|
-
* @returns
|
|
284
|
-
*/
|
|
285
|
-
function createDiffSizePngImage(width, height) {
|
|
286
|
-
const png = new pngjs.PNG({
|
|
287
|
-
width,
|
|
288
|
-
height
|
|
289
|
-
});
|
|
290
|
-
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
291
|
-
const idx = width * y + x << 2;
|
|
292
|
-
png.data[idx] = 255;
|
|
293
|
-
png.data[idx + 1] = 0;
|
|
294
|
-
png.data[idx + 2] = 0;
|
|
295
|
-
png.data[idx + 3] = 255;
|
|
296
|
-
}
|
|
297
|
-
return pngjs.PNG.sync.write(png);
|
|
298
|
-
}
|
|
299
|
-
|
|
300
310
|
//#endregion
|
|
301
311
|
//#region src/screenshot.ts
|
|
302
312
|
const defaultDiffConfig = {
|
|
@@ -321,6 +331,7 @@ var ScreenshotTool = class {
|
|
|
321
331
|
logger;
|
|
322
332
|
retries;
|
|
323
333
|
filesystem;
|
|
334
|
+
logConsoleEvents;
|
|
324
335
|
constructor(options) {
|
|
325
336
|
this.browserType = options.browserType || "chromium";
|
|
326
337
|
this.headless = options.headless !== false;
|
|
@@ -334,6 +345,7 @@ var ScreenshotTool = class {
|
|
|
334
345
|
...options.diff
|
|
335
346
|
};
|
|
336
347
|
this.concurrency = Math.max(1, options.concurrency || 1);
|
|
348
|
+
this.logConsoleEvents = options.logConsoleEvents ?? true;
|
|
337
349
|
this.logger = (0, __cappa_logger.getLogger)();
|
|
338
350
|
this.retries = options.retries || 2;
|
|
339
351
|
this.filesystem = new ScreenshotFileSystem(this.outputDir);
|
|
@@ -730,5 +742,7 @@ var screenshot_default = ScreenshotTool;
|
|
|
730
742
|
//#endregion
|
|
731
743
|
exports.ScreenshotFileSystem = ScreenshotFileSystem;
|
|
732
744
|
exports.ScreenshotTool = screenshot_default;
|
|
745
|
+
exports.compareImages = compareImages;
|
|
733
746
|
exports.defineConfig = defineConfig;
|
|
747
|
+
exports.imagesMatch = imagesMatch;
|
|
734
748
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["path","fs","PNG","fs","defaultDiffConfig: DiffConfig","screenshotSettings: ScreenshotSettings","diffImagePath: string | undefined","path","result: ScreenshotCaptureDetails","baseResult: ScreenshotCaptureDetails","variantResults: ScreenshotVariantCaptureDetails[]","variantOptions: ScreenshotSettings","variantResult: ScreenshotVariantCaptureDetails"],"sources":["../src/config.ts","../src/filesystem.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { ConfigEnv, 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>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actualDir: string;\n private readonly expectedDir: string;\n private readonly diffDir: string;\n\n constructor(outputDir: string) {\n this.actualDir = path.resolve(outputDir, \"actual\");\n this.expectedDir = path.resolve(outputDir, \"expected\");\n this.diffDir = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDir(this.actualDir);\n this.ensureParentDir(this.expectedDir);\n this.ensureParentDir(this.diffDir);\n }\n\n clearActual() {\n this.removeDir(this.actualDir);\n }\n\n clearDiff() {\n this.removeDir(this.diffDir);\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actualDir, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actualDir, relativePath);\n const expectedPath = path.resolve(this.expectedDir, relativePath);\n const diffPath = path.resolve(this.diffDir, relativePath);\n\n this.ensureParentDir(expectedPath);\n\n fs.copyFileSync(actualPath, expectedPath);\n\n if (fs.existsSync(diffPath)) {\n fs.unlinkSync(diffPath);\n }\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actualDir;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expectedDir;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diffDir;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actualDir, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expectedDir, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diffDir, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n writeActualFile(filename: string, data: Buffer): void {\n const filepath = this.getActualFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n writeDiffFile(filename: string, data: Buffer): void {\n const filepath = this.getDiffFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Check if an expected file exists\n */\n hasExpectedFile(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n /**\n * Read an expected file\n */\n readExpectedFile(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 /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actualDir, filePath);\n }\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { getLogger } from \"@cappa/logger\";\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 error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\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 const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n try {\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 differentSizes: false,\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\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\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\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\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport function createDiffSizePngImage(width: number, height: number): Buffer {\n const png = new PNG({ width, height });\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return PNG.sync.write(png);\n}\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareResult,\n compareImages,\n createDiffSizePngImage,\n} from \"./compare\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type {\n DiffConfig,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: CompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n }\n >;\n}\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n filesystem: ScreenshotFileSystem;\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 concurrency?: 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 this.concurrency = Math.max(1, options.concurrency || 1);\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\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 // Create N contexts and pages\n this.contexts = [];\n this.pages = [];\n\n for (let i = 0; i < this.concurrency; i++) {\n const context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n\n this.contexts.push(context);\n this.pages.push(page);\n }\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n for (const context of this.contexts) {\n await 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 * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\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.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n this.filesystem.ensureParentDir(filepath);\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\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: ScreenshotSettings & {\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.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);\n this.logger.debug(`Actual 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.filesystem.getDiffFilePath(diffFilename);\n\n this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n // different sizes diff image\n if (retryScreenshot.comparisonResult.differentSizes) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = createDiffSizePngImage(200, 200);\n\n this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size 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 referenceImage: Buffer,\n options: ScreenshotSettings,\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\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,\n );\n\n // bail early if the images are different sizes\n if (comparisonResult.differentSizes) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\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 getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n\n if (!this.filesystem.hasExpectedFile(filename)) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.readExpectedFile(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n\n // Capture base screenshot\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl);\n await this.applyScreenshotOptimizations(page);\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url);\n await this.applyScreenshotOptimizations(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\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 /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;;;;ACJT,IAAa,uBAAb,MAAkC;CAChC,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,YAAY,WAAmB;AAC7B,OAAK,YAAYA,kBAAK,QAAQ,WAAW,SAAS;AAClD,OAAK,cAAcA,kBAAK,QAAQ,WAAW,WAAW;AACtD,OAAK,UAAUA,kBAAK,QAAQ,WAAW,OAAO;AAE9C,OAAK,gBAAgB,KAAK,UAAU;AACpC,OAAK,gBAAgB,KAAK,YAAY;AACtC,OAAK,gBAAgB,KAAK,QAAQ;;CAGpC,cAAc;AACZ,OAAK,UAAU,KAAK,UAAU;;CAGhC,YAAY;AACV,OAAK,UAAU,KAAK,QAAQ;;CAG9B,qBAAqB;AACnB,OAAK,aAAa;AAClB,OAAK,WAAW;;;;;;;CAQlB,sBAAsB,gBAAwB;EAC5C,MAAM,iBAAiB,KAAK,kBAAkB,eAA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AAM,KAAK,6BAA6B,KAAK;GAE7C,MAAM,eAAe,OAAO,WAAW,QAAQ;GAC/C,MAAM,kBAAkB,cAAc,iBAAiB;GACvD,MAAM,sBACJ,cAAc,qBAAqB;GAErC,MAAM,uBAAuB,MAAM,KAAK,wBACtC,MACA,iBACA,gBACA;IACE,eAAe;IACf,mBAAmB;IACpB,CACF;AAED,iBAAc,WAAW,qBAAqB;AAC9C,iBAAc,mBAAmB,qBAAqB;AACtD,iBAAc,gBAAgB,qBAAqB;AACnD,iBAAc,UAAU,qBAAqB;AAE7C,kBAAe,KAAK,cAAc;;AAGpC,SAAO;GACL,MAAM;GACN,UAAU;GACX;;;;;CAMH,mBAAmB,GAAW,OAAuB;AACnD,SAAO,IAAI,IAAI,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK;;;;;CAMrD,gBAAgB,OAAqB;AACnC,MAAI,QAAQ,EACV,OAAM,IAAI,MAAM,cAAc,MAAM,uBAAuB;AAG7D,MAAI,SAAS,KAAK,MAAM,OACtB,OAAM,IAAI,MACR,cAAc,MAAM,qBAAqB,KAAK,MAAM,SACrD;AAGH,MAAI,CAAC,KAAK,MAAM,OACd,OAAM,IAAI,MAAM,cAAc,MAAM,eAAe;AAGrD,SAAO,KAAK,MAAM;;;AAItB,yBAAe"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["PNG","fs","path","fs","defaultDiffConfig: DiffConfig","screenshotSettings: ScreenshotSettings","diffImagePath: string | undefined","path","result: ScreenshotCaptureDetails","baseResult: ScreenshotCaptureDetails","variantResults: ScreenshotVariantCaptureDetails[]","variantOptions: ScreenshotSettings","variantResult: ScreenshotVariantCaptureDetails"],"sources":["../src/compare.ts","../src/config.ts","../src/filesystem.ts","../src/screenshot.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { getLogger } from \"@cappa/logger\";\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 error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\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 const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n try {\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 differentSizes: false,\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\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\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\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\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport function createDiffSizePngImage(width: number, height: number): Buffer {\n const png = new PNG({ width, height });\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return PNG.sync.write(png);\n}\n","import type { ConfigEnv, 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>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actualDir: string;\n private readonly expectedDir: string;\n private readonly diffDir: string;\n\n constructor(outputDir: string) {\n this.actualDir = path.resolve(outputDir, \"actual\");\n this.expectedDir = path.resolve(outputDir, \"expected\");\n this.diffDir = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDir(this.actualDir);\n this.ensureParentDir(this.expectedDir);\n this.ensureParentDir(this.diffDir);\n }\n\n clearActual() {\n this.removeDir(this.actualDir);\n }\n\n clearDiff() {\n this.removeDir(this.diffDir);\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actualDir, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actualDir, relativePath);\n const expectedPath = path.resolve(this.expectedDir, relativePath);\n const diffPath = path.resolve(this.diffDir, relativePath);\n\n this.ensureParentDir(expectedPath);\n\n fs.copyFileSync(actualPath, expectedPath);\n\n if (fs.existsSync(diffPath)) {\n fs.unlinkSync(diffPath);\n }\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actualDir;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expectedDir;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diffDir;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actualDir, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expectedDir, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diffDir, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n writeActualFile(filename: string, data: Buffer): void {\n const filepath = this.getActualFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n writeDiffFile(filename: string, data: Buffer): void {\n const filepath = this.getDiffFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Check if an expected file exists\n */\n hasExpectedFile(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n /**\n * Read an expected file\n */\n readExpectedFile(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 /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actualDir, filePath);\n }\n}\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareResult,\n compareImages,\n createDiffSizePngImage,\n} from \"./compare\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type {\n DiffConfig,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: CompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n }\n >;\n}\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: boolean;\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 concurrency?: number;\n logConsoleEvents?: boolean;\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 this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\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 // Create N contexts and pages\n this.contexts = [];\n this.pages = [];\n\n for (let i = 0; i < this.concurrency; i++) {\n const context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n\n this.contexts.push(context);\n this.pages.push(page);\n }\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n for (const context of this.contexts) {\n await 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 * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\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.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n this.filesystem.ensureParentDir(filepath);\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\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: ScreenshotSettings & {\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.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);\n this.logger.debug(`Actual 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.filesystem.getDiffFilePath(diffFilename);\n\n this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n // different sizes diff image\n if (retryScreenshot.comparisonResult.differentSizes) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = createDiffSizePngImage(200, 200);\n\n this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size 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 referenceImage: Buffer,\n options: ScreenshotSettings,\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\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,\n );\n\n // bail early if the images are different sizes\n if (comparisonResult.differentSizes) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\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 getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n\n if (!this.filesystem.hasExpectedFile(filename)) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.readExpectedFile(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n\n // Capture base screenshot\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl);\n await this.applyScreenshotOptimizations(page);\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url);\n await this.applyScreenshotOptimizations(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\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 /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;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SAAO,IAAI,IAAI,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK;;;;;CAMrD,gBAAgB,OAAqB;AACnC,MAAI,QAAQ,EACV,OAAM,IAAI,MAAM,cAAc,MAAM,uBAAuB;AAG7D,MAAI,SAAS,KAAK,MAAM,OACtB,OAAM,IAAI,MACR,cAAc,MAAM,qBAAqB,KAAK,MAAM,SACrD;AAGH,MAAI,CAAC,KAAK,MAAM,OACd,OAAM,IAAI,MAAM,cAAc,MAAM,eAAe;AAGrD,SAAO,KAAK,MAAM;;;AAItB,yBAAe"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,114 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { getLogger } from "@cappa/logger";
|
|
4
|
-
import { chromium, firefox, webkit } from "playwright-core";
|
|
5
2
|
import blazediff from "@blazediff/core";
|
|
3
|
+
import { getLogger } from "@cappa/logger";
|
|
6
4
|
import { PNG } from "pngjs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { chromium, firefox, webkit } from "playwright-core";
|
|
7
|
+
|
|
8
|
+
//#region src/compare.ts
|
|
9
|
+
const compare = (image1, image2, diff, width, height, options) => {
|
|
10
|
+
return blazediff(image1, image2, diff, width, height, options);
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Compare two PNG images and return the difference
|
|
14
|
+
* @param image1 - First image (file path or Buffer)
|
|
15
|
+
* @param image2 - Second image (file path or Buffer)
|
|
16
|
+
* @param withDiff - Whether to create a diff image
|
|
17
|
+
* @param options - Comparison options
|
|
18
|
+
* @returns Comparison result
|
|
19
|
+
*/
|
|
20
|
+
async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
21
|
+
const png1 = await loadPNG(image1);
|
|
22
|
+
const png2 = await loadPNG(image2);
|
|
23
|
+
const { width, height } = png1;
|
|
24
|
+
if (width !== png2.width || height !== png2.height) return {
|
|
25
|
+
numDiffPixels: 0,
|
|
26
|
+
totalPixels: 0,
|
|
27
|
+
percentDifference: 0,
|
|
28
|
+
passed: false,
|
|
29
|
+
differentSizes: true
|
|
30
|
+
};
|
|
31
|
+
const diff = withDiff ? new PNG({
|
|
32
|
+
width,
|
|
33
|
+
height
|
|
34
|
+
}) : void 0;
|
|
35
|
+
try {
|
|
36
|
+
const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
|
|
37
|
+
const totalPixels = width * height;
|
|
38
|
+
const percentDifference = numDiffPixels / totalPixels * 100;
|
|
39
|
+
return {
|
|
40
|
+
numDiffPixels,
|
|
41
|
+
totalPixels,
|
|
42
|
+
percentDifference,
|
|
43
|
+
diffBuffer: diff ? PNG.sync.write(diff) : void 0,
|
|
44
|
+
passed: isPassed(percentDifference, numDiffPixels, options),
|
|
45
|
+
differentSizes: false
|
|
46
|
+
};
|
|
47
|
+
} catch (error) {
|
|
48
|
+
getLogger().error(error.message || "Unknown error");
|
|
49
|
+
return {
|
|
50
|
+
numDiffPixels: 0,
|
|
51
|
+
totalPixels: 0,
|
|
52
|
+
percentDifference: 0,
|
|
53
|
+
passed: false,
|
|
54
|
+
differentSizes: false,
|
|
55
|
+
error: error.message || "Unknown error"
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Load a PNG image from file path or Buffer
|
|
61
|
+
*/
|
|
62
|
+
async function loadPNG(source) {
|
|
63
|
+
if (Buffer.isBuffer(source)) return PNG.sync.read(source);
|
|
64
|
+
else {
|
|
65
|
+
const buffer = fs.readFileSync(source);
|
|
66
|
+
return PNG.sync.read(buffer);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Quick comparison function that returns only pass/fail
|
|
71
|
+
* @param image1 - First image (file path or Buffer)
|
|
72
|
+
* @param image2 - Second image (file path or Buffer)
|
|
73
|
+
* @param options - Comparison options
|
|
74
|
+
* @returns Whether the images match
|
|
75
|
+
*/
|
|
76
|
+
async function imagesMatch(image1, image2, options = {}) {
|
|
77
|
+
return (await compareImages(image1, image2, false, options)).passed;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Check if the comparison passed based on the options
|
|
81
|
+
* @param percentDifference - Percentage difference between the images
|
|
82
|
+
* @param numDiffPixels - Number of different pixels
|
|
83
|
+
* @param options - Comparison options
|
|
84
|
+
* @returns Whether the comparison passed
|
|
85
|
+
*/
|
|
86
|
+
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
87
|
+
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
88
|
+
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
89
|
+
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
90
|
+
return numDiffPixels === 0;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Create different size png image with all pixels red
|
|
94
|
+
* @returns
|
|
95
|
+
*/
|
|
96
|
+
function createDiffSizePngImage(width, height) {
|
|
97
|
+
const png = new PNG({
|
|
98
|
+
width,
|
|
99
|
+
height
|
|
100
|
+
});
|
|
101
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
102
|
+
const idx = width * y + x << 2;
|
|
103
|
+
png.data[idx] = 255;
|
|
104
|
+
png.data[idx + 1] = 0;
|
|
105
|
+
png.data[idx + 2] = 0;
|
|
106
|
+
png.data[idx + 3] = 255;
|
|
107
|
+
}
|
|
108
|
+
return PNG.sync.write(png);
|
|
109
|
+
}
|
|
7
110
|
|
|
111
|
+
//#endregion
|
|
8
112
|
//#region src/config.ts
|
|
9
113
|
/**
|
|
10
114
|
* Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
|
|
@@ -174,100 +278,6 @@ var ScreenshotFileSystem = class {
|
|
|
174
278
|
}
|
|
175
279
|
};
|
|
176
280
|
|
|
177
|
-
//#endregion
|
|
178
|
-
//#region src/compare.ts
|
|
179
|
-
const compare = (image1, image2, diff, width, height, options) => {
|
|
180
|
-
return blazediff(image1, image2, diff, width, height, options);
|
|
181
|
-
};
|
|
182
|
-
/**
|
|
183
|
-
* Compare two PNG images and return the difference
|
|
184
|
-
* @param image1 - First image (file path or Buffer)
|
|
185
|
-
* @param image2 - Second image (file path or Buffer)
|
|
186
|
-
* @param withDiff - Whether to create a diff image
|
|
187
|
-
* @param options - Comparison options
|
|
188
|
-
* @returns Comparison result
|
|
189
|
-
*/
|
|
190
|
-
async function compareImages(image1, image2, withDiff = false, options = {}) {
|
|
191
|
-
const png1 = await loadPNG(image1);
|
|
192
|
-
const png2 = await loadPNG(image2);
|
|
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
|
-
};
|
|
201
|
-
const diff = withDiff ? new PNG({
|
|
202
|
-
width,
|
|
203
|
-
height
|
|
204
|
-
}) : void 0;
|
|
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
|
-
}
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Load a PNG image from file path or Buffer
|
|
231
|
-
*/
|
|
232
|
-
async function loadPNG(source) {
|
|
233
|
-
if (Buffer.isBuffer(source)) return PNG.sync.read(source);
|
|
234
|
-
else {
|
|
235
|
-
const buffer = fs.readFileSync(source);
|
|
236
|
-
return PNG.sync.read(buffer);
|
|
237
|
-
}
|
|
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
|
-
*/
|
|
246
|
-
const isPassed = (percentDifference, numDiffPixels, options) => {
|
|
247
|
-
if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
|
|
248
|
-
if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
|
|
249
|
-
if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
|
|
250
|
-
return numDiffPixels === 0;
|
|
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
|
-
}
|
|
270
|
-
|
|
271
281
|
//#endregion
|
|
272
282
|
//#region src/screenshot.ts
|
|
273
283
|
const defaultDiffConfig = {
|
|
@@ -292,6 +302,7 @@ var ScreenshotTool = class {
|
|
|
292
302
|
logger;
|
|
293
303
|
retries;
|
|
294
304
|
filesystem;
|
|
305
|
+
logConsoleEvents;
|
|
295
306
|
constructor(options) {
|
|
296
307
|
this.browserType = options.browserType || "chromium";
|
|
297
308
|
this.headless = options.headless !== false;
|
|
@@ -305,6 +316,7 @@ var ScreenshotTool = class {
|
|
|
305
316
|
...options.diff
|
|
306
317
|
};
|
|
307
318
|
this.concurrency = Math.max(1, options.concurrency || 1);
|
|
319
|
+
this.logConsoleEvents = options.logConsoleEvents ?? true;
|
|
308
320
|
this.logger = getLogger();
|
|
309
321
|
this.retries = options.retries || 2;
|
|
310
322
|
this.filesystem = new ScreenshotFileSystem(this.outputDir);
|
|
@@ -699,5 +711,5 @@ var ScreenshotTool = class {
|
|
|
699
711
|
var screenshot_default = ScreenshotTool;
|
|
700
712
|
|
|
701
713
|
//#endregion
|
|
702
|
-
export { ScreenshotFileSystem, screenshot_default as ScreenshotTool, defineConfig };
|
|
714
|
+
export { ScreenshotFileSystem, screenshot_default as ScreenshotTool, compareImages, defineConfig, imagesMatch };
|
|
703
715
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","screenshotSettings: ScreenshotSettings","diffImagePath: string | undefined","result: ScreenshotCaptureDetails","baseResult: ScreenshotCaptureDetails","variantResults: ScreenshotVariantCaptureDetails[]","variantOptions: ScreenshotSettings","variantResult: ScreenshotVariantCaptureDetails"],"sources":["../src/config.ts","../src/filesystem.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { ConfigEnv, 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>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actualDir: string;\n private readonly expectedDir: string;\n private readonly diffDir: string;\n\n constructor(outputDir: string) {\n this.actualDir = path.resolve(outputDir, \"actual\");\n this.expectedDir = path.resolve(outputDir, \"expected\");\n this.diffDir = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDir(this.actualDir);\n this.ensureParentDir(this.expectedDir);\n this.ensureParentDir(this.diffDir);\n }\n\n clearActual() {\n this.removeDir(this.actualDir);\n }\n\n clearDiff() {\n this.removeDir(this.diffDir);\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actualDir, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actualDir, relativePath);\n const expectedPath = path.resolve(this.expectedDir, relativePath);\n const diffPath = path.resolve(this.diffDir, relativePath);\n\n this.ensureParentDir(expectedPath);\n\n fs.copyFileSync(actualPath, expectedPath);\n\n if (fs.existsSync(diffPath)) {\n fs.unlinkSync(diffPath);\n }\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actualDir;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expectedDir;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diffDir;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actualDir, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expectedDir, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diffDir, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n writeActualFile(filename: string, data: Buffer): void {\n const filepath = this.getActualFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n writeDiffFile(filename: string, data: Buffer): void {\n const filepath = this.getDiffFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Check if an expected file exists\n */\n hasExpectedFile(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n /**\n * Read an expected file\n */\n readExpectedFile(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 /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actualDir, filePath);\n }\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { getLogger } from \"@cappa/logger\";\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 error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\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 const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n try {\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 differentSizes: false,\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\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\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\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\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport function createDiffSizePngImage(width: number, height: number): Buffer {\n const png = new PNG({ width, height });\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return PNG.sync.write(png);\n}\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareResult,\n compareImages,\n createDiffSizePngImage,\n} from \"./compare\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type {\n DiffConfig,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: CompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n }\n >;\n}\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n filesystem: ScreenshotFileSystem;\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 concurrency?: 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 this.concurrency = Math.max(1, options.concurrency || 1);\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\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 // Create N contexts and pages\n this.contexts = [];\n this.pages = [];\n\n for (let i = 0; i < this.concurrency; i++) {\n const context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n\n this.contexts.push(context);\n this.pages.push(page);\n }\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n for (const context of this.contexts) {\n await 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 * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\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.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n this.filesystem.ensureParentDir(filepath);\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\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: ScreenshotSettings & {\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.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);\n this.logger.debug(`Actual 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.filesystem.getDiffFilePath(diffFilename);\n\n this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n // different sizes diff image\n if (retryScreenshot.comparisonResult.differentSizes) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = createDiffSizePngImage(200, 200);\n\n this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size 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 referenceImage: Buffer,\n options: ScreenshotSettings,\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\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,\n );\n\n // bail early if the images are different sizes\n if (comparisonResult.differentSizes) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\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 getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n\n if (!this.filesystem.hasExpectedFile(filename)) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.readExpectedFile(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n\n // Capture base screenshot\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl);\n await this.applyScreenshotOptimizations(page);\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url);\n await this.applyScreenshotOptimizations(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\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 /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AACh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M,cAAc,MAAM,eAAe;AAGrD,SAAO,KAAK,MAAM;;;AAItB,yBAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["defaultDiffConfig: DiffConfig","screenshotSettings: ScreenshotSettings","diffImagePath: string | undefined","result: ScreenshotCaptureDetails","baseResult: ScreenshotCaptureDetails","variantResults: ScreenshotVariantCaptureDetails[]","variantOptions: ScreenshotSettings","variantResult: ScreenshotVariantCaptureDetails"],"sources":["../src/compare.ts","../src/config.ts","../src/filesystem.ts","../src/screenshot.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { getLogger } from \"@cappa/logger\";\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 error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\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 const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n try {\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 differentSizes: false,\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\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\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\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\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport function createDiffSizePngImage(width: number, height: number): Buffer {\n const png = new PNG({ width, height });\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return PNG.sync.write(png);\n}\n","import type { ConfigEnv, 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>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actualDir: string;\n private readonly expectedDir: string;\n private readonly diffDir: string;\n\n constructor(outputDir: string) {\n this.actualDir = path.resolve(outputDir, \"actual\");\n this.expectedDir = path.resolve(outputDir, \"expected\");\n this.diffDir = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDir(this.actualDir);\n this.ensureParentDir(this.expectedDir);\n this.ensureParentDir(this.diffDir);\n }\n\n clearActual() {\n this.removeDir(this.actualDir);\n }\n\n clearDiff() {\n this.removeDir(this.diffDir);\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n const relativePath = path.relative(this.actualDir, actualAbsolute);\n\n if (relativePath.startsWith(\"..\")) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(relativePath);\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actualDir, relativePath);\n const expectedPath = path.resolve(this.expectedDir, relativePath);\n const diffPath = path.resolve(this.diffDir, relativePath);\n\n this.ensureParentDir(expectedPath);\n\n fs.copyFileSync(actualPath, expectedPath);\n\n if (fs.existsSync(diffPath)) {\n fs.unlinkSync(diffPath);\n }\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actualDir;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expectedDir;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diffDir;\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.resolve(this.actualDir, filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.resolve(this.expectedDir, filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.resolve(this.diffDir, filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n writeActualFile(filename: string, data: Buffer): void {\n const filepath = this.getActualFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n writeDiffFile(filename: string, data: Buffer): void {\n const filepath = this.getDiffFilePath(filename);\n this.ensureParentDir(filepath);\n fs.writeFileSync(filepath, data);\n }\n\n /**\n * Check if an expected file exists\n */\n hasExpectedFile(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n /**\n * Read an expected file\n */\n readExpectedFile(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 /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actualDir, filePath);\n }\n}\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareResult,\n compareImages,\n createDiffSizePngImage,\n} from \"./compare\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type {\n DiffConfig,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: CompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n }\n >;\n}\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: boolean;\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 concurrency?: number;\n logConsoleEvents?: boolean;\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 this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\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 // Create N contexts and pages\n this.contexts = [];\n this.pages = [];\n\n for (let i = 0; i < this.concurrency; i++) {\n const context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n\n this.contexts.push(context);\n this.pages.push(page);\n }\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n for (const context of this.contexts) {\n await 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 * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\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.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n this.filesystem.ensureParentDir(filepath);\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\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 /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\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 animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\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: ScreenshotSettings & {\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.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);\n this.logger.debug(`Actual 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.filesystem.getDiffFilePath(diffFilename);\n\n this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n // different sizes diff image\n if (retryScreenshot.comparisonResult.differentSizes) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = createDiffSizePngImage(200, 200);\n\n this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size 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 referenceImage: Buffer,\n options: ScreenshotSettings,\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\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,\n );\n\n // bail early if the images are different sizes\n if (comparisonResult.differentSizes) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\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 getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n return variant.filename;\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n\n if (!this.filesystem.hasExpectedFile(filename)) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.readExpectedFile(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n\n // Capture base screenshot\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl);\n await this.applyScreenshotOptimizations(page);\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename =\n variant.filename || this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url);\n await this.applyScreenshotOptimizations(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\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 /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;AAmBA,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;CACxB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;AAE1B,KAAI,UAAU,KAAK,SAAS,WAAW,KAAK,OAC1C,QAAO;EACL,eAAe;EACf,aAAa;EACb,mBAAmB;EACnB,QAAQ;EACR,gBAAgB;EACjB;CAGH,MAAM,OAAO,WAAW,IAAI,IAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;AAErD,KAAI;EACF,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;EAED,MAAM,cAAc,QAAQ;EAC5B,MAAM,oBAAqB,gBAAgB,cAAe;AAK1D,SAAO;GACL;GACA;GACA;GACA,YANiB,OAAO,IAAI,KAAK,MAAM,KAAK,GAAG;GAO/C,QAAQ,SAAS,mBAAmB,eAAe,QAAQ;GAC3D,gBA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W,QAAQ;GAC/C,MAAM,kBAAkB,cAAc,iBAAiB;GACvD,MAAM,sBACJ,cAAc,qBAAqB;GAErC,MAAM,uBAAuB,MAAM,KAAK,wBACtC,MACA,iBACA,gBACA;IACE,eAAe;IACf,mBAAmB;IACpB,CACF;AAED,iBAAc,WAAW,qBAAqB;AAC9C,iBAAc,mBAAmB,qBAAqB;AACtD,iBAAc,gBAAgB,qBAAqB;AACnD,iBAAc,UAAU,qBAAqB;AAE7C,kBAAe,KAAK,cAAc;;AAGpC,SAAO;GACL,MAAM;GACN,UAAU;GACX;;;;;CAMH,mBAAmB,GAAW,OAAuB;AACnD,SAAO,IAAI,IAAI,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK;;;;;CAMrD,gBAAgB,OAAqB;AACnC,MAAI,QAAQ,EACV,OAAM,IAAI,MAAM,cAAc,MAAM,uBAAuB;AAG7D,MAAI,SAAS,KAAK,MAAM,OACtB,OAAM,IAAI,MACR,cAAc,MAAM,qBAAqB,KAAK,MAAM,SACrD;AAGH,MAAI,CAAC,KAAK,MAAM,OACd,OAAM,IAAI,MAAM,cAAc,MAAM,eAAe;AAGrD,SAAO,KAAK,MAAM;;;AAItB,yBAAe"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cappa/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Core Playwright screenshot functionality for Cappa",
|
|
5
5
|
"author": "Tim Richter",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/tim-richter/cappa.git"
|
|
9
|
+
},
|
|
6
10
|
"license": "MIT",
|
|
7
11
|
"publishConfig": {
|
|
8
12
|
"access": "public"
|
|
@@ -18,20 +22,20 @@
|
|
|
18
22
|
"./package.json": "./package.json"
|
|
19
23
|
},
|
|
20
24
|
"dependencies": {
|
|
21
|
-
"@blazediff/core": "^1.
|
|
25
|
+
"@blazediff/core": "^1.6.0",
|
|
22
26
|
"@blazediff/types": "^1.4.1",
|
|
23
|
-
"playwright-core": "^1.56.
|
|
27
|
+
"playwright-core": "^1.56.1",
|
|
24
28
|
"pngjs": "^7.0.0",
|
|
25
|
-
"@cappa/logger": "0.0.
|
|
29
|
+
"@cappa/logger": "0.0.5"
|
|
26
30
|
},
|
|
27
31
|
"devDependencies": {
|
|
28
|
-
"@types/node": "24.
|
|
32
|
+
"@types/node": "24.9.2",
|
|
29
33
|
"@types/pngjs": "^6.0.5",
|
|
30
|
-
"@vitest/coverage-v8": "
|
|
31
|
-
"@vitest/ui": "
|
|
32
|
-
"tsdown": "0.15.
|
|
34
|
+
"@vitest/coverage-v8": "4.0.6",
|
|
35
|
+
"@vitest/ui": "4.0.6",
|
|
36
|
+
"tsdown": "0.15.12",
|
|
33
37
|
"typescript": "5.9.3",
|
|
34
|
-
"vitest": "
|
|
38
|
+
"vitest": "4.0.6"
|
|
35
39
|
},
|
|
36
40
|
"keywords": [
|
|
37
41
|
"screenshot",
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { compareImages, imagesMatch } from "./compare";
|
|
1
2
|
import { defineConfig } from "./config";
|
|
2
3
|
import { ScreenshotFileSystem } from "./filesystem";
|
|
3
4
|
import type { Plugin, PluginDef, PluginFunction } from "./plugin";
|
|
@@ -23,6 +24,8 @@ export {
|
|
|
23
24
|
ScreenshotTool,
|
|
24
25
|
ScreenshotFileSystem,
|
|
25
26
|
defineConfig,
|
|
27
|
+
compareImages,
|
|
28
|
+
imagesMatch,
|
|
26
29
|
type PluginFunction,
|
|
27
30
|
type Plugin,
|
|
28
31
|
type PluginDef,
|
package/src/screenshot.ts
CHANGED
|
@@ -77,6 +77,7 @@ class ScreenshotTool {
|
|
|
77
77
|
logger: Logger;
|
|
78
78
|
retries: number;
|
|
79
79
|
filesystem: ScreenshotFileSystem;
|
|
80
|
+
logConsoleEvents: boolean;
|
|
80
81
|
|
|
81
82
|
constructor(options: {
|
|
82
83
|
browserType?: "chromium" | "firefox" | "webkit";
|
|
@@ -86,6 +87,7 @@ class ScreenshotTool {
|
|
|
86
87
|
diff?: DiffConfig;
|
|
87
88
|
retries?: number;
|
|
88
89
|
concurrency?: number;
|
|
90
|
+
logConsoleEvents?: boolean;
|
|
89
91
|
}) {
|
|
90
92
|
this.browserType = options.browserType || "chromium";
|
|
91
93
|
this.headless = options.headless !== false; // Default to headless
|
|
@@ -93,6 +95,7 @@ class ScreenshotTool {
|
|
|
93
95
|
this.outputDir = options.outputDir || "./screenshots";
|
|
94
96
|
this.diff = { ...defaultDiffConfig, ...options.diff };
|
|
95
97
|
this.concurrency = Math.max(1, options.concurrency || 1);
|
|
98
|
+
this.logConsoleEvents = options.logConsoleEvents ?? true;
|
|
96
99
|
|
|
97
100
|
this.logger = getLogger();
|
|
98
101
|
this.retries = options.retries || 2;
|
package/src/types.ts
CHANGED
|
@@ -89,6 +89,13 @@ export type UserConfig = {
|
|
|
89
89
|
* The number of parallel browser contexts to use for taking screenshots
|
|
90
90
|
*/
|
|
91
91
|
concurrency?: number;
|
|
92
|
+
/**
|
|
93
|
+
* Whether to log Playwright console events while executing capture tasks.
|
|
94
|
+
*
|
|
95
|
+
* Enabled by default to aid in debugging. Disable to reduce noise in the
|
|
96
|
+
* console output when you do not need the additional details.
|
|
97
|
+
*/
|
|
98
|
+
logConsoleEvents?: boolean;
|
|
92
99
|
/**
|
|
93
100
|
* An array of Cappa plugins used for generation.
|
|
94
101
|
* Each plugin may have additional configurable options (defined within the plugin itself).
|