@cappa/core 0.18.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.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import fs from "node:fs";
1
+ import { DEFAULT_CONTAINER_IMAGE, playwright, resolveBrowserConfig, resolveContainerOptions } from "./playwright.mjs";
2
+ import { createRequire } from "node:module";
3
+ import fs, { realpathSync } from "node:fs";
2
4
  import gmsd from "@blazediff/gmsd";
3
5
  import { getLogger } from "@cappa/logger";
4
6
  import fsp, { glob, open, readFile, writeFile } from "node:fs/promises";
@@ -7,9 +9,9 @@ import os from "node:os";
7
9
  import path, { relative } from "node:path";
8
10
  import { compare } from "@blazediff/core-native";
9
11
  import { interpret } from "@blazediff/interpret-native";
12
+ import { execFile, execFileSync, spawn } from "node:child_process";
10
13
  import { createHash, randomUUID } from "node:crypto";
11
14
  import { chromium, firefox, webkit } from "playwright-core";
12
- import { execFile, execFileSync, spawn } from "node:child_process";
13
15
  //#region \0rolldown/runtime.js
14
16
  var __defProp = Object.defineProperty;
15
17
  var __exportAll = (all, no_symbols) => {
@@ -683,6 +685,242 @@ const attachConsoleLogging = (page, setting, logger) => {
683
685
  });
684
686
  };
685
687
  //#endregion
