@cappa/core 0.19.0 → 0.20.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.cjs CHANGED
@@ -2231,7 +2231,145 @@ var CaptureRunner = class {
2231
2231
  }
2232
2232
  };
2233
2233
  //#endregion
2234
+ //#region src/features/png/pixelRatio.ts
2235
+ /**
2236
+ * A screenshot's pixel ratio — image pixels per CSS pixel — stored in the PNG
2237
+ * itself.
2238
+ *
2239
+ * Kept in the file rather than beside it because `approve` is a plain copy:
2240
+ * the baseline carries the ratio it was captured at through approve, git and
2241
+ * CI artifacts with no bookkeeping.
2242
+ *
2243
+ * Two chunks, both before the image data:
2244
+ * - a `tEXt` chunk keyed `cappa:pixelRatio` — the source of truth. Only cappa
2245
+ * writes it, so an image another tool stamped with a DPI is never misread.
2246
+ * - a standard `pHYs` chunk, which image viewers read as DPI, so a 2×
2247
+ * screenshot opens at its CSS size in tools that honour it.
2248
+ *
2249
+ * Only written for ratios other than 1. A PNG without the key is 1×, which is
2250
+ * what every screenshot taken with `scale: "css"` is — so those stay
2251
+ * byte-for-byte what they were, and `fastBufferCheck` keeps matching them.
2252
+ */
2253
+ const PIXEL_RATIO_KEY = "cappa:pixelRatio";
2254
+ /** Pixels per metre at 96 DPI, the CSS reference pixel density. */
2255
+ const PPM_AT_1X = 96 / .0254;
2256
+ const IHDR_END = 33;
2257
+ /** Ancillary chunks before IDAT are few; bound every walk regardless. */
2258
+ const MAX_CHUNKS_BEFORE_IDAT = 64;
2259
+ const roundRatio = (ratio) => Math.round(ratio * 100) / 100;
2260
+ const createPhysChunk = (ratio) => {
2261
+ const ppm = Math.round(PPM_AT_1X * ratio);
2262
+ const chunk = Buffer.alloc(21);
2263
+ chunk.writeUInt32BE(9, 0);
2264
+ chunk.write("pHYs", 4, "ascii");
2265
+ chunk.writeUInt32BE(ppm, 8);
2266
+ chunk.writeUInt32BE(ppm, 12);
2267
+ chunk.writeUInt8(1, 16);
2268
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, 17)), 17);
2269
+ return chunk;
2270
+ };
2271
+ const isRatioText = (type, data) => type === "tEXt" && data.length > 16 && data.toString("latin1", 0, 17) === `cappa:pixelRatio\0`;
2272
+ const parseRatioText = (data) => {
2273
+ const value = Number(data.toString("latin1", 17));
2274
+ return Number.isFinite(value) && value > 0 ? roundRatio(value) : void 0;
2275
+ };
2276
+ /** The chunks between IHDR and the first IDAT. */
2277
+ function* chunksBeforeImage(buffer) {
2278
+ let offset = IHDR_END;
2279
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2280
+ if (offset + 8 > buffer.length) return;
2281
+ const length = buffer.readUInt32BE(offset);
2282
+ const type = buffer.toString("ascii", offset + 4, offset + 8);
2283
+ const end = offset + 12 + length;
2284
+ if (type === "IDAT" || type === "IEND" || end > buffer.length) return;
2285
+ yield {
2286
+ type,
2287
+ start: offset,
2288
+ end,
2289
+ data: buffer.subarray(offset + 8, offset + 8 + length)
2290
+ };
2291
+ offset = end;
2292
+ }
2293
+ }
2294
+ const hasIhdr = (buffer) => isValidPngSignature(buffer) && buffer.length >= IHDR_END && buffer.toString("ascii", 12, 16) === "IHDR";
2295
+ /**
2296
+ * Return `buffer` stamped with `ratio`, replacing any ratio it carried.
2297
+ *
2298
+ * Ratio 1 removes cappa's chunks instead (see above); a `pHYs` some other tool
2299
+ * wrote is left alone unless cappa is writing its own. Anything that is not a
2300
+ * PNG comes back untouched. No pixel data is re-encoded.
2301
+ */
2302
+ function withPixelRatio(buffer, ratio) {
2303
+ if (!hasIhdr(buffer)) return buffer;
2304
+ const stamp = ratio > 0 && roundRatio(ratio) !== 1;
2305
+ const chunks = [...chunksBeforeImage(buffer)];
2306
+ const ours = chunks.some((chunk) => isRatioText(chunk.type, chunk.data));
2307
+ if (!stamp && !ours) return buffer;
2308
+ const drop = chunks.filter((chunk) => isRatioText(chunk.type, chunk.data) || chunk.type === "pHYs" && (stamp || ours));
2309
+ const parts = [buffer.subarray(0, IHDR_END)];
2310
+ if (stamp) parts.push(createTextChunk(PIXEL_RATIO_KEY, String(roundRatio(ratio))), createPhysChunk(ratio));
2311
+ let copyFrom = IHDR_END;
2312
+ for (const chunk of drop) {
2313
+ parts.push(buffer.subarray(copyFrom, chunk.start));
2314
+ copyFrom = chunk.end;
2315
+ }
2316
+ parts.push(buffer.subarray(copyFrom));
2317
+ return Buffer.concat(parts);
2318
+ }
2319
+ async function readHead(path) {
2320
+ const fh = await (0, node_fs_promises.open)(path, "r");
2321
+ try {
2322
+ const head = Buffer.alloc(IHDR_END);
2323
+ const { bytesRead } = await fh.read(head, 0, IHDR_END, 0);
2324
+ if (bytesRead < IHDR_END || !hasIhdr(head)) return void 0;
2325
+ const parts = [head];
2326
+ const header = Buffer.alloc(8);
2327
+ let offset = IHDR_END;
2328
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2329
+ if ((await fh.read(header, 0, 8, offset)).bytesRead < 8) break;
2330
+ const length = header.readUInt32BE(0);
2331
+ const type = header.toString("ascii", 4, 8);
2332
+ if (type === "IDAT" || type === "IEND") break;
2333
+ const chunk = Buffer.alloc(12 + length);
2334
+ await fh.read(chunk, 0, chunk.length, offset);
2335
+ parts.push(chunk);
2336
+ offset += chunk.length;
2337
+ }
2338
+ return Buffer.concat(parts);
2339
+ } finally {
2340
+ await fh.close();
2341
+ }
2342
+ }
2343
+ /**
2344
+ * The pixel ratio a screenshot was captured at: 1 when the PNG carries no
2345
+ * ratio, and also when the file cannot be read — a missing ratio must never
2346
+ * break listing or comparing screenshots.
2347
+ */
2348
+ async function readPixelRatio(source) {
2349
+ try {
2350
+ const buffer = typeof source === "string" ? await readHead(source) : source;
2351
+ if (!buffer || !hasIhdr(buffer)) return 1;
2352
+ for (const chunk of chunksBeforeImage(buffer)) if (isRatioText(chunk.type, chunk.data)) return parseRatioText(chunk.data) ?? 1;
2353
+ return 1;
2354
+ } catch {
2355
+ return 1;
2356
+ }
2357
+ }
2358
+ const formatRatio = (ratio) => `${ratio}×`;
2359
+ /**
2360
+ * Why a screenshot cannot match its baseline when the two were captured at
2361
+ * different pixel ratios — `screenshot.scale` or `deviceScaleFactor` changed.
2362
+ */
2363
+ function describePixelRatioMismatch(expected, actual) {
2364
+ return `Baseline was captured at ${formatRatio(expected)} pixel ratio, this screenshot at ${formatRatio(actual)}, so their sizes cannot match. If the change of screenshot.scale or deviceScaleFactor is intended, approve the new screenshots; otherwise restore the previous setting.`;
2365
+ }
2366
+ //#endregion
2234
2367
  //#region src/screenshot.ts
