Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { PNG } from "pngjs";
import pixelmatch from "pixelmatch";
import fs from "fs";
 
const readFile = (path) => {
  return new Promise((resolve) => {
    fs.readFile(path, (err, file) => {
      if (err) return resolve(err);
      resolve({ path, file });
    });
  });
};
 
const runComparison = async (options) => {
  const files = await Promise.all([readFile(options.initialScreenshot), readFile(options.currentScreenshot)]).then(
    (files) => {
      return files.map((f) => {
        return {
          ...f,
          file: PNG.sync.read(f.file),
        };
      });
    },
  );
 
  const img1 = files.find(({ path }) => path.match("-orig")).file;
  const img2 = files.find(({ path }) => path.match("-comp")).file;
  const { width, height } = img1;
  const diff = new PNG({ width, height });
 
  const totalPixels = width * height;
 
  const changedPixels = pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, {
    threshold: options.threshold,
  });
  const changeRatio = changedPixels / totalPixels;
 
  // Add debug logging for CI troubleshooting
  console.log(
    `Screenshot comparison - Changed pixels: ${changedPixels}/${totalPixels} (${(changeRatio * 100).toFixed(2)}%), Threshold: ${options.threshold}, Operation: ${options.compare}`,
  );
 
  switch (options.compare) {
    case "shouldChange":
      return changeRatio > options.threshold;
    case "shouldNotChange":
      return changeRatio <= options.threshold;
  }
  return false;
};
 
export const compareScreenshots = (options) => {
  return runComparison(options);
};