688
+ //#region src/container.ts
689
+ /**
690
+ * Runs the official Playwright image for an exact `playwright-core` version
691
+ * through a container CLI (docker, podman, nerdctl, …) and hands back the
692
+ * `run-server` endpoint.
693
+ *
694
+ * Only subcommands all of those CLIs share are used: `version`, `image
695
+ * inspect`, `pull`, `inspect`, `run`, `port`, `logs`, `ps` and `rm`.
696
+ */
697
+ /** Label on every container cappa starts; `removePlaywrightContainers` finds them by it. */
698
+ const CONTAINER_LABEL = "dev.cappa.playwright";
699
+ /** Port `run-server` listens on inside the container. */
700
+ const SERVER_PORT = 3e3;
701
+ /** Where the host's `playwright-core` is mounted inside the container. */
702
+ const PACKAGE_MOUNT = "/opt/playwright-core";
703
+ const defaultExec = (file, args) => new Promise((resolve, reject) => {
704
+ execFile(file, args, {
705
+ maxBuffer: 16777216,
706
+ windowsHide: true
707
+ }, (error, stdout, stderr) => {
708
+ if (error) reject(Object.assign(error, {
709
+ stdout,
710
+ stderr
711
+ }));
712
+ else resolve({
713
+ stdout: String(stdout),
714
+ stderr: String(stderr)
715
+ });
716
+ });
717
+ });
718
+ /** `true` once `run-server` answers plain HTTP with `Running`. */
719
+ const defaultProbe = async (url) => {
720
+ try {
721
+ const response = await fetch(url, { signal: AbortSignal.timeout(2e3) });
722
+ return response.ok && (await response.text()).includes("Running");
723
+ } catch {
724
+ return false;
725
+ }
726
+ };
727
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
728
+ const errorText = (error) => {
729
+ const stderr = error?.stderr;
730
+ if (typeof stderr === "string" && stderr.trim()) return stderr.trim();
731
+ return error instanceof Error ? error.message : String(error);
732
+ };
733
+ const isNotFound = (error) => error?.code === "ENOENT";
734
+ /** `{version}` filled in. */
735
+ const containerImage = (image, version) => image.replaceAll("{version}", version);
736
+ /**
737
+ * Deterministic per version, image and run arguments: changing any of them
738
+ * starts a fresh container instead of reusing one with stale settings.
739
+ */
740
+ const containerName = (version, image, runArgs, packageDir = "") => {
741
+ const hash = createHash("sha256").update(JSON.stringify([
742
+ image,
743
+ runArgs,
744
+ packageDir
745
+ ])).digest("hex").slice(0, 8);
746
+ return `cappa-playwright-v${version.replace(/[^\w.-]/g, "_")}-${hash}`;
747
+ };
748
+ /** Host port from `<cli> port` output (`127.0.0.1:49153`, maybe several lines). */
749
+ const parsePort = (output) => {
750
+ for (const line of output.split("\n")) {
751
+ const match = line.trim().match(/:(\d+)$/);
752
+ if (match) return Number(match[1]);
753
+ }
754
+ return null;
755
+ };
756
+ /**
757
+ * Start — or reuse — the Playwright server container for `version` and wait
758
+ * until it accepts connections.
759
+ */
760
+ async function ensurePlaywrightContainer(options) {
761
+ const { version, packageDir, cli, runArgs, readyTimeout, log = () => {}, exec = defaultExec, probe = defaultProbe, sleep = defaultSleep, now = Date.now } = options;
762
+ const image = containerImage(options.image, version);
763
+ const name = containerName(version, image, runArgs, packageDir);
764
+ const deadline = now() + readyTimeout;
765
+ const run = async (args) => {
766
+ try {
767
+ return await exec(cli, args);
768
+ } catch (error) {
769
+ if (isNotFound(error)) throw new Error(`Container CLI "${cli}" not found. Install it, or set playwright({ container: { cli } }) / CAPPA_CONTAINER_CLI to the one you use (docker, podman, nerdctl).`, { cause: error });
770
+ throw error;
771
+ }
772
+ };
773
+ try {
774
+ await run(["version"]);
775
+ } catch (error) {
776
+ if (error instanceof Error && error.message.startsWith("Container CLI")) throw error;
777
+ throw new Error(`"${cli} version" failed.${cli === "podman" ? " Is the podman machine running (`podman machine start`)?" : " Is the daemon running?"}\n\n${errorText(error)}`, { cause: error });
778
+ }
779
+ const state = async () => {
780
+ try {
781
+ const { stdout } = await run([
782
+ "inspect",
783
+ "--format",
784
+ "{{.State.Running}}",
785
+ name
786
+ ]);
787
+ return stdout.trim() === "true" ? "running" : "stopped";
788
+ } catch {
789
+ return "absent";
790
+ }
791
+ };
792
+ const remove = async () => {
793
+ await run([
794
+ "rm",
795
+ "-f",
796
+ name
797
+ ]).catch(() => {});
798
+ };
799
+ const stop = async () => {
800
+ await remove();
801
+ };
802
+ let reused = false;
803
+ const current = await state();
804
+ if (current === "running") {
805
+ reused = true;
806
+ log(`Reusing Playwright container ${name}`);
807
+ } else {
808
+ if (current === "stopped") await remove();
809
+ if (!await run([
810
+ "image",
811
+ "inspect",
812
+ image
813
+ ]).then(() => true, () => false)) {
814
+ log(`Pulling ${image} (first run only; this can take a few minutes)`);
815
+ try {
816
+ await run(["pull", image]);
817
+ } catch (error) {
818
+ throw new Error(`Could not pull ${image}. Official images exist for every released Playwright version — check that playwright-core ${version} is a release (not a prerelease) and that the registry is reachable.\n\n${errorText(error)}`, { cause: error });
819
+ }
820
+ }
821
+ log(`Starting Playwright ${version} container ${name}`);
822
+ try {
823
+ await run([
824
+ "run",
825
+ "-d",
826
+ "--init",
827
+ "--ipc=host",
828
+ "--user",
829
+ "pwuser",
830
+ "--workdir",
831
+ "/home/pwuser",
832
+ "-p",
833
+ `127.0.0.1::${SERVER_PORT}`,
834
+ "--mount",
835
+ `type=bind,source=${packageDir},target=${PACKAGE_MOUNT},readonly`,
836
+ "--label",
837
+ `${CONTAINER_LABEL}=${version}`,
838
+ "--name",
839
+ name,
840
+ ...runArgs,
841
+ image,
842
+ "node",
843
+ `${PACKAGE_MOUNT}/cli.js`,
844
+ "run-server",
845
+ "--port",
846
+ String(SERVER_PORT),
847
+ "--host",
848
+ "0.0.0.0"
849
+ ]);
850
+ } catch (error) {
851
+ if (/already in use|conflict|already exists/i.test(errorText(error))) reused = true;
852
+ else throw new Error(`Could not start ${image}.\n\n${errorText(error)}`, { cause: error });
853
+ }
854
+ }
855
+ const containerLogs = async () => {
856
+ const result = await run([
857
+ "logs",
858
+ "--tail",
859
+ "30",
860
+ name
861
+ ]).catch(() => null);
862
+ return result ? `${result.stdout}${result.stderr}`.trim() : "";
863
+ };
864
+ let port = null;
865
+ let attempt = 0;
866
+ while (true) {
867
+ if (port === null) {
868
+ const output = await run([
869
+ "port",
870
+ name,
871
+ `${SERVER_PORT}/tcp`
872
+ ]).then((r) => r.stdout, () => "");
873
+ port = parsePort(output);
874
+ }
875
+ if (port !== null && await probe(`http://127.0.0.1:${port}/`)) return {
876
+ wsEndpoint: `ws://127.0.0.1:${port}/`,
877
+ name,
878
+ image,
879
+ reused,
880
+ stop
881
+ };
882
+ attempt++;
883
+ if (attempt % 8 === 0 && await state() !== "running") {
884
+ const logs = await containerLogs();
885
+ await remove();
886
+ throw new Error(`The Playwright container ${name} exited before its server came up.${logs ? `\n\n${logs}` : ""}`);
887
+ }
888
+ if (now() >= deadline) {
889
+ const logs = await containerLogs();
890
+ throw new Error(`Timed out after ${readyTimeout}ms waiting for the Playwright server in container ${name}. Raise playwright({ container: { readyTimeout } }) if the image is still downloading.${logs ? `\n\n${logs}` : ""}`);
891
+ }
892
+ await sleep(250);
893
+ }
894
+ }
895
+ /**
896
+ * Remove every container cappa started, whatever its version. Returns their
897
+ * names.
898
+ */
899
+ async function removePlaywrightContainers(options) {
900
+ const { cli, exec = defaultExec } = options;
901
+ let stdout;
902
+ try {
903
+ ({stdout} = await exec(cli, [
904
+ "ps",
905
+ "-a",
906
+ "--filter",
907
+ `label=${CONTAINER_LABEL}`,
908
+ "--format",
909
+ "{{.Names}}"
910
+ ]));
911
+ } catch (error) {
912
+ if (isNotFound(error)) throw new Error(`Container CLI "${cli}" not found.`, { cause: error });
913
+ throw new Error(`"${cli} ps" failed.\n\n${errorText(error)}`, { cause: error });
914
+ }
915
+ const names = stdout.split("\n").map((line) => line.trim()).filter(Boolean);
916
+ if (names.length > 0) await exec(cli, [
917
+ "rm",
918
+ "-f",
919
+ ...names
920
+ ]);
921
+ return names;
922
+ }
923
+ //#endregion
686
924
  //#region src/crop.ts