2368
+ /**
2369
+ * `deviceScaleFactor` for contexts whose `contextOptions` set none. With the
2370
+ * default `scale: "css"` it only changes how the page renders, not the PNG.
2371
+ */
2372
+ const DEFAULT_DEVICE_SCALE_FACTOR = 2;
2235
2373
  const defaultPixelDiffConfig = {
2236
2374
  type: "pixel",
2237
2375
  threshold: .1,
@@ -2309,6 +2447,8 @@ var ScreenshotTool = class {
2309
2447
  fullPage;
2310
2448
  /** Default content crop; a screenshot's own `crop` overrides it. */
2311
2449
  crop;
2450
+ /** Default `scale`; a screenshot's own `scale` overrides it. */
2451
+ scale;
2312
2452
  outputDir;
2313
2453
  browser = null;
2314
2454
  context = null;
@@ -2349,6 +2489,7 @@ var ScreenshotTool = class {
2349
2489
  };
2350
2490
  this.fullPage = options.fullPage ?? true;
2351
2491
  this.crop = options.crop ?? false;
2492
+ this.scale = options.scale ?? "css";
2352
2493
  this.outputDir = options.outputDir || "./screenshots";
2353
2494
  this.diff = this.resolveDiffOptions(options.diff);
2354
2495
  this.concurrency = Math.max(1, options.concurrency || 1);
@@ -2490,7 +2631,7 @@ var ScreenshotTool = class {
2490
2631
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
2491
2632
  const context = await browser.newContext({
2492
2633
  reducedMotion: "reduce",
2493
- deviceScaleFactor: 2,
2634
+ deviceScaleFactor: DEFAULT_DEVICE_SCALE_FACTOR,
2494
2635
  ...extraContextOptions,
2495
2636
  userAgent: `${contextOptions?.userAgent ?? this.defaultUserAgent} CappaStorybook`,
2496
2637
  viewport: this.viewport
@@ -2614,21 +2755,33 @@ var ScreenshotTool = class {
2614
2755
  const clip = crop ? await measureContentClip(page, crop, fullPage) : void 0;
2615
2756
  if (crop && !clip) this.logger.debug(`Nothing painted inside "${crop.root}" to crop to; taking the uncropped screenshot`);
2616
2757
  const screenshotOptions = {
2617
- path: filepath,
2618
2758
  fullPage,
2619
2759
  clip,
2620
2760
  type: "png",
2621
2761
  timeout: 6e4,
2622
2762
  mask: options.mask,
2623
2763
  omitBackground: options.omitBackground,
2624
- scale: "css",
2764
+ scale: options.scale ?? this.scale,
2625
2765
  animations: "disabled",
2626
2766
  caret: "hide"
2627
2767
  };
2628
- return page.screenshot(screenshotOptions);
2768
+ const buffer = withPixelRatio(await page.screenshot(screenshotOptions), this.pixelRatioFor(options));
2769
+ if (filepath) await node_fs_promises.default.writeFile(filepath, buffer);
2770
+ return buffer;
2629
2771
  });
2630
2772
  }
2631
2773
  /**
2774
+ * Image pixels per CSS pixel for a screenshot taken with `options`: the
2775
+ * context's `deviceScaleFactor` with `scale: "device"`, else 1.
2776
+ *
2777
+ * Stamped into every PNG (see `features/png/pixelRatio.ts`) so a baseline
2778
+ * remembers the ratio it was captured at.
2779
+ */
2780
+ pixelRatioFor(options) {
2781
+ if ((options.scale ?? this.scale) !== "device") return 1;
2782
+ return this.browserConfig.provider.options.contextOptions?.deviceScaleFactor ?? DEFAULT_DEVICE_SCALE_FACTOR;
2783
+ }
2784
+ /**
2632
2785
  * Sets the viewport size and executes the action, ensuring the original viewport is restored
2633
2786
  * even if the action throws an error.
2634
2787
  */
@@ -2663,6 +2816,7 @@ var ScreenshotTool = class {
2663
2816
  const screenshotSettings = {
2664
2817
  fullPage: options.fullPage ?? this.fullPage,
2665
2818
  crop: options.crop,
2819
+ scale: options.scale,
2666
2820
  mask: options.mask,
2667
2821
  omitBackground: options.omitBackground,
2668
2822
  delay: options.delay,
@@ -2688,7 +2842,7 @@ var ScreenshotTool = class {
2688
2842
  });
2689
2843
  }
2690
2844
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
2691
- this.logger.warn(`Screenshot has different sizes than reference image`);
2845
+ if (!retryScreenshot.pixelRatio) this.logger.warn(`Screenshot has different sizes than reference image`);
2692
2846
  if (!diffImagePath) {
2693
2847
  const diffFilename = options.diffImageFilename || filename;
2694
2848
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
@@ -2700,7 +2854,8 @@ var ScreenshotTool = class {
2700
2854
  return {
2701
2855
  screenshotPath: filepath,
2702
2856
  comparisonResult: retryScreenshot.comparisonResult,
2703
- diffImagePath
2857
+ diffImagePath,
2858
+ ...retryScreenshot.pixelRatio ? { pixelRatio: retryScreenshot.pixelRatio } : {}
2704
2859
  };
2705
2860
  } catch (error) {
2706
2861
  this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
@@ -2709,19 +2864,27 @@ var ScreenshotTool = class {
2709
2864
  }
2710
2865
  async retryScreenshot(page, referenceImage, options, diffOverride) {
2711
2866
  const diffConfig = this.mergeDiffOptions(diffOverride);
2712
- for (let i = 0; i < this.retries; i++) try {
2867
+ const pixelRatio = {
2868
+ expected: await readPixelRatio(referenceImage),
2869
+ actual: this.pixelRatioFor(options)
2870
+ };
2871
+ const ratioMismatch = pixelRatio.expected !== pixelRatio.actual;
2872
+ if (ratioMismatch) this.logger.error(describePixelRatioMismatch(pixelRatio.expected, pixelRatio.actual));
2873
+ const attempts = ratioMismatch ? 1 : this.retries;
2874
+ for (let i = 0; i < attempts; i++) try {
2713
2875
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
2714
2876
  ...options,
2715
2877
  delay: this.getIncBackoffDelay(i, options.delay || 0)
2716
2878
  });
2717
2879
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
2718
2880
  const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
2719
- if (i === this.retries - 1 && !comparisonResult.passed) {
2720
- this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2881
+ if (i === attempts - 1 && !comparisonResult.passed) {
2882
+ if (!ratioMismatch) this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2721
2883
  return {
2722
2884
  screenshotPath: screenshotBuffer,
2723
2885
  comparisonResult,
2724
- passed: false
2886
+ passed: false,
2887
+ ...ratioMismatch ? { pixelRatio } : {}
2725
2888
  };
2726
2889
  }
2727
2890
  if (comparisonResult.passed) return {
@@ -3137,7 +3300,11 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3137
3300
  const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
3138
3301
  const expectedScreenshot = expectedByRelativePath.get(relativePath);
3139
3302
  const diffScreenshot = diffByRelativePath.get(relativePath);
3140
- const diffMeta = diffScreenshot ? await readDiffMeta(diffScreenshot) : void 0;
3303
+ const [diffMeta, actualPixelRatio, expectedPixelRatio] = await Promise.all([
3304
+ diffScreenshot ? readDiffMeta(diffScreenshot) : void 0,
3305
+ readPixelRatio(screenshot),
3306
+ expectedScreenshot ? readPixelRatio(expectedScreenshot) : 1
3307
+ ]);
3141
3308
  screenshotRepresentations.push({
3142
3309
  id,
3143
3310
  name,
@@ -3145,7 +3312,8 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3145
3312
  expectedPath: expectedScreenshot ? node_path.default.relative(outputDir, expectedScreenshot) : void 0,
3146
3313
  diffPath: diffScreenshot ? node_path.default.relative(outputDir, diffScreenshot) : void 0,
3147
3314
  actualPath: node_path.default.relative(outputDir, screenshot),
3148
- ...diffMeta ? { diffMeta } : {}
3315
+ ...diffMeta ? { diffMeta } : {},
3316
+ ...pixelRatios(actualPixelRatio, expectedPixelRatio)
3149
3317
  });
3150
3318
  }
3151
3319
  for (const expectedScreenshot of expectedScreenshots) {
@@ -3157,13 +3325,19 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
3157
3325
  id,
3158
3326
  name,
3159
3327
  category: "deleted",
3160
- expectedPath: node_path.default.relative(outputDir, expectedScreenshot)
3328
+ expectedPath: node_path.default.relative(outputDir, expectedScreenshot),
3329
+ ...pixelRatios(1, await readPixelRatio(expectedScreenshot))
3161
3330
  });
3162
3331
  }
3163
3332
  return screenshotRepresentations.sort((a, b) => {
3164
3333
  return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
3165
3334
  });
3166
3335
  };
3336
+ /** Ratios other than 1 only: absent means 1, which keeps 1× listings as they were. */
3337
+ const pixelRatios = (actual, expected) => ({
3338
+ ...actual !== 1 ? { actualPixelRatio: actual } : {},
3339
+ ...expected !== 1 ? { expectedPixelRatio: expected } : {}
3340
+ });
3167
3341
  const buildCategory = (expectedScreenshot, diffScreenshot) => {
3168
3342
  if (expectedScreenshot && diffScreenshot) return "changed";
3169
3343
  if (expectedScreenshot) return "passed";
@@ -4353,6 +4527,7 @@ var LocalEngine = class {
4353
4527
  logConsoleEvents: this.options.logConsoleEvents,
4354
4528
  fullPage: this.options.fullPage ?? true,
4355
4529
  crop: this.options.crop ?? false,
4530
+ scale: this.options.scale ?? "css",
4356
4531
  viewport: this.options.viewport ?? {
4357
4532
  width: 1920,
4358
4533
  height: 1080
@@ -5415,6 +5590,7 @@ exports.MANIFEST_FILENAME = MANIFEST_FILENAME;
5415
5590
  exports.MANIFEST_VERSION = MANIFEST_VERSION;
5416
5591
  exports.NO_WEB_SERVER_HINT = NO_WEB_SERVER_HINT;
5417
5592
  exports.OutputTail = OutputTail;
5593
+ exports.PIXEL_RATIO_KEY = PIXEL_RATIO_KEY;
5418
5594
  exports.RunInProgressError = RunInProgressError;
5419
5595
  exports.RunStore = RunStore;
5420
5596
  exports.ScreenshotFileSystem = ScreenshotFileSystem;
@@ -5436,6 +5612,7 @@ exports.compareImagesGMSD = compareImagesGMSD;
5436
5612
  exports.contextPadding = contextPadding;
5437
5613
  exports.defineConfig = defineConfig;
5438
5614
  exports.describeChange = describeChange;
5615
+ exports.describePixelRatioMismatch = describePixelRatioMismatch;
5439
5616
  exports.didScreenshotFail = didScreenshotFail;
5440
5617
  exports.ensurePlaywrightContainer = ensurePlaywrightContainer;
5441
5618
  exports.filterTasks = filterTasks;
@@ -5461,6 +5638,7 @@ exports.playwright = require_playwright.playwright;
5461
5638
  exports.readAgentReport = readAgentReport;
5462
5639
  exports.readCaptureManifest = readCaptureManifest;
5463
5640
  exports.readDiffMeta = readDiffMeta;
5641
+ exports.readPixelRatio = readPixelRatio;
5464
5642
  exports.recordCaptureOrigins = recordCaptureOrigins;
5465
5643
  exports.removePlaywrightContainers = removePlaywrightContainers;
5466
5644
  exports.renderJudgmentTiles = renderJudgmentTiles;
@@ -5481,6 +5659,7 @@ exports.toSerializedError = toSerializedError;
5481
5659
  exports.toSlimAgentReport = toSlimAgentReport;
5482
5660
  exports.toTaskStatus = toTaskStatus;
5483
5661
  exports.waitForUrl = waitForUrl;
5662
+ exports.withPixelRatio = withPixelRatio;
5484
5663
  exports.writeAgentVerdict = writeAgentVerdict;
5485
5664
 
5486
5665
  //# sourceMappingURL=index.cjs.map