@cappa/core 0.0.27 → 0.1.1

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.
@@ -0,0 +1,358 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { PNG } from "pngjs";
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
5
+ import {
6
+ type CompareOptions,
7
+ type CompareResult,
8
+ compareImages,
9
+ imagesMatch,
10
+ saveDiffImage,
11
+ } from "./compare";
12
+
13
+ // Test utilities
14
+ function createSolidColorPNG(
15
+ width: number,
16
+ height: number,
17
+ color: [number, number, number, number] = [255, 0, 0, 255],
18
+ ): Buffer {
19
+ const png = new PNG({ width, height });
20
+
21
+ for (let y = 0; y < height; y++) {
22
+ for (let x = 0; x < width; x++) {
23
+ const idx = (width * y + x) << 2;
24
+ png.data[idx] = color[0]; // red
25
+ png.data[idx + 1] = color[1]; // green
26
+ png.data[idx + 2] = color[2]; // blue
27
+ png.data[idx + 3] = color[3]; // alpha
28
+ }
29
+ }
30
+
31
+ return PNG.sync.write(png);
32
+ }
33
+
34
+ function createGradientPNG(width: number, height: number): Buffer {
35
+ const png = new PNG({ width, height });
36
+
37
+ for (let y = 0; y < height; y++) {
38
+ for (let x = 0; x < width; x++) {
39
+ const idx = (width * y + x) << 2;
40
+ png.data[idx] = Math.floor((x / width) * 255); // red gradient
41
+ png.data[idx + 1] = Math.floor((y / height) * 255); // green gradient
42
+ png.data[idx + 2] = 128; // blue constant
43
+ png.data[idx + 3] = 255; // alpha
44
+ }
45
+ }
46
+
47
+ return PNG.sync.write(png);
48
+ }
49
+
50
+ function createCheckerboardPNG(
51
+ width: number,
52
+ height: number,
53
+ squareSize: number = 10,
54
+ ): Buffer {
55
+ const png = new PNG({ width, height });
56
+
57
+ for (let y = 0; y < height; y++) {
58
+ for (let x = 0; x < width; x++) {
59
+ const idx = (width * y + x) << 2;
60
+ const squareX = Math.floor(x / squareSize);
61
+ const squareY = Math.floor(y / squareSize);
62
+ const isWhite = (squareX + squareY) % 2 === 0;
63
+
64
+ const color = isWhite ? 255 : 0;
65
+ png.data[idx] = color; // red
66
+ png.data[idx + 1] = color; // green
67
+ png.data[idx + 2] = color; // blue
68
+ png.data[idx + 3] = 255; // alpha
69
+ }
70
+ }
71
+
72
+ return PNG.sync.write(png);
73
+ }
74
+
75
+ describe("compare", () => {
76
+ const testDir = path.join(__dirname, "__test-images__");
77
+
78
+ beforeAll(() => {
79
+ // Create test directory
80
+ if (!fs.existsSync(testDir)) {
81
+ fs.mkdirSync(testDir, { recursive: true });
82
+ }
83
+
84
+ // Create test image files
85
+ const redImage = createSolidColorPNG(100, 100, [255, 0, 0, 255]);
86
+ const blueImage = createSolidColorPNG(100, 100, [0, 0, 255, 255]);
87
+ const gradientImage = createGradientPNG(100, 100);
88
+ const checkerImage = createCheckerboardPNG(100, 100);
89
+ const smallImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
90
+
91
+ fs.writeFileSync(path.join(testDir, "red.png"), redImage);
92
+ fs.writeFileSync(path.join(testDir, "blue.png"), blueImage);
93
+ fs.writeFileSync(path.join(testDir, "gradient.png"), gradientImage);
94
+ fs.writeFileSync(path.join(testDir, "checker.png"), checkerImage);
95
+ fs.writeFileSync(path.join(testDir, "small.png"), smallImage);
96
+ });
97
+
98
+ afterAll(() => {
99
+ // Clean up test directory
100
+ if (fs.existsSync(testDir)) {
101
+ fs.rmSync(testDir, { recursive: true, force: true });
102
+ }
103
+ });
104
+
105
+ describe("compareImages", () => {
106
+ it("should return 0% difference for identical images", async () => {
107
+ const image = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
108
+
109
+ const result = await compareImages(image, image);
110
+
111
+ expect(result.numDiffPixels).toBe(0);
112
+ expect(result.totalPixels).toBe(2500);
113
+ expect(result.percentDifference).toBe(0);
114
+ expect(result.passed).toBe(true);
115
+ expect(result.diffBuffer).toEqual(undefined);
116
+ });
117
+
118
+ it("should return 100% difference for completely different images", async () => {
119
+ const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
120
+ const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
121
+
122
+ const result = await compareImages(redImage, blueImage);
123
+
124
+ expect(result.numDiffPixels).toBe(2500);
125
+ expect(result.totalPixels).toBe(2500);
126
+ expect(result.percentDifference).toBe(100);
127
+ expect(result.passed).toBe(false);
128
+ });
129
+
130
+ it("should work with file paths", async () => {
131
+ const redPath = path.join(testDir, "red.png");
132
+ const bluePath = path.join(testDir, "blue.png");
133
+
134
+ const result = await compareImages(redPath, bluePath);
135
+
136
+ expect(result.numDiffPixels).toBe(10000);
137
+ expect(result.totalPixels).toBe(10000);
138
+ expect(result.percentDifference).toBe(100);
139
+ expect(result.passed).toBe(false);
140
+ });
141
+
142
+ it("should work with mixed file path and buffer", async () => {
143
+ const redPath = path.join(testDir, "red.png");
144
+ const blueBuffer = createSolidColorPNG(100, 100, [0, 0, 255, 255]);
145
+
146
+ const result = await compareImages(redPath, blueBuffer);
147
+
148
+ expect(result.percentDifference).toBe(100);
149
+ expect(result.passed).toBe(false);
150
+ });
151
+
152
+ it("should respect maxDifferencePercent parameter", async () => {
153
+ const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
154
+ const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
155
+
156
+ const result1 = await compareImages(redImage, blueImage, false, {}, 50);
157
+ const result2 = await compareImages(redImage, blueImage, false, {}, 150);
158
+
159
+ expect(result1.passed).toBe(false); // 100% > 50%
160
+ expect(result2.passed).toBe(true); // 100% < 150%
161
+ });
162
+
163
+ it("should apply threshold option correctly", async () => {
164
+ // Create two slightly different images
165
+ const image1 = createSolidColorPNG(50, 50, [100, 100, 100, 255]);
166
+ const image2 = createSolidColorPNG(50, 50, [105, 105, 105, 255]); // Slightly lighter
167
+
168
+ const strictResult = await compareImages(image1, image2, false, {
169
+ threshold: 0.01,
170
+ });
171
+ const lenientResult = await compareImages(image1, image2, false, {
172
+ threshold: 0.5,
173
+ });
174
+
175
+ expect(strictResult.numDiffPixels).toBeGreaterThan(
176
+ lenientResult.numDiffPixels,
177
+ );
178
+ });
179
+
180
+ it("should throw error for mismatched dimensions", async () => {
181
+ const largeImage = createSolidColorPNG(100, 100, [255, 0, 0, 255]);
182
+ const smallImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
183
+
184
+ await expect(compareImages(largeImage, smallImage)).rejects.toThrow(
185
+ "Image sizes do not match. Image 1 size: 40000, image 2 size: 10000",
186
+ );
187
+ });
188
+
189
+ it("should handle custom compare options", async () => {
190
+ const image1 = createCheckerboardPNG(50, 50, 5);
191
+ const image2 = createCheckerboardPNG(50, 50, 6); // Slightly different pattern
192
+
193
+ const options: CompareOptions = {
194
+ threshold: 0.2,
195
+ includeAA: true,
196
+ alpha: 0.2,
197
+ aaColor: [0, 255, 0],
198
+ diffColor: [255, 0, 255],
199
+ diffColorAlt: [0, 255, 255],
200
+ };
201
+
202
+ const result = await compareImages(image1, image2, false, options);
203
+
204
+ expect(result).toBeDefined();
205
+ expect(result.diffBuffer).toEqual(undefined);
206
+ });
207
+
208
+ it("should handle identical file paths", async () => {
209
+ const redPath = path.join(testDir, "red.png");
210
+
211
+ const result = await compareImages(redPath, redPath);
212
+
213
+ expect(result.numDiffPixels).toBe(0);
214
+ expect(result.percentDifference).toBe(0);
215
+ expect(result.passed).toBe(true);
216
+ });
217
+ });
218
+
219
+ describe("imagesMatch", () => {
220
+ it("should return true for identical images", async () => {
221
+ const image = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
222
+
223
+ const matches = await imagesMatch(image, image);
224
+
225
+ expect(matches).toBe(true);
226
+ });
227
+
228
+ it("should return false for completely different images", async () => {
229
+ const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
230
+ const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
231
+
232
+ const matches = await imagesMatch(redImage, blueImage);
233
+
234
+ expect(matches).toBe(false);
235
+ });
236
+
237
+ it("should respect maxDifferencePercent", async () => {
238
+ const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
239
+ const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
240
+
241
+ const strictMatch = await imagesMatch(redImage, blueImage, 50);
242
+ const lenientMatch = await imagesMatch(redImage, blueImage, 150);
243
+
244
+ expect(strictMatch).toBe(false);
245
+ expect(lenientMatch).toBe(true);
246
+ });
247
+
248
+ it("should work with file paths", async () => {
249
+ const redPath = path.join(testDir, "red.png");
250
+ const checkerPath = path.join(testDir, "checker.png");
251
+
252
+ const matches = await imagesMatch(redPath, checkerPath);
253
+
254
+ expect(matches).toBe(false);
255
+ });
256
+
257
+ it("should pass through compare options", async () => {
258
+ const image1 = createSolidColorPNG(50, 50, [100, 100, 100, 255]);
259
+ const image2 = createSolidColorPNG(50, 50, [105, 105, 105, 255]);
260
+
261
+ const strictMatch = await imagesMatch(image1, image2, 50, {
262
+ threshold: 0.01,
263
+ });
264
+ const lenientMatch = await imagesMatch(image1, image2, 50, {
265
+ threshold: 0.5,
266
+ });
267
+
268
+ // With lenient threshold, more pixels should be considered "same"
269
+ expect(lenientMatch).toBe(true);
270
+ expect(strictMatch).toBe(false);
271
+ });
272
+ });
273
+
274
+ describe("saveDiffImage", () => {
275
+ it("should save diff image to file", async () => {
276
+ const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
277
+ const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
278
+
279
+ const result = await compareImages(redImage, blueImage, true);
280
+ const outputPath = path.join(testDir, "diff-output.png");
281
+
282
+ saveDiffImage(result, outputPath);
283
+
284
+ expect(fs.existsSync(outputPath)).toBe(true);
285
+
286
+ // Verify the saved file is a valid PNG
287
+ const savedBuffer = fs.readFileSync(outputPath);
288
+ expect(() => PNG.sync.read(savedBuffer)).not.toThrow();
289
+
290
+ // Clean up
291
+ fs.unlinkSync(outputPath);
292
+ });
293
+
294
+ it("should throw error when no diff buffer available", () => {
295
+ const result: CompareResult = {
296
+ numDiffPixels: 0,
297
+ totalPixels: 100,
298
+ percentDifference: 0,
299
+ passed: true,
300
+ // diffBuffer is undefined
301
+ };
302
+
303
+ expect(() => saveDiffImage(result, "test.png")).toThrow(
304
+ "No diff buffer available in comparison result",
305
+ );
306
+ });
307
+ });
308
+
309
+ describe("error handling", () => {
310
+ it("should handle non-existent file paths", async () => {
311
+ const nonExistentPath = path.join(testDir, "does-not-exist.png");
312
+ const validImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
313
+
314
+ await expect(
315
+ compareImages(nonExistentPath, validImage),
316
+ ).rejects.toThrow();
317
+ });
318
+
319
+ it("should handle invalid image buffers", async () => {
320
+ const invalidBuffer = Buffer.from("not a png");
321
+ const validImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
322
+
323
+ await expect(compareImages(invalidBuffer, validImage)).rejects.toThrow();
324
+ });
325
+ });
326
+
327
+ describe("edge cases", () => {
328
+ it("should handle 1x1 pixel images", async () => {
329
+ const image1 = createSolidColorPNG(1, 1, [255, 0, 0, 255]);
330
+ const image2 = createSolidColorPNG(1, 1, [0, 0, 255, 255]);
331
+
332
+ const result = await compareImages(image1, image2);
333
+
334
+ expect(result.totalPixels).toBe(1);
335
+ expect(result.numDiffPixels).toBe(1);
336
+ expect(result.percentDifference).toBe(100);
337
+ });
338
+
339
+ it("should handle very large difference percentages", async () => {
340
+ const redImage = createSolidColorPNG(10, 10, [255, 0, 0, 255]);
341
+ const blueImage = createSolidColorPNG(10, 10, [0, 0, 255, 255]);
342
+
343
+ const result = await compareImages(redImage, blueImage, false);
344
+
345
+ expect(result.passed).toBe(false);
346
+ expect(result.percentDifference).toBe(56.00000000000001);
347
+ });
348
+
349
+ it("should handle zero difference threshold", async () => {
350
+ const image = createSolidColorPNG(10, 10, [255, 0, 0, 255]);
351
+
352
+ const result = await compareImages(image, image, false, {}, 0);
353
+
354
+ expect(result.passed).toBe(true);
355
+ expect(result.percentDifference).toBe(0);
356
+ });
357
+ });
358
+ });
package/src/compare.ts ADDED
@@ -0,0 +1,118 @@
1
+ import fs from "node:fs";
2
+ import blazediff from "@blazediff/core";
3
+ import type { BlazeDiffOptions } from "@blazediff/types";
4
+ import { PNG } from "pngjs";
5
+ import type { DiffConfig } from "./types";
6
+
7
+ export type CompareOptions = BlazeDiffOptions;
8
+
9
+ export interface CompareResult {
10
+ numDiffPixels: number;
11
+ totalPixels: number;
12
+ percentDifference: number;
13
+ diffBuffer?: Buffer; // PNG buffer of the diff image
14
+ passed: boolean; // Whether the comparison passed based on threshold
15
+ }
16
+
17
+ const compare = (
18
+ image1: Uint8Array | Uint8ClampedArray,
19
+ image2: Uint8Array | Uint8ClampedArray,
20
+ diff: Uint8Array | Uint8ClampedArray | undefined,
21
+ width: number,
22
+ height: number,
23
+ options?: BlazeDiffOptions,
24
+ ) => {
25
+ return blazediff(image1, image2, diff, width, height, options);
26
+ };
27
+
28
+ /**
29
+ * Compare two PNG images and return the difference
30
+ * @param image1 - First image (file path or Buffer)
31
+ * @param image2 - Second image (file path or Buffer)
32
+ * @param withDiff - Whether to create a diff image
33
+ * @param options - Comparison options
34
+ * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
35
+ * @returns Comparison result
36
+ */
37
+ export async function compareImages(
38
+ image1: string | Buffer,
39
+ image2: string | Buffer,
40
+ withDiff: boolean = false,
41
+ options: DiffConfig,
42
+ ): Promise<CompareResult> {
43
+ // Load images as PNG objects
44
+ const png1 = await loadPNG(image1);
45
+ const png2 = await loadPNG(image2);
46
+
47
+ const { width, height } = png1;
48
+
49
+ // Create diff image
50
+ const diff = withDiff ? new PNG({ width, height }) : undefined;
51
+
52
+ // Compare images using pixelmatch
53
+ const numDiffPixels = compare(
54
+ png1.data,
55
+ png2.data,
56
+ diff?.data,
57
+ width,
58
+ height,
59
+ options,
60
+ );
61
+
62
+ const totalPixels = width * height;
63
+ const percentDifference = (numDiffPixels / totalPixels) * 100;
64
+ const passed = percentDifference <= (options.maxDiffPercentage || 0);
65
+
66
+ // Convert diff image to buffer
67
+ const diffBuffer = diff ? PNG.sync.write(diff) : undefined;
68
+
69
+ return {
70
+ numDiffPixels,
71
+ totalPixels,
72
+ percentDifference,
73
+ diffBuffer,
74
+ passed,
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Load a PNG image from file path or Buffer
80
+ */
81
+ async function loadPNG(source: string | Buffer): Promise<PNG> {
82
+ if (Buffer.isBuffer(source)) {
83
+ return PNG.sync.read(source);
84
+ } else {
85
+ const buffer = fs.readFileSync(source);
86
+ return PNG.sync.read(buffer);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Save a comparison result diff image to file
92
+ * @param result - Comparison result containing diffBuffer
93
+ * @param outputPath - Path to save the diff image
94
+ */
95
+ export function saveDiffImage(result: CompareResult, outputPath: string): void {
96
+ if (!result.diffBuffer) {
97
+ throw new Error("No diff buffer available in comparison result");
98
+ }
99
+
100
+ fs.writeFileSync(outputPath, result.diffBuffer);
101
+ }
102
+
103
+ /**
104
+ * Quick comparison function that returns only pass/fail
105
+ * @param image1 - First image (file path or Buffer)
106
+ * @param image2 - Second image (file path or Buffer)
107
+ * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
108
+ * @param options - Comparison options
109
+ * @returns Whether the images are similar enough
110
+ */
111
+ export async function imagesMatch(
112
+ image1: string | Buffer,
113
+ image2: string | Buffer,
114
+ options: DiffConfig,
115
+ ): Promise<boolean> {
116
+ const result = await compareImages(image1, image2, false, options);
117
+ return result.passed;
118
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import { defineConfig } from "./config";
2
2
  import type { Plugin, PluginDef, PluginFunction } from "./plugin";
3
3
  import ScreenshotTool from "./screenshot";
4
- import type { Exposed, ScreenshotOptions, UserConfig } from "./types";
4
+ import type {
5
+ Exposed,
6
+ Screenshot,
7
+ ScreenshotOptions,
8
+ UserConfig,
9
+ } from "./types";
5
10
 
6
11
  export {
7
12
  ScreenshotTool,
@@ -12,4 +17,5 @@ export {
12
17
  type UserConfig,
13
18
  type ScreenshotOptions,
14
19
  type Exposed,
20
+ type Screenshot,
15
21
  };