687
925
  const DEFAULT_CROP_PADDING = 8;
688
926
  /** The crop to apply, or `undefined` for none. */
@@ -1967,7 +2205,145 @@ var CaptureRunner = class {
1967
2205
  }
1968
2206
  };
1969
2207
  //#endregion
2208
+ //#region src/features/png/pixelRatio.ts
2209
+ /**
2210
+ * A screenshot's pixel ratio — image pixels per CSS pixel — stored in the PNG
2211
+ * itself.
2212
+ *
2213
+ * Kept in the file rather than beside it because `approve` is a plain copy:
2214
+ * the baseline carries the ratio it was captured at through approve, git and
2215
+ * CI artifacts with no bookkeeping.
2216
+ *
2217
+ * Two chunks, both before the image data:
2218
+ * - a `tEXt` chunk keyed `cappa:pixelRatio` — the source of truth. Only cappa
2219
+ * writes it, so an image another tool stamped with a DPI is never misread.
2220
+ * - a standard `pHYs` chunk, which image viewers read as DPI, so a 2×
2221
+ * screenshot opens at its CSS size in tools that honour it.
2222
+ *
2223
+ * Only written for ratios other than 1. A PNG without the key is 1×, which is
2224
+ * what every screenshot taken with `scale: "css"` is — so those stay
2225
+ * byte-for-byte what they were, and `fastBufferCheck` keeps matching them.
2226
+ */
2227
+ const PIXEL_RATIO_KEY = "cappa:pixelRatio";
2228
+ /** Pixels per metre at 96 DPI, the CSS reference pixel density. */
2229
+ const PPM_AT_1X = 96 / .0254;
2230
+ const IHDR_END = 33;
2231
+ /** Ancillary chunks before IDAT are few; bound every walk regardless. */
2232
+ const MAX_CHUNKS_BEFORE_IDAT = 64;
2233
+ const roundRatio = (ratio) => Math.round(ratio * 100) / 100;
2234
+ const createPhysChunk = (ratio) => {
2235
+ const ppm = Math.round(PPM_AT_1X * ratio);
2236
+ const chunk = Buffer.alloc(21);
2237
+ chunk.writeUInt32BE(9, 0);
2238
+ chunk.write("pHYs", 4, "ascii");
2239
+ chunk.writeUInt32BE(ppm, 8);
2240
+ chunk.writeUInt32BE(ppm, 12);
2241
+ chunk.writeUInt8(1, 16);
2242
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, 17)), 17);
2243
+ return chunk;
2244
+ };
2245
+ const isRatioText = (type, data) => type === "tEXt" && data.length > 16 && data.toString("latin1", 0, 17) === `cappa:pixelRatio\0`;
2246
+ const parseRatioText = (data) => {
2247
+ const value = Number(data.toString("latin1", 17));
2248
+ return Number.isFinite(value) && value > 0 ? roundRatio(value) : void 0;
2249
+ };
2250
+ /** The chunks between IHDR and the first IDAT. */
2251
+ function* chunksBeforeImage(buffer) {
2252
+ let offset = IHDR_END;
2253
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2254
+ if (offset + 8 > buffer.length) return;
2255
+ const length = buffer.readUInt32BE(offset);
2256
+ const type = buffer.toString("ascii", offset + 4, offset + 8);
2257
+ const end = offset + 12 + length;
2258
+ if (type === "IDAT" || type === "IEND" || end > buffer.length) return;
2259
+ yield {
2260
+ type,
2261
+ start: offset,
2262
+ end,
2263
+ data: buffer.subarray(offset + 8, offset + 8 + length)
2264
+ };
2265
+ offset = end;
2266
+ }
2267
+ }
2268
+ const hasIhdr = (buffer) => isValidPngSignature(buffer) && buffer.length >= IHDR_END && buffer.toString("ascii", 12, 16) === "IHDR";
2269
+ /**
2270
+ * Return `buffer` stamped with `ratio`, replacing any ratio it carried.
2271
+ *
2272
+ * Ratio 1 removes cappa's chunks instead (see above); a `pHYs` some other tool
2273
+ * wrote is left alone unless cappa is writing its own. Anything that is not a
2274
+ * PNG comes back untouched. No pixel data is re-encoded.
2275
+ */
2276
+ function withPixelRatio(buffer, ratio) {
2277
+ if (!hasIhdr(buffer)) return buffer;
2278
+ const stamp = ratio > 0 && roundRatio(ratio) !== 1;
2279
+ const chunks = [...chunksBeforeImage(buffer)];
2280
+ const ours = chunks.some((chunk) => isRatioText(chunk.type, chunk.data));
2281
+ if (!stamp && !ours) return buffer;
2282
+ const drop = chunks.filter((chunk) => isRatioText(chunk.type, chunk.data) || chunk.type === "pHYs" && (stamp || ours));
2283
+ const parts = [buffer.subarray(0, IHDR_END)];
2284
+ if (stamp) parts.push(createTextChunk(PIXEL_RATIO_KEY, String(roundRatio(ratio))), createPhysChunk(ratio));
2285
+ let copyFrom = IHDR_END;
2286
+ for (const chunk of drop) {
2287
+ parts.push(buffer.subarray(copyFrom, chunk.start));
2288
+ copyFrom = chunk.end;
2289
+ }
2290
+ parts.push(buffer.subarray(copyFrom));
2291
+ return Buffer.concat(parts);
2292
+ }
2293
+ async function readHead(path) {
2294
+ const fh = await open(path, "r");
2295
+ try {
2296
+ const head = Buffer.alloc(IHDR_END);
2297
+ const { bytesRead } = await fh.read(head, 0, IHDR_END, 0);
2298
+ if (bytesRead < IHDR_END || !hasIhdr(head)) return void 0;
2299
+ const parts = [head];
2300
+ const header = Buffer.alloc(8);
2301
+ let offset = IHDR_END;
2302
+ for (let i = 0; i < MAX_CHUNKS_BEFORE_IDAT; i++) {
2303
+ if ((await fh.read(header, 0, 8, offset)).bytesRead < 8) break;
2304
+ const length = header.readUInt32BE(0);
2305
+ const type = header.toString("ascii", 4, 8);
2306
+ if (type === "IDAT" || type === "IEND") break;
2307
+ const chunk = Buffer.alloc(12 + length);
2308
+ await fh.read(chunk, 0, chunk.length, offset);
2309
+ parts.push(chunk);
2310
+ offset += chunk.length;
2311
+ }
2312
+ return Buffer.concat(parts);
2313
+ } finally {
2314
+ await fh.close();
2315
+ }
2316
+ }
2317
+ /**
2318
+ * The pixel ratio a screenshot was captured at: 1 when the PNG carries no
2319
+ * ratio, and also when the file cannot be read — a missing ratio must never
2320
+ * break listing or comparing screenshots.
2321
+ */
2322
+ async function readPixelRatio(source) {
2323
+ try {
2324
+ const buffer = typeof source === "string" ? await readHead(source) : source;
2325
+ if (!buffer || !hasIhdr(buffer)) return 1;
2326
+ for (const chunk of chunksBeforeImage(buffer)) if (isRatioText(chunk.type, chunk.data)) return parseRatioText(chunk.data) ?? 1;
2327
+ return 1;
2328
+ } catch {
2329
+ return 1;
2330
+ }
2331
+ }
2332
+ const formatRatio = (ratio) => `${ratio}×`;
2333
+ /**
2334
+ * Why a screenshot cannot match its baseline when the two were captured at
2335
+ * different pixel ratios — `screenshot.scale` or `deviceScaleFactor` changed.
2336
+ */
2337
+ function describePixelRatioMismatch(expected, actual) {
2338
+ 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.`;
2339
+ }
2340
+ //#endregion
1970
2341
  //#region src/screenshot.ts
2342
+ /**
2343
+ * `deviceScaleFactor` for contexts whose `contextOptions` set none. With the
2344
+ * default `scale: "css"` it only changes how the page renders, not the PNG.
2345
+ */
2346
+ const DEFAULT_DEVICE_SCALE_FACTOR = 2;
1971
2347
  const defaultPixelDiffConfig = {
1972
2348
  type: "pixel",
1973
2349
  threshold: .1,
@@ -1991,13 +2367,62 @@ const LOG_SINK_LEVELS = [
1991
2367
  ];
1992
2368
  /** A logger-shaped object that forwards every call to `sink`. */
1993
2369
  const toSinkLogger = (sink) => Object.fromEntries(LOG_SINK_LEVELS.map((level) => [level, (message, ...args) => sink(level, String(message), ...args)]));
2370
+ const browserMap = {
2371
+ chromium,
2372
+ firefox,
2373
+ webkit
2374
+ };
2375
+ /** Where the remote-browser recipe lives; linked from connection errors. */
2376
+ const REMOTE_BROWSER_DOCS = "https://tim-richter.github.io/cappa/configuration/#connecting-to-a-remote-browser";
2377
+ /** The installed `playwright-core` version, or `null` if it cannot be read. */
2378
+ const clientPlaywrightVersion = () => {
2379
+ try {
2380
+ return createRequire(import.meta.url)("playwright-core/package.json").version;
2381
+ } catch {
2382
+ return null;
2383
+ }
2384
+ };
2385
+ /** The installed `playwright-core` directory, symlinks resolved, or `null`. */
2386
+ const clientPlaywrightPackageDir = () => {
2387
+ try {
2388
+ const require = createRequire(import.meta.url);
2389
+ return realpathSync(path.dirname(require.resolve("playwright-core/package.json")));
2390
+ } catch {
2391
+ return null;
2392
+ }
2393
+ };
2394
+ /**
2395
+ * Turn a raw `browserType.connect()` failure into something actionable.
2396
+ *
2397
+ * Exported for tests.
2398
+ */
2399
+ const describeConnectError = (error, wsEndpoint, clientVersion = clientPlaywrightVersion(), container) => {
2400
+ const message = error instanceof Error ? error.message : String(error);
2401
+ if (container && (/version mismatch/i.test(message) || /\b428\b/.test(message))) return new Error(`The container image ${container.image} runs a different Playwright version than this client${clientVersion ? ` (playwright-core ${clientVersion})` : ""}. A custom playwright({ container: { image } }) must be built from the official image for the same version — use {version} in the tag.\n\n${message}`, { cause: error });
2402
+ if (/version mismatch/i.test(message) || /\b428\b/.test(message)) {
2403
+ const image = clientVersion ? `mcr.microsoft.com/playwright:v${clientVersion}-noble` : "the mcr.microsoft.com/playwright image matching your playwright-core";
2404
+ return new Error(`The Playwright server at ${wsEndpoint} runs a different Playwright version than this client${clientVersion ? ` (playwright-core ${clientVersion})` : ""}. Run the server from ${image}.\n\n${message}`, { cause: error });
2405
+ }
2406
+ if (/timeout/i.test(message) && /exceeded/i.test(message)) return new Error(`Timed out connecting to the Playwright server at ${wsEndpoint}. See ${REMOTE_BROWSER_DOCS}\n\n${message}`, { cause: error });
2407
+ return new Error(`No Playwright server at ${wsEndpoint}. Start one with \`playwright run-server\`, or unset connectOptions.wsEndpoint to launch a local browser. See ${REMOTE_BROWSER_DOCS}\n\n${message}`, { cause: error });
2408
+ };
1994
2409
  var ScreenshotTool = class {
1995
2410
  browserType;
1996
2411
  headless;
2412
+ /** Browser provider, headless mode and instance — see `UserConfig.browser`. */
2413
+ browserConfig;
2414
+ /**
2415
+ * Set when the browser goes away underneath the tool — a remote browser
2416
+ * server restarting, or a local browser crashing. `WarmBrowser` checks it so
2417
+ * it starts a fresh browser instead of handing out a dead one.
2418
+ */
2419
+ disconnected = false;
1997
2420
  viewport;
1998
2421
  fullPage;
1999
2422
  /** Default content crop; a screenshot's own `crop` overrides it. */
2000
2423
  crop;
2424
+ /** Default `scale`; a screenshot's own `scale` overrides it. */
2425
+ scale;
2001
2426
  outputDir;
2002
2427
  browser = null;
2003
2428
  context = null;
@@ -2018,20 +2443,27 @@ var ScreenshotTool = class {
2018
2443
  filesystem;
2019
2444
  logConsoleEvents;
2020
2445
  connectionTimeout;
2446
+ /** The container `init()` started or reused, when `container` is on. */
2447
+ container = null;
2021
2448
  defaultUserAgent = "";
2022
2449
  /** The real logger, kept so `setLogSink(null)` restores the same instance. */
2023
2450
  baseLogger;
2024
2451
  /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
2025
2452
  captureSink = null;
2026
2453
  constructor(options) {
2027
- this.browserType = options.browserType || "chromium";
2028
- this.headless = options.headless !== false;
2454
+ this.browserConfig = resolveBrowserConfig(options.browser ?? {
2455
+ headless: options.headless !== false,
2456
+ instances: [{ browser: options.browserType || "chromium" }]
2457
+ });
2458
+ this.browserType = this.browserConfig.instances[0].browser;
2459
+ this.headless = this.browserConfig.headless;
2029
2460
  this.viewport = options.viewport || {
2030
2461
  width: 1920,
2031
2462
  height: 1080
2032
2463
  };
2033
2464
  this.fullPage = options.fullPage ?? true;
2034
2465
  this.crop = options.crop ?? false;
2466
+ this.scale = options.scale ?? "css";
2035
2467
  this.outputDir = options.outputDir || "./screenshots";
2036
2468
  this.diff = this.resolveDiffOptions(options.diff);
2037
2469
  this.concurrency = Math.max(1, options.concurrency || 1);
@@ -2100,34 +2532,85 @@ var ScreenshotTool = class {
2100
2532
  * Initialize playwright and page
2101
2533
  */
2102
2534
  async init() {
2103
- const browserClass = {
2104
- chromium,
2105
- firefox,
2106
- webkit
2107
- }[this.browserType];
2108
- if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
2109
- const browser = await browserClass.launch({ headless: this.headless });
2535
+ const browserType = browserMap[this.browserType];
2536
+ if (!browserType) throw new Error(`Unsupported browser type: ${this.browserType}`);
2537
+ const { launchOptions, connectOptions, contextOptions } = this.browserConfig.provider.options;
2538
+ const launch = {
2539
+ ...launchOptions,
2540
+ headless: this.headless
2541
+ };
2542
+ const container = resolveContainerOptions(this.browserConfig.provider.options.container);
2543
+ let connect = connectOptions?.wsEndpoint ? {
2544
+ ...connectOptions,
2545
+ wsEndpoint: connectOptions.wsEndpoint
2546
+ } : null;
2547
+ if (connect && container) this.logger.debug(`connectOptions.wsEndpoint is set (${connect.wsEndpoint}); not starting a container.`);
2548
+ else if (container) {
2549
+ const version = clientPlaywrightVersion();
2550
+ const packageDir = clientPlaywrightPackageDir();
2551
+ if (!version || !packageDir) throw new Error("playwright({ container }) needs the installed playwright-core, but its package.json could not be read.");
2552
+ this.container = await ensurePlaywrightContainer({
2553
+ ...container,
2554
+ version,
2555
+ packageDir,
2556
+ log: (message) => this.logger.info(message)
2557
+ });
2558
+ connect = {
2559
+ exposeNetwork: "<loopback>",
2560
+ ...connectOptions,
2561
+ wsEndpoint: this.container.wsEndpoint
2562
+ };
2563
+ }
2564
+ let browser;
2565
+ if (connect) {
2566
+ const { wsEndpoint, ...options } = connect;
2567
+ try {
2568
+ browser = await browserType.connect(wsEndpoint, {
2569
+ ...options,
2570
+ headers: {
2571
+ "x-playwright-launch-options": JSON.stringify(launch),
2572
+ ...options.headers
2573
+ }
2574
+ });
2575
+ } catch (error) {
2576
+ throw describeConnectError(error, wsEndpoint, void 0, this.container ?? void 0);
2577
+ }
2578
+ } else browser = await browserType.launch(launch);
2110
2579
  if (!browser) throw new Error("Something went wrong with starting the browser.");
2111
2580
  this.browser = browser;
2112
- const tempCtx = await browser.newContext();
2113
- const tempPage = await tempCtx.newPage();
2114
- this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
2115
- await tempCtx.close();
2581
+ this.disconnected = false;
2582
+ browser.on("disconnected", () => {
2583
+ if (this.browser === browser) this.disconnected = true;
2584
+ });
2585
+ if (!contextOptions?.userAgent) {
2586
+ const tempCtx = await browser.newContext();
2587
+ const tempPage = await tempCtx.newPage();
2588
+ this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
2589
+ await tempCtx.close();
2590
+ }
2116
2591
  await this.createContexts();
2117
2592
  }
2118
2593
  /**
2119
2594
  * Create the pool of browser contexts and pages.
2595
+ *
2596
+ * `contextOptions` from the provider merge over cappa's defaults; the
2597
+ * viewport and the `CappaStorybook` user-agent suffix always win, because
2598
+ * plugins and `isCappa()` rely on them.
2120
2599
  */
2121
2600
  async createContexts() {
2122
2601
  const browser = this.browser;
2123
2602
  if (!browser) throw new Error("Browser not initialized");
2603
+ const { contextOptions, actionTimeout } = this.browserConfig.provider.options;
2604
+ const { viewport: _ignored, ...extraContextOptions } = contextOptions ?? {};
2124
2605
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
2125
2606
  const context = await browser.newContext({
2126
2607
  reducedMotion: "reduce",
2127
- deviceScaleFactor: 2,
2128
- userAgent: `${this.defaultUserAgent} CappaStorybook`,
2608
+ deviceScaleFactor: DEFAULT_DEVICE_SCALE_FACTOR,
2609
+ ...extraContextOptions,
2610
+ userAgent: `${contextOptions?.userAgent ?? this.defaultUserAgent} CappaStorybook`,
2129
2611
  viewport: this.viewport
2130
2612
  });
2613
+ if (actionTimeout) context.setDefaultTimeout(actionTimeout);
2131
2614
  return {
2132
2615
  context,
2133
2616
  page: await context.newPage()
@@ -2182,13 +2665,23 @@ var ScreenshotTool = class {
2182
2665
  this.context = null;
2183
2666
  this.page = null;
2184
2667
  }
2185
- if (this.browser) {
2668
+ const browser = this.browser;
2669
+ if (browser) {
2670
+ this.browser = null;
2186
2671
  try {
2187
- await this.browser.close();
2672
+ await browser.close();
2188
2673
  } catch (error) {
2189
2674
  getLogger().debug("Error closing the browser:", error);
2190
2675
  }
2191
- this.browser = null;
2676
+ }
2677
+ this.disconnected = false;
2678
+ const container = this.container;
2679
+ this.container = null;
2680
+ const options = resolveContainerOptions(this.browserConfig.provider.options.container);
2681
+ if (container && options && !options.keepAlive && !container.reused) try {
2682
+ await container.stop();
2683
+ } catch (error) {
2684
+ getLogger().debug("Error removing the Playwright container:", error);
2192
2685
  }
2193
2686
  }
2194
2687
  /**
@@ -2236,21 +2729,33 @@ var ScreenshotTool = class {
2236
2729
  const clip = crop ? await measureContentClip(page, crop, fullPage) : void 0;
2237
2730
  if (crop && !clip) this.logger.debug(`Nothing painted inside "${crop.root}" to crop to; taking the uncropped screenshot`);
2238
2731
  const screenshotOptions = {
2239
- path: filepath,
2240
2732
  fullPage,
2241
2733
  clip,
2242
2734
  type: "png",
2243
2735
  timeout: 6e4,
2244
2736
  mask: options.mask,
2245
2737
  omitBackground: options.omitBackground,
2246
- scale: "css",
2738
+ scale: options.scale ?? this.scale,
2247
2739
  animations: "disabled",
2248
2740
  caret: "hide"
2249
2741
  };
2250
- return page.screenshot(screenshotOptions);
2742
+ const buffer = withPixelRatio(await page.screenshot(screenshotOptions), this.pixelRatioFor(options));
2743
+ if (filepath) await fsp.writeFile(filepath, buffer);
2744
+ return buffer;
2251
2745
  });
2252
2746
  }
2253
2747
  /**
2748
+ * Image pixels per CSS pixel for a screenshot taken with `options`: the
2749
+ * context's `deviceScaleFactor` with `scale: "device"`, else 1.
2750
+ *
2751
+ * Stamped into every PNG (see `features/png/pixelRatio.ts`) so a baseline
2752
+ * remembers the ratio it was captured at.
2753
+ */
2754
+ pixelRatioFor(options) {
2755
+ if ((options.scale ?? this.scale) !== "device") return 1;
2756
+ return this.browserConfig.provider.options.contextOptions?.deviceScaleFactor ?? DEFAULT_DEVICE_SCALE_FACTOR;
2757
+ }
2758
+ /**
2254
2759
  * Sets the viewport size and executes the action, ensuring the original viewport is restored
2255
2760
  * even if the action throws an error.
2256
2761
  */
@@ -2285,6 +2790,7 @@ var ScreenshotTool = class {
2285
2790
  const screenshotSettings = {
2286
2791
  fullPage: options.fullPage ?? this.fullPage,
2287
2792
  crop: options.crop,
2793
+ scale: options.scale,
2288
2794
  mask: options.mask,
2289
2795
  omitBackground: options.omitBackground,
2290
2796
  delay: options.delay,
@@ -2310,7 +2816,7 @@ var ScreenshotTool = class {
2310
2816
  });
2311
2817
  }
2312
2818
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
2313
- this.logger.warn(`Screenshot has different sizes than reference image`);
2819
+ if (!retryScreenshot.pixelRatio) this.logger.warn(`Screenshot has different sizes than reference image`);
2314
2820
  if (!diffImagePath) {
2315
2821
  const diffFilename = options.diffImageFilename || filename;
2316
2822
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
@@ -2322,7 +2828,8 @@ var ScreenshotTool = class {
2322
2828
  return {
2323
2829
  screenshotPath: filepath,
2324
2830
  comparisonResult: retryScreenshot.comparisonResult,
2325
- diffImagePath
2831
+ diffImagePath,
2832
+ ...retryScreenshot.pixelRatio ? { pixelRatio: retryScreenshot.pixelRatio } : {}
2326
2833
  };
2327
2834
  } catch (error) {
2328
2835
  this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
@@ -2331,19 +2838,27 @@ var ScreenshotTool = class {
2331
2838
  }
2332
2839
  async retryScreenshot(page, referenceImage, options, diffOverride) {
2333
2840
  const diffConfig = this.mergeDiffOptions(diffOverride);
2334
- for (let i = 0; i < this.retries; i++) try {
2841
+ const pixelRatio = {
2842
+ expected: await readPixelRatio(referenceImage),
2843
+ actual: this.pixelRatioFor(options)
2844
+ };
2845
+ const ratioMismatch = pixelRatio.expected !== pixelRatio.actual;
2846
+ if (ratioMismatch) this.logger.error(describePixelRatioMismatch(pixelRatio.expected, pixelRatio.actual));
2847
+ const attempts = ratioMismatch ? 1 : this.retries;
2848
+ for (let i = 0; i < attempts; i++) try {
2335
2849
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
2336
2850
  ...options,
2337
2851
  delay: this.getIncBackoffDelay(i, options.delay || 0)
2338
2852
  });
2339
2853
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
2340
2854
  const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
2341
- if (i === this.retries - 1 && !comparisonResult.passed) {
2342
- this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2855
+ if (i === attempts - 1 && !comparisonResult.passed) {
2856
+ if (!ratioMismatch) this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
2343
2857
  return {
2344
2858
  screenshotPath: screenshotBuffer,
2345
2859
  comparisonResult,
2346
- passed: false
2860
+ passed: false,
2861
+ ...ratioMismatch ? { pixelRatio } : {}
2347
2862
  };
2348
2863
  }
2349
2864
  if (comparisonResult.passed) return {
@@ -2759,7 +3274,11 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2759
3274
  const id = createHash("sha256").update(relativePath).digest("hex");
2760
3275
  const expectedScreenshot = expectedByRelativePath.get(relativePath);
2761
3276
  const diffScreenshot = diffByRelativePath.get(relativePath);
2762
- const diffMeta = diffScreenshot ? await readDiffMeta(diffScreenshot) : void 0;
3277
+ const [diffMeta, actualPixelRatio, expectedPixelRatio] = await Promise.all([
3278
+ diffScreenshot ? readDiffMeta(diffScreenshot) : void 0,
3279
+ readPixelRatio(screenshot),
3280
+ expectedScreenshot ? readPixelRatio(expectedScreenshot) : 1
3281
+ ]);
2763
3282
  screenshotRepresentations.push({
2764
3283
  id,
2765
3284
  name,
@@ -2767,7 +3286,8 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2767
3286
  expectedPath: expectedScreenshot ? path.relative(outputDir, expectedScreenshot) : void 0,
2768
3287
  diffPath: diffScreenshot ? path.relative(outputDir, diffScreenshot) : void 0,
2769
3288
  actualPath: path.relative(outputDir, screenshot),
2770
- ...diffMeta ? { diffMeta } : {}
3289
+ ...diffMeta ? { diffMeta } : {},
3290
+ ...pixelRatios(actualPixelRatio, expectedPixelRatio)
2771
3291
  });
2772
3292
  }
2773
3293
  for (const expectedScreenshot of expectedScreenshots) {
@@ -2779,13 +3299,19 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2779
3299
  id,
2780
3300
  name,
2781
3301
  category: "deleted",
2782
- expectedPath: path.relative(outputDir, expectedScreenshot)
3302
+ expectedPath: path.relative(outputDir, expectedScreenshot),
3303
+ ...pixelRatios(1, await readPixelRatio(expectedScreenshot))
2783
3304
  });
2784
3305
  }
2785
3306
  return screenshotRepresentations.sort((a, b) => {
2786
3307
  return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
2787
3308
  });
2788
3309
  };
3310
+ /** Ratios other than 1 only: absent means 1, which keeps 1× listings as they were. */
3311
+ const pixelRatios = (actual, expected) => ({
3312
+ ...actual !== 1 ? { actualPixelRatio: actual } : {},
3313
+ ...expected !== 1 ? { expectedPixelRatio: expected } : {}
3314
+ });
2789
3315
  const buildCategory = (expectedScreenshot, diffScreenshot) => {
2790
3316
  if (expectedScreenshot && diffScreenshot) return "changed";
2791
3317
  if (expectedScreenshot) return "passed";
@@ -3426,6 +3952,13 @@ var WarmBrowser = class {
3426
3952
  if (this.closed) throw new Error("WarmBrowser has been closed");
3427
3953
  this.cancelIdleTimer();
3428
3954
  this.inUse = true;
3955
+ if (this.tool?.disconnected === true) {
3956
+ const dead = this.tool;
3957
+ this.tool = null;
3958
+ try {
3959
+ await dead.close();
3960
+ } catch {}
3961
+ }
3429
3962
  if (this.tool) {
3430
3963
  await this.tool.recycleContexts();
3431
3964
  return this.tool;
@@ -3968,11 +4501,13 @@ var LocalEngine = class {
3968
4501
  logConsoleEvents: this.options.logConsoleEvents,
3969
4502
  fullPage: this.options.fullPage ?? true,
3970
4503
  crop: this.options.crop ?? false,
4504
+ scale: this.options.scale ?? "css",
3971
4505
  viewport: this.options.viewport ?? {
3972
4506
  width: 1920,
3973
4507
  height: 1080
3974
4508
  },
3975
- connectionTimeout: this.options.connectionTimeout
4509
+ connectionTimeout: this.options.connectionTimeout,
4510
+ browser: this.options.browser
3976
4511
  });
3977
4512
  }
3978
4513
  async listPlugins() {
@@ -5009,6 +5544,6 @@ function resolveWebServerConfig(webServer, configDir, env = process.env) {
5009
5544
  });
5010
5545
  }
5011
5546
  //#endregion
5012
- export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CaptureRunner, DEFAULT_CROP_PADDING, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_KILL_GRACE_MS, DEFAULT_MAX_TASKS, DEFAULT_WEB_SERVER_TIMEOUT_MS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, NO_WEB_SERVER_HINT, OutputTail, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, describeChange, didScreenshotFail, filterTasks, findRefusedConnection, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isUrlReady, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, measureContentClip, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, readAgentReport, readCaptureManifest, readDiffMeta, recordCaptureOrigins, renderJudgmentTiles, renderOverview, resolveCrop, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, writeAgentVerdict };
5547
+ export { ACTION_BY_LABEL, AGENT_DIRNAME, AGENT_REPORT_VERSION, CONSOLE_LOG_LEVELS, CONTAINER_LABEL, CaptureRunner, DEFAULT_CONTAINER_IMAGE, DEFAULT_CROP_PADDING, DEFAULT_DEBOUNCE_MS, DEFAULT_IGNORED_DIRS, DEFAULT_KILL_GRACE_MS, DEFAULT_MAX_TASKS, DEFAULT_WEB_SERVER_TIMEOUT_MS, ENGINE_ERROR_CODES, FsScreenshotStore, LocalEngine, MANIFEST_FILENAME, MANIFEST_VERSION, NO_WEB_SERVER_HINT, OutputTail, PIXEL_RATIO_KEY, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, describeChange, describePixelRatioMismatch, didScreenshotFail, ensurePlaywrightContainer, filterTasks, findRefusedConnection, fingerprintImages, getDeletedScreenshots, groupScreenshots, imagesMatch, imagesMatchGMSD, isRunInProgressError, isUnknownTargetsError, isUrlReady, isVerdictLabel, isWatchInProgressError, judgmentDir, mapWithConcurrency, measureContentClip, mergeCaptureManifest, normalizeChangeType, padAndClamp, parseAgentVerdict, playwright, readAgentReport, readCaptureManifest, readDiffMeta, readPixelRatio, recordCaptureOrigins, removePlaywrightContainers, renderJudgmentTiles, renderOverview, resolveBrowserConfig, resolveContainerOptions, resolveCrop, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, withPixelRatio, writeAgentVerdict };
5013
5548
 
5014
5549
  //# sourceMappingURL=index.mjs.map