@cappa/core 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,375 +0,0 @@
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 maxDiffPercentage 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, {
157
- maxDiffPercentage: 50,
158
- });
159
- const result2 = await compareImages(redImage, blueImage, false, {
160
- maxDiffPercentage: 100,
161
- });
162
-
163
- expect(result1.passed).toBe(false); // 100% > 50%
164
- expect(result2.passed).toBe(true); // 100% < 100%
165
- });
166
-
167
- it("should apply threshold option correctly", async () => {
168
- // Create two slightly different images
169
- const image1 = createSolidColorPNG(50, 50, [100, 100, 100, 255]);
170
- const image2 = createSolidColorPNG(50, 50, [105, 105, 105, 255]); // Slightly lighter
171
-
172
- const strictResult = await compareImages(image1, image2, false, {
173
- threshold: 0.01,
174
- });
175
- const lenientResult = await compareImages(image1, image2, false, {
176
- threshold: 0.5,
177
- });
178
-
179
- expect(strictResult.numDiffPixels).toBeGreaterThan(
180
- lenientResult.numDiffPixels,
181
- );
182
- });
183
-
184
- it("should throw error for mismatched dimensions", async () => {
185
- const largeImage = createSolidColorPNG(100, 100, [255, 0, 0, 255]);
186
- const smallImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
187
-
188
- const result = await compareImages(largeImage, smallImage);
189
-
190
- expect(result.differentSizes).toBe(true);
191
- expect(result.numDiffPixels).toBe(0);
192
- expect(result.totalPixels).toBe(0);
193
- expect(result.percentDifference).toBe(0);
194
- expect(result.passed).toBe(false);
195
- });
196
-
197
- it("should handle custom compare options", async () => {
198
- const image1 = createCheckerboardPNG(50, 50, 5);
199
- const image2 = createCheckerboardPNG(50, 50, 6); // Slightly different pattern
200
-
201
- const options: CompareOptions = {
202
- threshold: 0.2,
203
- includeAA: true,
204
- alpha: 0.2,
205
- aaColor: [0, 255, 0],
206
- diffColor: [255, 0, 255],
207
- diffColorAlt: [0, 255, 255],
208
- };
209
-
210
- const result = await compareImages(image1, image2, false, options);
211
-
212
- expect(result).toBeDefined();
213
- expect(result.diffBuffer).toEqual(undefined);
214
- });
215
-
216
- it("should handle identical file paths", async () => {
217
- const redPath = path.join(testDir, "red.png");
218
-
219
- const result = await compareImages(redPath, redPath);
220
-
221
- expect(result.numDiffPixels).toBe(0);
222
- expect(result.percentDifference).toBe(0);
223
- expect(result.passed).toBe(true);
224
- });
225
- });
226
-
227
- describe("imagesMatch", () => {
228
- it("should return true for identical images", async () => {
229
- const image = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
230
-
231
- const matches = await imagesMatch(image, image);
232
-
233
- expect(matches).toBe(true);
234
- });
235
-
236
- it("should return false for completely different images", async () => {
237
- const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
238
- const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
239
-
240
- const matches = await imagesMatch(redImage, blueImage);
241
-
242
- expect(matches).toBe(false);
243
- });
244
-
245
- it("should respect maxDifferencePercent", async () => {
246
- const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
247
- const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
248
-
249
- const strictMatch = await imagesMatch(redImage, blueImage, {
250
- maxDiffPercentage: 50,
251
- });
252
- const lenientMatch = await imagesMatch(redImage, blueImage, {
253
- maxDiffPercentage: 150,
254
- });
255
-
256
- expect(strictMatch).toBe(false);
257
- expect(lenientMatch).toBe(true);
258
- });
259
-
260
- it("should work with file paths", async () => {
261
- const redPath = path.join(testDir, "red.png");
262
- const checkerPath = path.join(testDir, "checker.png");
263
-
264
- const matches = await imagesMatch(redPath, checkerPath);
265
-
266
- expect(matches).toBe(false);
267
- });
268
-
269
- it("should pass through compare options", async () => {
270
- const image1 = createSolidColorPNG(50, 50, [100, 100, 100, 255]);
271
- const image2 = createSolidColorPNG(50, 50, [105, 105, 105, 255]);
272
-
273
- const strictMatch = await imagesMatch(image1, image2, {
274
- maxDiffPercentage: 50,
275
- threshold: 0.01,
276
- });
277
- const lenientMatch = await imagesMatch(image1, image2, {
278
- maxDiffPercentage: 50,
279
- threshold: 0.5,
280
- });
281
-
282
- // With lenient threshold, more pixels should be considered "same"
283
- expect(lenientMatch).toBe(true);
284
- expect(strictMatch).toBe(false);
285
- });
286
- });
287
-
288
- describe("saveDiffImage", () => {
289
- it("should save diff image to file", async () => {
290
- const redImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
291
- const blueImage = createSolidColorPNG(50, 50, [0, 0, 255, 255]);
292
-
293
- const result = await compareImages(redImage, blueImage, true);
294
- const outputPath = path.join(testDir, "diff-output.png");
295
-
296
- saveDiffImage(result, outputPath);
297
-
298
- expect(fs.existsSync(outputPath)).toBe(true);
299
-
300
- // Verify the saved file is a valid PNG
301
- const savedBuffer = fs.readFileSync(outputPath);
302
- expect(() => PNG.sync.read(savedBuffer)).not.toThrow();
303
-
304
- // Clean up
305
- fs.unlinkSync(outputPath);
306
- });
307
-
308
- it("should throw error when no diff buffer available", () => {
309
- const result: CompareResult = {
310
- numDiffPixels: 0,
311
- totalPixels: 100,
312
- percentDifference: 0,
313
- passed: true,
314
- differentSizes: false,
315
- // diffBuffer is undefined
316
- };
317
-
318
- expect(() => saveDiffImage(result, "test.png")).toThrow(
319
- "No diff buffer available in comparison result",
320
- );
321
- });
322
- });
323
-
324
- describe("error handling", () => {
325
- it("should handle non-existent file paths", async () => {
326
- const nonExistentPath = path.join(testDir, "does-not-exist.png");
327
- const validImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
328
-
329
- await expect(
330
- compareImages(nonExistentPath, validImage),
331
- ).rejects.toThrow();
332
- });
333
-
334
- it("should handle invalid image buffers", async () => {
335
- const invalidBuffer = Buffer.from("not a png");
336
- const validImage = createSolidColorPNG(50, 50, [255, 0, 0, 255]);
337
-
338
- await expect(compareImages(invalidBuffer, validImage)).rejects.toThrow();
339
- });
340
- });
341
-
342
- describe("edge cases", () => {
343
- it("should handle 1x1 pixel images", async () => {
344
- const image1 = createSolidColorPNG(1, 1, [255, 0, 0, 255]);
345
- const image2 = createSolidColorPNG(1, 1, [0, 0, 255, 255]);
346
-
347
- const result = await compareImages(image1, image2);
348
-
349
- expect(result.totalPixels).toBe(1);
350
- expect(result.numDiffPixels).toBe(1);
351
- expect(result.percentDifference).toBe(100);
352
- });
353
-
354
- it("should handle very large difference percentages", async () => {
355
- const redImage = createSolidColorPNG(10, 10, [255, 0, 0, 255]);
356
- const blueImage = createSolidColorPNG(10, 10, [0, 0, 255, 255]);
357
-
358
- const result = await compareImages(redImage, blueImage, false);
359
-
360
- expect(result.passed).toBe(false);
361
- expect(result.percentDifference).toBe(100);
362
- });
363
-
364
- it("should handle zero difference threshold", async () => {
365
- const image = createSolidColorPNG(10, 10, [255, 0, 0, 255]);
366
-
367
- const result = await compareImages(image, image, false, {
368
- maxDiffPercentage: 0,
369
- });
370
-
371
- expect(result.passed).toBe(true);
372
- expect(result.percentDifference).toBe(0);
373
- });
374
- });
375
- });
package/src/compare.ts DELETED
@@ -1,191 +0,0 @@
1
- import fs from "node:fs";
2
- import blazediff from "@blazediff/core";
3
- import type { BlazeDiffOptions } from "@blazediff/types";
4
- import { getLogger } from "@cappa/logger";
5
- import { PNG } from "pngjs";
6
- import type { DiffConfig } from "./types";
7
-
8
- export type CompareOptions = BlazeDiffOptions;
9
-
10
- export interface CompareResult {
11
- numDiffPixels: number;
12
- totalPixels: number;
13
- percentDifference: number;
14
- diffBuffer?: Buffer; // PNG buffer of the diff image
15
- passed: boolean; // Whether the comparison passed based on threshold
16
- error?: string; // Error message if the comparison failed
17
- differentSizes: boolean; // Whether the images have different sizes
18
- }
19
-
20
- const compare = (
21
- image1: Uint8Array | Uint8ClampedArray,
22
- image2: Uint8Array | Uint8ClampedArray,
23
- diff: Uint8Array | Uint8ClampedArray | undefined,
24
- width: number,
25
- height: number,
26
- options?: BlazeDiffOptions,
27
- ) => {
28
- return blazediff(image1, image2, diff, width, height, options);
29
- };
30
-
31
- /**
32
- * Compare two PNG images and return the difference
33
- * @param image1 - First image (file path or Buffer)
34
- * @param image2 - Second image (file path or Buffer)
35
- * @param withDiff - Whether to create a diff image
36
- * @param options - Comparison options
37
- * @returns Comparison result
38
- */
39
- export async function compareImages(
40
- image1: string | Buffer,
41
- image2: string | Buffer,
42
- withDiff: boolean = false,
43
- options: DiffConfig = {},
44
- ): Promise<CompareResult> {
45
- const png1 = await loadPNG(image1);
46
- const png2 = await loadPNG(image2);
47
-
48
- const { width, height } = png1;
49
-
50
- if (width !== png2.width || height !== png2.height) {
51
- return {
52
- numDiffPixels: 0,
53
- totalPixels: 0,
54
- percentDifference: 0,
55
- passed: false,
56
- differentSizes: true,
57
- };
58
- }
59
-
60
- const diff = withDiff ? new PNG({ width, height }) : undefined;
61
-
62
- try {
63
- const numDiffPixels = compare(
64
- png1.data,
65
- png2.data,
66
- diff?.data,
67
- width,
68
- height,
69
- options,
70
- );
71
-
72
- const totalPixels = width * height;
73
- const percentDifference = (numDiffPixels / totalPixels) * 100;
74
-
75
- // Convert diff image to buffer
76
- const diffBuffer = diff ? PNG.sync.write(diff) : undefined;
77
-
78
- return {
79
- numDiffPixels,
80
- totalPixels,
81
- percentDifference,
82
- diffBuffer,
83
- passed: isPassed(percentDifference, numDiffPixels, options),
84
- differentSizes: false,
85
- };
86
- } catch (error) {
87
- getLogger().error((error as Error).message || "Unknown error");
88
-
89
- return {
90
- numDiffPixels: 0,
91
- totalPixels: 0,
92
- percentDifference: 0,
93
- passed: false,
94
- differentSizes: false,
95
- error: (error as Error).message || "Unknown error",
96
- };
97
- }
98
- }
99
-
100
- /**
101
- * Load a PNG image from file path or Buffer
102
- */
103
- async function loadPNG(source: string | Buffer): Promise<PNG> {
104
- if (Buffer.isBuffer(source)) {
105
- return PNG.sync.read(source);
106
- } else {
107
- const buffer = fs.readFileSync(source);
108
- return PNG.sync.read(buffer);
109
- }
110
- }
111
-
112
- /**
113
- * Save a comparison result diff image to file
114
- * @param result - Comparison result containing diffBuffer
115
- * @param outputPath - Path to save the diff image
116
- */
117
- export function saveDiffImage(result: CompareResult, outputPath: string): void {
118
- if (!result.diffBuffer) {
119
- throw new Error("No diff buffer available in comparison result");
120
- }
121
-
122
- fs.writeFileSync(outputPath, result.diffBuffer);
123
- }
124
-
125
- /**
126
- * Quick comparison function that returns only pass/fail
127
- * @param image1 - First image (file path or Buffer)
128
- * @param image2 - Second image (file path or Buffer)
129
- * @param options - Comparison options
130
- * @returns Whether the images match
131
- */
132
- export async function imagesMatch(
133
- image1: string | Buffer,
134
- image2: string | Buffer,
135
- options: DiffConfig = {},
136
- ): Promise<boolean> {
137
- const result = await compareImages(image1, image2, false, options);
138
-
139
- return result.passed;
140
- }
141
-
142
- /**
143
- * Check if the comparison passed based on the options
144
- * @param percentDifference - Percentage difference between the images
145
- * @param numDiffPixels - Number of different pixels
146
- * @param options - Comparison options
147
- * @returns Whether the comparison passed
148
- */
149
- const isPassed = (
150
- percentDifference: number,
151
- numDiffPixels: number,
152
- options: DiffConfig,
153
- ) => {
154
- if (options.maxDiffPercentage && options.maxDiffPixels) {
155
- return (
156
- percentDifference <= options.maxDiffPercentage &&
157
- numDiffPixels <= options.maxDiffPixels
158
- );
159
- }
160
-
161
- if (options.maxDiffPercentage) {
162
- return percentDifference <= options.maxDiffPercentage;
163
- }
164
-
165
- if (options.maxDiffPixels) {
166
- return numDiffPixels <= options.maxDiffPixels;
167
- }
168
-
169
- // fallback to 0 pixels
170
- return numDiffPixels === 0;
171
- };
172
-
173
- /**
174
- * Create different size png image with all pixels red
175
- * @returns
176
- */
177
- export function createDiffSizePngImage(width: number, height: number): Buffer {
178
- const png = new PNG({ width, height });
179
-
180
- for (let y = 0; y < height; y++) {
181
- for (let x = 0; x < width; x++) {
182
- const idx = (width * y + x) << 2;
183
- png.data[idx] = 255; // red
184
- png.data[idx + 1] = 0; // green
185
- png.data[idx + 2] = 0; // blue
186
- png.data[idx + 3] = 255; // alpha
187
- }
188
- }
189
-
190
- return PNG.sync.write(png);
191
- }
package/src/config.ts DELETED
@@ -1,12 +0,0 @@
1
- import type { ConfigEnv, PossiblePromise, UserConfig } from "./types";
2
-
3
- /**
4
- * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
5
- */
6
- export function defineConfig(
7
- options:
8
- | PossiblePromise<UserConfig>
9
- | ((env: ConfigEnv) => PossiblePromise<UserConfig>),
10
- ): typeof options {
11
- return options;
12
- }
@@ -1,83 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
- import { ScreenshotFileSystem } from "./filesystem";
6
-
7
- let tempDir: string;
8
-
9
- beforeEach(() => {
10
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "cappa-fs-"));
11
- fs.mkdirSync(path.join(tempDir, "actual"), { recursive: true });
12
- fs.mkdirSync(path.join(tempDir, "expected"), { recursive: true });
13
- fs.mkdirSync(path.join(tempDir, "diff"), { recursive: true });
14
- });
15
-
16
- afterEach(() => {
17
- fs.rmSync(tempDir, { recursive: true, force: true });
18
- });
19
-
20
- describe("ScreenshotFileSystem", () => {
21
- it("clears existing actual and diff directories", () => {
22
- const fileSystem = new ScreenshotFileSystem(tempDir);
23
-
24
- const actualFile = path.join(tempDir, "actual", "example.png");
25
- const diffFile = path.join(tempDir, "diff", "example.png");
26
-
27
- fs.writeFileSync(actualFile, "actual");
28
- fs.writeFileSync(diffFile, "diff");
29
-
30
- fileSystem.clearActual();
31
- fileSystem.clearDiff();
32
-
33
- expect(fs.existsSync(path.join(tempDir, "actual"))).toBe(false);
34
- expect(fs.existsSync(path.join(tempDir, "diff"))).toBe(false);
35
- });
36
-
37
- it("approves screenshots from absolute actual paths and removes diffs", () => {
38
- const fileSystem = new ScreenshotFileSystem(tempDir);
39
-
40
- const actualPath = path.join(tempDir, "actual", "component", "button.png");
41
- const expectedPath = path.join(
42
- tempDir,
43
- "expected",
44
- "component",
45
- "button.png",
46
- );
47
- const diffPath = path.join(tempDir, "diff", "component", "button.png");
48
-
49
- fs.mkdirSync(path.dirname(actualPath), { recursive: true });
50
- fs.mkdirSync(path.dirname(diffPath), { recursive: true });
51
-
52
- fs.writeFileSync(actualPath, "button");
53
- fs.writeFileSync(diffPath, "diff");
54
-
55
- const result = fileSystem.approveFromActualPath(actualPath);
56
-
57
- expect(fs.readFileSync(expectedPath, "utf-8")).toBe("button");
58
- expect(fs.existsSync(diffPath)).toBe(false);
59
- expect(result).toEqual({
60
- actualPath,
61
- expectedPath,
62
- diffPath,
63
- });
64
- });
65
-
66
- it("approves screenshots by logical name", () => {
67
- const fileSystem = new ScreenshotFileSystem(tempDir);
68
-
69
- const actualPath = path.join(
70
- tempDir,
71
- "actual",
72
- "pages",
73
- "home",
74
- "hero.png",
75
- );
76
- fs.mkdirSync(path.dirname(actualPath), { recursive: true });
77
- fs.writeFileSync(actualPath, "hero");
78
-
79
- const { expectedPath } = fileSystem.approveByName("pages/home/hero");
80
-
81
- expect(fs.readFileSync(expectedPath, "utf-8")).toBe("hero");
82
- });
83
- });