@cappa/core 0.10.0 → 0.12.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/dist/index.d.cts CHANGED
@@ -1,5 +1,7 @@
1
+ import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/core-native";
1
2
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
2
3
  import { Logger } from "@cappa/logger";
4
+
3
5
  //#region src/compare/pixel.d.ts
4
6
  interface CompareResult$1 {
5
7
  numDiffPixels: number;
@@ -9,6 +11,7 @@ interface CompareResult$1 {
9
11
  passed: boolean;
10
12
  error?: string;
11
13
  differentSizes: boolean;
14
+ interpretation?: InterpretResult$1;
12
15
  }
13
16
  /**
14
17
  * Compare two PNG images and return the difference
@@ -29,6 +32,15 @@ declare function compareImages(image1: string | Buffer, image2: string | Buffer,
29
32
  declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
30
33
  //#endregion
31
34
  //#region src/filesystem.d.ts
35
+ /**
36
+ * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
37
+ */
38
+ declare function toDiffMetaPath(diffImagePath: string): string;
39
+ /**
40
+ * Read a diff metadata sidecar, returning `undefined` when it is missing or
41
+ * cannot be parsed (so callers can degrade gracefully).
42
+ */
43
+ declare function readDiffMeta(diffImagePath: string): Promise<DiffMetadata | undefined>;
32
44
  /**
33
45
  * Class for interacting with the local file system to store the screenshots.
34
46
  */
@@ -121,6 +133,14 @@ declare class ScreenshotFileSystem {
121
133
  * Write a file to the diff directory
122
134
  */
123
135
  writeDiffFile(filename: string, data: Buffer): Promise<void>;
136
+ /**
137
+ * Get the path to a diff metadata sidecar file (`<name>.json`)
138
+ */
139
+ getDiffMetaFilePath(filename: string): string;
140
+ /**
141
+ * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.
142
+ */
143
+ writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void>;
124
144
  /**
125
145
  * Check if an expected file exists
126
146
  */
@@ -381,6 +401,15 @@ interface DiffConfig {
381
401
  * this can mean that small changes still slip through.
382
402
  */
383
403
  maxDiffPercentage?: number;
404
+ /**
405
+ * Run structured interpretation after the raw pixel diff.
406
+ * Default = false
407
+ *
408
+ * When enabled, changed screenshots get a `diff/<name>.json` sidecar describing
409
+ * *what* changed (additions, deletions, color shifts) grouped into regions, with a
410
+ * human-readable summary and severity. Pixel diff only — ignored when `type: 'gmsd'`.
411
+ */
412
+ interpret?: boolean;
384
413
  }
385
414
  /**
386
415
  * Configuration for the comparison of images using GMSD
@@ -533,11 +562,29 @@ type DeletedScreenshot = {
533
562
  category: "deleted";
534
563
  expectedPath: string;
535
564
  };
565
+ /**
566
+ * Pixel-diff statistics and optional structured interpretation for a changed
567
+ * screenshot. Persisted as a `diff/<name>.json` sidecar next to the diff image
568
+ * and read back when the review UI / CLI rebuild state from disk.
569
+ */
570
+ interface DiffMetadata {
571
+ /** Number of differing pixels reported by the pixel diff. */
572
+ numDiffPixels: number;
573
+ /** Percentage of differing pixels (0-100). */
574
+ percentDifference: number;
575
+ /** Structured interpretation, present only when `diff.interpret` is enabled. */
576
+ interpretation?: InterpretResult$1;
577
+ }
536
578
  type ChangedScreenshot = {
537
579
  category: "changed";
538
580
  diffPath: string;
539
581
  actualPath: string;
540
582
  expectedPath: string;
583
+ /**
584
+ * Diff statistics and optional interpretation loaded from the
585
+ * `diff/<name>.json` sidecar. Absent if the sidecar was not written.
586
+ */
587
+ diffMeta?: DiffMetadata;
541
588
  };
542
589
  type PassedScreenshot = {
543
590
  category: "passed";
@@ -595,5 +642,5 @@ declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffe
595
642
  */
596
643
  declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
597
644
  //#endregion
598
- export { type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type NewScreenshot, type PassedScreenshot, 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, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD };
645
+ export { type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type InterpretResult, type NewScreenshot, type PassedScreenshot, 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, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, readDiffMeta, toDiffMetaPath };
599
646
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Logger } from "@cappa/logger";
2
+ import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/core-native";
2
3
  import { Browser, BrowserContext, Locator, Page } from "playwright-core";
3
4
 
4
5
  //#region src/compare/pixel.d.ts
@@ -10,6 +11,7 @@ interface CompareResult$1 {
10
11
  passed: boolean;
11
12
  error?: string;
12
13
  differentSizes: boolean;
14
+ interpretation?: InterpretResult$1;
13
15
  }
14
16
  /**
15
17
  * Compare two PNG images and return the difference
@@ -30,6 +32,15 @@ declare function compareImages(image1: string | Buffer, image2: string | Buffer,
30
32
  declare function imagesMatch(image1: string | Buffer, image2: string | Buffer, options?: DiffConfig): Promise<boolean>;
31
33
  //#endregion
32
34
  //#region src/filesystem.d.ts
35
+ /**
36
+ * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
37
+ */
38
+ declare function toDiffMetaPath(diffImagePath: string): string;
39
+ /**
40
+ * Read a diff metadata sidecar, returning `undefined` when it is missing or
41
+ * cannot be parsed (so callers can degrade gracefully).
42
+ */
43
+ declare function readDiffMeta(diffImagePath: string): Promise<DiffMetadata | undefined>;
33
44
  /**
34
45
  * Class for interacting with the local file system to store the screenshots.
35
46
  */
@@ -122,6 +133,14 @@ declare class ScreenshotFileSystem {
122
133
  * Write a file to the diff directory
123
134
  */
124
135
  writeDiffFile(filename: string, data: Buffer): Promise<void>;
136
+ /**
137
+ * Get the path to a diff metadata sidecar file (`<name>.json`)
138
+ */
139
+ getDiffMetaFilePath(filename: string): string;
140
+ /**
141
+ * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.
142
+ */
143
+ writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void>;
125
144
  /**
126
145
  * Check if an expected file exists
127
146
  */
@@ -382,6 +401,15 @@ interface DiffConfig {
382
401
  * this can mean that small changes still slip through.
383
402
  */
384
403
  maxDiffPercentage?: number;
404
+ /**
405
+ * Run structured interpretation after the raw pixel diff.
406
+ * Default = false
407
+ *
408
+ * When enabled, changed screenshots get a `diff/<name>.json` sidecar describing
409
+ * *what* changed (additions, deletions, color shifts) grouped into regions, with a
410
+ * human-readable summary and severity. Pixel diff only — ignored when `type: 'gmsd'`.
411
+ */
412
+ interpret?: boolean;
385
413
  }
386
414
  /**
387
415
  * Configuration for the comparison of images using GMSD
@@ -534,11 +562,29 @@ type DeletedScreenshot = {
534
562
  category: "deleted";
535
563
  expectedPath: string;
536
564
  };
565
+ /**
566
+ * Pixel-diff statistics and optional structured interpretation for a changed
567
+ * screenshot. Persisted as a `diff/<name>.json` sidecar next to the diff image
568
+ * and read back when the review UI / CLI rebuild state from disk.
569
+ */
570
+ interface DiffMetadata {
571
+ /** Number of differing pixels reported by the pixel diff. */
572
+ numDiffPixels: number;
573
+ /** Percentage of differing pixels (0-100). */
574
+ percentDifference: number;
575
+ /** Structured interpretation, present only when `diff.interpret` is enabled. */
576
+ interpretation?: InterpretResult$1;
577
+ }
537
578
  type ChangedScreenshot = {
538
579
  category: "changed";
539
580
  diffPath: string;
540
581
  actualPath: string;
541
582
  expectedPath: string;
583
+ /**
584
+ * Diff statistics and optional interpretation loaded from the
585
+ * `diff/<name>.json` sidecar. Absent if the sidecar was not written.
586
+ */
587
+ diffMeta?: DiffMetadata;
542
588
  };
543
589
  type PassedScreenshot = {
544
590
  category: "passed";
@@ -596,5 +642,5 @@ declare function imagesMatchGMSD(image1: string | Buffer, image2: string | Buffe
596
642
  */
597
643
  declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
598
644
  //#endregion
599
- export { type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type NewScreenshot, type PassedScreenshot, 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, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD };
645
+ export { type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type FailedScreenshot, type InterpretResult, type NewScreenshot, type PassedScreenshot, 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, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, readDiffMeta, toDiffMetaPath };
600
646
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -18,7 +18,7 @@ const pngSignature = Buffer.from([
18
18
  26,
19
19
  10
20
20
  ]);
21
- const crcTable = new Uint32Array(256).map((_, index) => {
21
+ const crcTable = (/* @__PURE__ */ new Uint32Array(256)).map((_, index) => {
22
22
  let c = index;
23
23
  for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
24
24
  return c >>> 0;
@@ -273,12 +273,13 @@ async function resolveInputPath(source, fileName, state) {
273
273
  await fsp.writeFile(dest, source);
274
274
  return dest;
275
275
  }
276
- function toNativeOptions(config) {
276
+ function toNativeOptions(config, withDiff) {
277
277
  const extra = config;
278
278
  const out = {
279
279
  threshold: extra.threshold,
280
280
  antialiasing: extra.includeAA ?? false
281
281
  };
282
+ if (extra.interpret && withDiff) out.interpret = true;
282
283
  if (extra.diffMask !== void 0) out.diffMask = extra.diffMask;
283
284
  if (extra.compression !== void 0) out.compression = extra.compression;
284
285
  if (extra.quality !== void 0) out.quality = extra.quality;
@@ -304,7 +305,7 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
304
305
  }
305
306
  let nativeResult;
306
307
  try {
307
- nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options));
308
+ nativeResult = await compare(p1, p2, withDiff ? diffPath : void 0, toNativeOptions(options, withDiff));
308
309
  } catch (error) {
309
310
  getLogger().error(error.message || "Unknown error");
310
311
  return {
@@ -349,7 +350,8 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
349
350
  percentDifference,
350
351
  diffBuffer,
351
352
  passed: isPassed(percentDifference, numDiffPixels, options),
352
- differentSizes: false
353
+ differentSizes: false,
354
+ interpretation: nativeResult.interpretation
353
355
  };
354
356
  } finally {
355
357
  if (state.tempRoot) await fsp.rm(state.tempRoot, {
@@ -437,6 +439,25 @@ async function mapWithConcurrency(concurrency, items, fn) {
437
439
  //#region src/filesystem.ts
438
440
  const APPROVE_SCREENSHOTS_CONCURRENCY = 8;
439
441
  /**
442
+ * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
443
+ */
444
+ function toDiffMetaPath(diffImagePath) {
445
+ const ext = path.extname(diffImagePath);
446
+ return ext ? `${diffImagePath.slice(0, -ext.length)}.json` : `${diffImagePath}.json`;
447
+ }
448
+ /**
449
+ * Read a diff metadata sidecar, returning `undefined` when it is missing or
450
+ * cannot be parsed (so callers can degrade gracefully).
451
+ */
452
+ async function readDiffMeta(diffImagePath) {
453
+ try {
454
+ const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), "utf8");
455
+ return JSON.parse(raw);
456
+ } catch {
457
+ return;
458
+ }
459
+ }
460
+ /**
440
461
  * Class for interacting with the local file system to store the screenshots.
441
462
  */
442
463
  var ScreenshotFileSystem = class {
@@ -503,7 +524,9 @@ var ScreenshotFileSystem = class {
503
524
  }
504
525
  if (screenshot.category === "changed") {
505
526
  logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);
506
- await fsp.unlink(path.resolve(outputDir, screenshot.diffPath));
527
+ const diffPath = path.resolve(outputDir, screenshot.diffPath);
528
+ await fsp.unlink(diffPath);
529
+ await fsp.rm(toDiffMetaPath(diffPath), { force: true });
507
530
  await this.approveFromActualPath(path.resolve(outputDir, screenshot.actualPath));
508
531
  return;
509
532
  }
@@ -543,6 +566,7 @@ var ScreenshotFileSystem = class {
543
566
  }
544
567
  await this.copyDiffMetadataToExpected(diffPath, expectedPath);
545
568
  await fsp.unlink(diffPath);
569
+ await fsp.rm(toDiffMetaPath(diffPath), { force: true });
546
570
  return {
547
571
  actualPath,
548
572
  expectedPath,
@@ -642,6 +666,20 @@ var ScreenshotFileSystem = class {
642
666
  await fsp.writeFile(filepath, data);
643
667
  }
644
668
  /**
669
+ * Get the path to a diff metadata sidecar file (`<name>.json`)
670
+ */
671
+ getDiffMetaFilePath(filename) {
672
+ return toDiffMetaPath(this.getDiffFilePath(filename));
673
+ }
674
+ /**
675
+ * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.
676
+ */
677
+ async writeDiffMetaFile(filename, meta) {
678
+ const filepath = this.getDiffMetaFilePath(filename);
679
+ await this.ensureParentDir(filepath);
680
+ await fsp.writeFile(filepath, JSON.stringify(meta));
681
+ }
682
+ /**
645
683
  * Check if an expected file exists
646
684
  */
647
685
  async hasExpectedFile(filename) {
@@ -765,12 +803,14 @@ var ScreenshotTool = class {
765
803
  webkit
766
804
  }[this.browserType];
767
805
  if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
768
- this.browser = await browserClass.launch({ headless: this.headless });
769
- const tempCtx = await this.browser.newContext();
806
+ const browser = await browserClass.launch({ headless: this.headless });
807
+ if (!browser) throw new Error("Something went wrong with starting the browser.");
808
+ this.browser = browser;
809
+ const tempCtx = await browser.newContext();
770
810
  const defaultUserAgent = await (await tempCtx.newPage()).evaluate(() => navigator.userAgent);
771
811
  await tempCtx.close();
772
812
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
773
- const context = await this.browser.newContext({
813
+ const context = await browser.newContext({
774
814
  reducedMotion: "reduce",
775
815
  deviceScaleFactor: 2,
776
816
  userAgent: `${defaultUserAgent} CappaStorybook`,
@@ -905,6 +945,12 @@ var ScreenshotTool = class {
905
945
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
906
946
  await this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
907
947
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
948
+ const result = retryScreenshot.comparisonResult;
949
+ if ("numDiffPixels" in result && result.interpretation) await this.filesystem.writeDiffMetaFile(diffFilename, {
950
+ numDiffPixels: result.numDiffPixels,
951
+ percentDifference: result.percentDifference,
952
+ interpretation: result.interpretation
953
+ });
908
954
  }
909
955
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
910
956
  this.logger.warn(`Screenshot has different sizes than reference image`);
@@ -1176,6 +1222,6 @@ var ScreenshotTool = class {
1176
1222
  }
1177
1223
  };
1178
1224
  //#endregion
1179
- export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD };
1225
+ export { ScreenshotFileSystem, ScreenshotTool, compareImages, compareImagesGMSD, defineConfig, imagesMatch, imagesMatchGMSD, readDiffMeta, toDiffMetaPath };
1180
1226
 
1181
1227
  //# sourceMappingURL=index.mjs.map