@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.cjs CHANGED
@@ -30,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  enumerable: true
31
31
  }) : target, mod));
32
32
  //#endregion
33
+ const require_playwright = require("./playwright.cjs");
33
34
  let node_fs = require("node:fs");
34
35
  node_fs = __toESM(node_fs);
35
36
  let _blazediff_gmsd = require("@blazediff/gmsd");
@@ -45,9 +46,10 @@ let node_path = require("node:path");
45
46
  node_path = __toESM(node_path);
46
47
  let _blazediff_core_native = require("@blazediff/core-native");
47
48
  let _blazediff_interpret_native = require("@blazediff/interpret-native");
49
+ let node_child_process = require("node:child_process");
48
50
  let node_crypto = require("node:crypto");
51
+ let node_module = require("node:module");
49
52
  let playwright_core = require("playwright-core");
50
- let node_child_process = require("node:child_process");
51
53
  //#region src/features/png/util.ts
52
54
  const pngSignature = Buffer.from([
53
55
  137,
@@ -709,6 +711,242 @@ const attachConsoleLogging = (page, setting, logger) => {
709
711
  });
710
712
  };
711
713
  //#endregion
714
+ //#region src/container.ts
715
+ /**
716
+ * Runs the official Playwright image for an exact `playwright-core` version
717
+ * through a container CLI (docker, podman, nerdctl, …) and hands back the
718
+ * `run-server` endpoint.
719
+ *
720
+ * Only subcommands all of those CLIs share are used: `version`, `image
721
+ * inspect`, `pull`, `inspect`, `run`, `port`, `logs`, `ps` and `rm`.
722
+ */
723
+ /** Label on every container cappa starts; `removePlaywrightContainers` finds them by it. */
724
+ const CONTAINER_LABEL = "dev.cappa.playwright";
725
+ /** Port `run-server` listens on inside the container. */
726
+ const SERVER_PORT = 3e3;
727
+ /** Where the host's `playwright-core` is mounted inside the container. */
728
+ const PACKAGE_MOUNT = "/opt/playwright-core";
729
+ const defaultExec = (file, args) => new Promise((resolve, reject) => {
730
+ (0, node_child_process.execFile)(file, args, {
731
+ maxBuffer: 16777216,
732
+ windowsHide: true
733
+ }, (error, stdout, stderr) => {
734
+ if (error) reject(Object.assign(error, {
735
+ stdout,
736
+ stderr
737
+ }));
738
+ else resolve({
739
+ stdout: String(stdout),
740
+ stderr: String(stderr)
741
+ });
742
+ });
743
+ });
744
+ /** `true` once `run-server` answers plain HTTP with `Running`. */
745
+ const defaultProbe = async (url) => {
746
+ try {
747
+ const response = await fetch(url, { signal: AbortSignal.timeout(2e3) });
748
+ return response.ok && (await response.text()).includes("Running");
749
+ } catch {
750
+ return false;
751
+ }
752
+ };
753
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
754
+ const errorText = (error) => {
755
+ const stderr = error?.stderr;
756
+ if (typeof stderr === "string" && stderr.trim()) return stderr.trim();
757
+ return error instanceof Error ? error.message : String(error);
758
+ };
759
+ const isNotFound = (error) => error?.code === "ENOENT";
760
+ /** `{version}` filled in. */
761
+ const containerImage = (image, version) => image.replaceAll("{version}", version);
762
+ /**
763
+ * Deterministic per version, image and run arguments: changing any of them
764
+ * starts a fresh container instead of reusing one with stale settings.
765
+ */
766
+ const containerName = (version, image, runArgs, packageDir = "") => {
767
+ const hash = (0, node_crypto.createHash)("sha256").update(JSON.stringify([
768
+ image,
769
+ runArgs,
770
+ packageDir
771
+ ])).digest("hex").slice(0, 8);
772
+ return `cappa-playwright-v${version.replace(/[^\w.-]/g, "_")}-${hash}`;
773
+ };
774
+ /** Host port from `<cli> port` output (`127.0.0.1:49153`, maybe several lines). */
775
+ const parsePort = (output) => {
776
+ for (const line of output.split("\n")) {
777
+ const match = line.trim().match(/:(\d+)$/);
778
+ if (match) return Number(match[1]);
779
+ }
780
+ return null;
781
+ };
782
+ /**
783
+ * Start — or reuse — the Playwright server container for `version` and wait
784
+ * until it accepts connections.
785
+ */
786
+ async function ensurePlaywrightContainer(options) {
787
+ const { version, packageDir, cli, runArgs, readyTimeout, log = () => {}, exec = defaultExec, probe = defaultProbe, sleep = defaultSleep, now = Date.now } = options;
788
+ const image = containerImage(options.image, version);
789
+ const name = containerName(version, image, runArgs, packageDir);
790
+ const deadline = now() + readyTimeout;
791
+ const run = async (args) => {
792
+ try {
793
+ return await exec(cli, args);
794
+ } catch (error) {
795
+ 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 });
796
+ throw error;
797
+ }
798
+ };
799
+ try {
800
+ await run(["version"]);
801
+ } catch (error) {
802
+ if (error instanceof Error && error.message.startsWith("Container CLI")) throw error;
803
+ 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 });
804
+ }
805
+ const state = async () => {
806
+ try {
807
+ const { stdout } = await run([
808
+ "inspect",
809
+ "--format",
810
+ "{{.State.Running}}",
811
+ name
812
+ ]);
813
+ return stdout.trim() === "true" ? "running" : "stopped";
814
+ } catch {
815
+ return "absent";
816
+ }
817
+ };
818
+ const remove = async () => {
819
+ await run([
820
+ "rm",
821
+ "-f",
822
+ name
823
+ ]).catch(() => {});
824
+ };
825
+ const stop = async () => {
826
+ await remove();
827
+ };
828
+ let reused = false;
829
+ const current = await state();
830
+ if (current === "running") {
831
+ reused = true;
832
+ log(`Reusing Playwright container ${name}`);
833
+ } else {
834
+ if (current === "stopped") await remove();
835
+ if (!await run([
836
+ "image",
837
+ "inspect",
838
+ image
839
+ ]).then(() => true, () => false)) {
840
+ log(`Pulling ${image} (first run only; this can take a few minutes)`);
841
+ try {
842
+ await run(["pull", image]);
843
+ } catch (error) {
844
+ 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 });
845
+ }
846
+ }
847
+ log(`Starting Playwright ${version} container ${name}`);
848
+ try {
849
+ await run([
850
+ "run",
851
+ "-d",
852
+ "--init",
853
+ "--ipc=host",
854
+ "--user",
855
+ "pwuser",
856
+ "--workdir",
857
+ "/home/pwuser",
858
+ "-p",
859
+ `127.0.0.1::${SERVER_PORT}`,
860
+ "--mount",
861
+ `type=bind,source=${packageDir},target=${PACKAGE_MOUNT},readonly`,
862
+ "--label",
863
+ `${CONTAINER_LABEL}=${version}`,
864
+ "--name",
865
+ name,
866
+ ...runArgs,
867
+ image,
868
+ "node",
869
+ `${PACKAGE_MOUNT}/cli.js`,
870
+ "run-server",
871
+ "--port",
872
+ String(SERVER_PORT),
873
+ "--host",
874
+ "0.0.0.0"
875
+ ]);
876
+ } catch (error) {
877
+ if (/already in use|conflict|already exists/i.test(errorText(error))) reused = true;
878
+ else throw new Error(`Could not start ${image}.\n\n${errorText(error)}`, { cause: error });
879
+ }
880
+ }
881
+ const containerLogs = async () => {
882
+ const result = await run([
883
+ "logs",
884
+ "--tail",
885
+ "30",
886
+ name
887
+ ]).catch(() => null);
888
+ return result ? `${result.stdout}${result.stderr}`.trim() : "";
889
+ };
890
+ let port = null;
891
+ let attempt = 0;
892
+ while (true) {
893
+ if (port === null) {
894
+ const output = await run([
895
+ "port",
896
+ name,
897
+ `${SERVER_PORT}/tcp`
898
+ ]).then((r) => r.stdout, () => "");
899
+ port = parsePort(output);
900
+ }
901
+ if (port !== null && await probe(`http://127.0.0.1:${port}/`)) return {
902
+ wsEndpoint: `ws://127.0.0.1:${port}/`,
903
+ name,
904
+ image,
905
+ reused,
906
+ stop
907
+ };
908
+ attempt++;
909
+ if (attempt % 8 === 0 && await state() !== "running") {
910
+ const logs = await containerLogs();
911
+ await remove();
912
+ throw new Error(`The Playwright container ${name} exited before its server came up.${logs ? `\n\n${logs}` : ""}`);
913
+ }
914
+ if (now() >= deadline) {
915
+ const logs = await containerLogs();
916
+ 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}` : ""}`);
917
+ }
918
+ await sleep(250);
919
+ }
920
+ }
921
+ /**
922
+ * Remove every container cappa started, whatever its version. Returns their
923
+ * names.
924
+ */
925
+ async function removePlaywrightContainers(options) {
926
+ const { cli, exec = defaultExec } = options;
927
+ let stdout;
928
+ try {
929
+ ({stdout} = await exec(cli, [
930
+ "ps",
931
+ "-a",
932
+ "--filter",
933
+ `label=${CONTAINER_LABEL}`,
934
+ "--format",
935
+ "{{.Names}}"
936
+ ]));
937
+ } catch (error) {
938
+ if (isNotFound(error)) throw new Error(`Container CLI "${cli}" not found.`, { cause: error });
939
+ throw new Error(`"${cli} ps" failed.\n\n${errorText(error)}`, { cause: error });
940
+ }
941
+ const names = stdout.split("\n").map((line) => line.trim()).filter(Boolean);
942
+ if (names.length > 0) await exec(cli, [
943
+ "rm",
944
+ "-f",
945
+ ...names
946
+ ]);
947
+ return names;
948
+ }
949
+ //#endregion
712
950
  //#region src/crop.ts
713
951
  const DEFAULT_CROP_PADDING = 8;
714
952
  /** The crop to apply, or `undefined` for none. */
@@ -1993,7 +2231,145 @@ var CaptureRunner = class {
1993
2231
  }
1994
2232
  };
1995
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
1996
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;
1997
2373
  const defaultPixelDiffConfig = {
1998
2374
  type: "pixel",
1999
2375
  threshold: .1,
@@ -2017,13 +2393,62 @@ const LOG_SINK_LEVELS = [
2017
2393
  ];
2018
2394
  /** A logger-shaped object that forwards every call to `sink`. */
2019
2395
  const toSinkLogger = (sink) => Object.fromEntries(LOG_SINK_LEVELS.map((level) => [level, (message, ...args) => sink(level, String(message), ...args)]));
2396
+ const browserMap = {
2397
+ chromium: playwright_core.chromium,
2398
+ firefox: playwright_core.firefox,
2399
+ webkit: playwright_core.webkit
2400
+ };
2401
+ /** Where the remote-browser recipe lives; linked from connection errors. */
2402
+ const REMOTE_BROWSER_DOCS = "https://tim-richter.github.io/cappa/configuration/#connecting-to-a-remote-browser";
2403
+ /** The installed `playwright-core` version, or `null` if it cannot be read. */
2404
+ const clientPlaywrightVersion = () => {
2405
+ try {
2406
+ return (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("playwright-core/package.json").version;
2407
+ } catch {
2408
+ return null;
2409
+ }
2410
+ };
2411
+ /** The installed `playwright-core` directory, symlinks resolved, or `null`. */
2412
+ const clientPlaywrightPackageDir = () => {
2413
+ try {
2414
+ const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2415
+ return (0, node_fs.realpathSync)(node_path.default.dirname(require$1.resolve("playwright-core/package.json")));
2416
+ } catch {
2417
+ return null;
2418
+ }
2419
+ };
2420
+ /**
2421
+ * Turn a raw `browserType.connect()` failure into something actionable.
2422
+ *
2423
+ * Exported for tests.
2424
+ */
2425
+ const describeConnectError = (error, wsEndpoint, clientVersion = clientPlaywrightVersion(), container) => {
2426
+ const message = error instanceof Error ? error.message : String(error);
2427
+ 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 });
2428
+ if (/version mismatch/i.test(message) || /\b428\b/.test(message)) {
2429
+ const image = clientVersion ? `mcr.microsoft.com/playwright:v${clientVersion}-noble` : "the mcr.microsoft.com/playwright image matching your playwright-core";
2430
+ 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 });
2431
+ }
2432
+ 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 });
2433
+ 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 });
2434
+ };
2020
2435
  var ScreenshotTool = class {
2021
2436
  browserType;
2022
2437
  headless;
2438
+ /** Browser provider, headless mode and instance — see `UserConfig.browser`. */
2439
+ browserConfig;
2440
+ /**
2441
+ * Set when the browser goes away underneath the tool — a remote browser
2442
+ * server restarting, or a local browser crashing. `WarmBrowser` checks it so
2443
+ * it starts a fresh browser instead of handing out a dead one.
2444
+ */
2445
+ disconnected = false;
2023
2446
  viewport;
2024
2447
  fullPage;
2025
2448
  /** Default content crop; a screenshot's own `crop` overrides it. */
2026
2449
  crop;
2450
+ /** Default `scale`; a screenshot's own `scale` overrides it. */
2451
+ scale;
2027
2452
  outputDir;
2028
2453
  browser = null;
2029
2454
  context = null;
@@ -2044,20 +2469,27 @@ var ScreenshotTool = class {
2044
2469
  filesystem;
2045
2470
  logConsoleEvents;
2046
2471
  connectionTimeout;
2472
+ /** The container `init()` started or reused, when `container` is on. */
2473
+ container = null;
2047
2474
  defaultUserAgent = "";
2048
2475
  /** The real logger, kept so `setLogSink(null)` restores the same instance. */
2049
2476
  baseLogger;
2050
2477
  /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
2051
2478
  captureSink = null;
2052
2479
  constructor(options) {
2053
- this.browserType = options.browserType || "chromium";
2054
- this.headless = options.headless !== false;
2480
+ this.browserConfig = require_playwright.resolveBrowserConfig(options.browser ?? {
2481
+ headless: options.headless !== false,
2482
+ instances: [{ browser: options.browserType || "chromium" }]
2483
+ });
2484
+ this.browserType = this.browserConfig.instances[0].browser;
2485
+ this.headless = this.browserConfig.headless;
2055
2486
  this.viewport = options.viewport || {
2056
2487
  width: 1920,
2057
2488
  height: 1080
2058
2489
  };
2059
2490
  this.fullPage = options.fullPage ?? true;
2060
2491
  this.crop = options.crop ?? false;
2492
+ this.scale = options.scale ?? "css";
2061
2493
  this.outputDir = options.outputDir || "./screenshots";
2062
2494
  this.diff = this.resolveDiffOptions(options.diff);
2063
2495
  this.concurrency = Math.max(1, options.concurrency || 1);
@@ -2126,34 +2558,85 @@ var ScreenshotTool = class {
2126
2558
  * Initialize playwright and page
2127
2559
  */
2128
2560
  async init() {
2129
- const browserClass = {
2130
- chromium: playwright_core.chromium,
2131
- firefox: playwright_core.firefox,
2132
- webkit: playwright_core.webkit
2133
- }[this.browserType];
2134
- if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
2135
- const browser = await browserClass.launch({ headless: this.headless });
2561
+ const browserType = browserMap[this.browserType];
2562
+ if (!browserType) throw new Error(`Unsupported browser type: ${this.browserType}`);
2563
+ const { launchOptions, connectOptions, contextOptions } = this.browserConfig.provider.options;
2564
+ const launch = {
2565
+ ...launchOptions,
2566
+ headless: this.headless
2567
+ };
2568
+ const container = require_playwright.resolveContainerOptions(this.browserConfig.provider.options.container);
2569
+ let connect = connectOptions?.wsEndpoint ? {
2570
+ ...connectOptions,
2571
+ wsEndpoint: connectOptions.wsEndpoint
2572
+ } : null;
2573
+ if (connect && container) this.logger.debug(`connectOptions.wsEndpoint is set (${connect.wsEndpoint}); not starting a container.`);
2574
+ else if (container) {
2575
+ const version = clientPlaywrightVersion();
2576
+ const packageDir = clientPlaywrightPackageDir();
2577
+ if (!version || !packageDir) throw new Error("playwright({ container }) needs the installed playwright-core, but its package.json could not be read.");
2578
+ this.container = await ensurePlaywrightContainer({
2579
+ ...container,
2580
+ version,
2581
+ packageDir,
2582
+ log: (message) => this.logger.info(message)
2583
+ });
2584
+ connect = {
2585
+ exposeNetwork: "<loopback>",
2586
+ ...connectOptions,
2587
+ wsEndpoint: this.container.wsEndpoint
2588
+ };
2589
+ }
2590
+ let browser;
2591
+ if (connect) {
2592
+ const { wsEndpoint, ...options } = connect;
2593
+ try {
2594
+ browser = await browserType.connect(wsEndpoint, {
2595
+ ...options,
2596
+ headers: {
2597
+ "x-playwright-launch-options": JSON.stringify(launch),
2598
+ ...options.headers
2599
+ }
2600
+ });
2601
+ } catch (error) {
2602
+ throw describeConnectError(error, wsEndpoint, void 0, this.container ?? void 0);
2603
+ }
2604
+ } else browser = await browserType.launch(launch);
2136
2605
  if (!browser) throw new Error("Something went wrong with starting the browser.");
2137
2606
  this.browser = browser;
2138
- const tempCtx = await browser.newContext();
2139
- const tempPage = await tempCtx.newPage();
2140
- this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
2141
- await tempCtx.close();
2607
+ this.disconnected = false;
2608
+ browser.on("disconnected", () => {
2609
+ if (this.browser === browser) this.disconnected = true;
2610
+ });
2611
+ if (!contextOptions?.userAgent) {
2612
+ const tempCtx = await browser.newContext();
2613
+ const tempPage = await tempCtx.newPage();
2614
+ this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
2615
+ await tempCtx.close();
2616
+ }
2142
2617
  await this.createContexts();
2143
2618
  }
2144
2619
  /**
2145
2620
  * Create the pool of browser contexts and pages.
2621
+ *
2622
+ * `contextOptions` from the provider merge over cappa's defaults; the
2623
+ * viewport and the `CappaStorybook` user-agent suffix always win, because
2624
+ * plugins and `isCappa()` rely on them.
2146
2625
  */
2147
2626
  async createContexts() {
2148
2627
  const browser = this.browser;
2149
2628
  if (!browser) throw new Error("Browser not initialized");
2629
+ const { contextOptions, actionTimeout } = this.browserConfig.provider.options;
2630
+ const { viewport: _ignored, ...extraContextOptions } = contextOptions ?? {};
2150
2631
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
2151
2632
  const context = await browser.newContext({
2152
2633
  reducedMotion: "reduce",
2153
- deviceScaleFactor: 2,
2154
- userAgent: `${this.defaultUserAgent} CappaStorybook`,
2634
+ deviceScaleFactor: DEFAULT_DEVICE_SCALE_FACTOR,
2635
+ ...extraContextOptions,
2636
+ userAgent: `${contextOptions?.userAgent ?? this.defaultUserAgent} CappaStorybook`,
2155
2637
  viewport: this.viewport
2156
2638
  });
2639
+ if (actionTimeout) context.setDefaultTimeout(actionTimeout);
2157
2640
  return {
2158
2641
  context,
2159
2642
  page: await context.newPage()
@@ -2208,13 +2691,23 @@ var ScreenshotTool = class {
2208
2691
  this.context = null;
2209
2692
  this.page = null;
2210
2693
  }
2211
- if (this.browser) {
2694
+ const browser = this.browser;
2695
+ if (browser) {
2696
+ this.browser = null;
2212
2697
  try {
2213
- await this.browser.close();
2698
+ await browser.close();
2214
2699
  } catch (error) {
2215
2700
  (0, _cappa_logger.getLogger)().debug("Error closing the browser:", error);
2216
2701
  }
2217
- this.browser = null;
2702
+ }
2703
+ this.disconnected = false;
2704
+ const container = this.container;
2705
+ this.container = null;
2706
+ const options = require_playwright.resolveContainerOptions(this.browserConfig.provider.options.container);
2707
+ if (container && options && !options.keepAlive && !container.reused) try {
2708
+ await container.stop();
2709
+ } catch (error) {
2710
+ (0, _cappa_logger.getLogger)().debug("Error removing the Playwright container:", error);
2218
2711
  }
2219
2712
  }
2220
2713
  /**
@@ -2262,21 +2755,33 @@ var ScreenshotTool = class {
2262
2755
  const clip = crop ? await measureContentClip(page, crop, fullPage) : void 0;
2263
2756
  if (crop && !clip) this.logger.debug(`Nothing painted inside "${crop.root}" to crop to; taking the uncropped screenshot`);
2264
2757
  const screenshotOptions = {
2265
- path: filepath,
2266
2758
  fullPage,
2267
2759
  clip,
2268
2760
  type: "png",
2269
2761
  timeout: 6e4,
2270
2762
  mask: options.mask,
2271
2763
  omitBackground: options.omitBackground,
2272
- scale: "css",
2764
+ scale: options.scale ?? this.scale,
2273
2765
  animations: "disabled",
2274
2766
  caret: "hide"
2275
2767
  };
2276
- 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;
2277
2771
  });
2278
2772
  }
2279
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
+ /**
2280
2785
  * Sets the viewport size and executes the action, ensuring the original viewport is restored
2281
2786
  * even if the action throws an error.
2282
2787
  */
@@ -2311,6 +2816,7 @@ var ScreenshotTool = class {
2311
2816
  const screenshotSettings = {
2312
2817
  fullPage: options.fullPage ?? this.fullPage,
2313
2818
  crop: options.crop,
2819
+ scale: options.scale,
2314
2820
  mask: options.mask,
2315
2821
  omitBackground: options.omitBackground,
2316
2822
  delay: options.delay,
@@ -2336,7 +2842,7 @@ var ScreenshotTool = class {
2336
2842
  });
2337
2843
  }
2338
2844
  if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
2339
- this.logger.warn(`Screenshot has different sizes than reference image`);
2845
+ if (!retryScreenshot.pixelRatio) this.logger.warn(`Screenshot has different sizes than reference image`);
2340
2846
  if (!diffImagePath) {
2341
2847
  const diffFilename = options.diffImageFilename || filename;
2342
2848
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
@@ -2348,7 +2854,8 @@ var ScreenshotTool = class {
2348
2854
  return {
2349
2855
  screenshotPath: filepath,
2350
2856
  comparisonResult: retryScreenshot.comparisonResult,
2351
- diffImagePath
2857
+ diffImagePath,
2858
+ ...retryScreenshot.pixelRatio ? { pixelRatio: retryScreenshot.pixelRatio } : {}
2352
2859
  };
2353
2860
  } catch (error) {
2354
2861
  this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
@@ -2357,19 +2864,27 @@ var ScreenshotTool = class {
2357
2864
  }
2358
2865
  async retryScreenshot(page, referenceImage, options, diffOverride) {
2359
2866
  const diffConfig = this.mergeDiffOptions(diffOverride);
2360
- 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 {
2361
2875
  const screenshotBuffer = await this.takeScreenshotBuffer(page, {
2362
2876
  ...options,
2363
2877
  delay: this.getIncBackoffDelay(i, options.delay || 0)
2364
2878
  });
2365
2879
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
2366
2880
  const comparisonResult = diffConfig.type === "gmsd" ? await compareImagesGMSD(referenceImage, screenshotBuffer, true, diffConfig) : await compareImages(referenceImage, screenshotBuffer, true, diffConfig);
2367
- if (i === this.retries - 1 && !comparisonResult.passed) {
2368
- 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`);
2369
2883
  return {
2370
2884
  screenshotPath: screenshotBuffer,
2371
2885
  comparisonResult,
2372
- passed: false
2886
+ passed: false,
2887
+ ...ratioMismatch ? { pixelRatio } : {}
2373
2888
  };
2374
2889
  }
2375
2890
  if (comparisonResult.passed) return {
@@ -2785,7 +3300,11 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2785
3300
  const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
2786
3301
  const expectedScreenshot = expectedByRelativePath.get(relativePath);
2787
3302
  const diffScreenshot = diffByRelativePath.get(relativePath);
2788
- 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
+ ]);
2789
3308
  screenshotRepresentations.push({
2790
3309
  id,
2791
3310
  name,
@@ -2793,7 +3312,8 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2793
3312
  expectedPath: expectedScreenshot ? node_path.default.relative(outputDir, expectedScreenshot) : void 0,
2794
3313
  diffPath: diffScreenshot ? node_path.default.relative(outputDir, diffScreenshot) : void 0,
2795
3314
  actualPath: node_path.default.relative(outputDir, screenshot),
2796
- ...diffMeta ? { diffMeta } : {}
3315
+ ...diffMeta ? { diffMeta } : {},
3316
+ ...pixelRatios(actualPixelRatio, expectedPixelRatio)
2797
3317
  });
2798
3318
  }
2799
3319
  for (const expectedScreenshot of expectedScreenshots) {
@@ -2805,13 +3325,19 @@ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScre
2805
3325
  id,
2806
3326
  name,
2807
3327
  category: "deleted",
2808
- expectedPath: node_path.default.relative(outputDir, expectedScreenshot)
3328
+ expectedPath: node_path.default.relative(outputDir, expectedScreenshot),
3329
+ ...pixelRatios(1, await readPixelRatio(expectedScreenshot))
2809
3330
  });
2810
3331
  }
2811
3332
  return screenshotRepresentations.sort((a, b) => {
2812
3333
  return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
2813
3334
  });
2814
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
+ });
2815
3341
  const buildCategory = (expectedScreenshot, diffScreenshot) => {
2816
3342
  if (expectedScreenshot && diffScreenshot) return "changed";
2817
3343
  if (expectedScreenshot) return "passed";
@@ -3452,6 +3978,13 @@ var WarmBrowser = class {
3452
3978
  if (this.closed) throw new Error("WarmBrowser has been closed");
3453
3979
  this.cancelIdleTimer();
3454
3980
  this.inUse = true;
3981
+ if (this.tool?.disconnected === true) {
3982
+ const dead = this.tool;
3983
+ this.tool = null;
3984
+ try {
3985
+ await dead.close();
3986
+ } catch {}
3987
+ }
3455
3988
  if (this.tool) {
3456
3989
  await this.tool.recycleContexts();
3457
3990
  return this.tool;
@@ -3994,11 +4527,13 @@ var LocalEngine = class {
3994
4527
  logConsoleEvents: this.options.logConsoleEvents,
3995
4528
  fullPage: this.options.fullPage ?? true,
3996
4529
  crop: this.options.crop ?? false,
4530
+ scale: this.options.scale ?? "css",
3997
4531
  viewport: this.options.viewport ?? {
3998
4532
  width: 1920,
3999
4533
  height: 1080
4000
4534
  },
4001
- connectionTimeout: this.options.connectionTimeout
4535
+ connectionTimeout: this.options.connectionTimeout,
4536
+ browser: this.options.browser
4002
4537
  });
4003
4538
  }
4004
4539
  async listPlugins() {
@@ -5039,7 +5574,9 @@ exports.ACTION_BY_LABEL = ACTION_BY_LABEL;
5039
5574
  exports.AGENT_DIRNAME = AGENT_DIRNAME;
5040
5575
  exports.AGENT_REPORT_VERSION = AGENT_REPORT_VERSION;
5041
5576
  exports.CONSOLE_LOG_LEVELS = CONSOLE_LOG_LEVELS;
5577
+ exports.CONTAINER_LABEL = CONTAINER_LABEL;
5042
5578
  exports.CaptureRunner = CaptureRunner;
5579
+ exports.DEFAULT_CONTAINER_IMAGE = require_playwright.DEFAULT_CONTAINER_IMAGE;
5043
5580
  exports.DEFAULT_CROP_PADDING = DEFAULT_CROP_PADDING;
5044
5581
  exports.DEFAULT_DEBOUNCE_MS = DEFAULT_DEBOUNCE_MS;
5045
5582
  exports.DEFAULT_IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
@@ -5053,6 +5590,7 @@ exports.MANIFEST_FILENAME = MANIFEST_FILENAME;
5053
5590
  exports.MANIFEST_VERSION = MANIFEST_VERSION;
5054
5591
  exports.NO_WEB_SERVER_HINT = NO_WEB_SERVER_HINT;
5055
5592
  exports.OutputTail = OutputTail;
5593
+ exports.PIXEL_RATIO_KEY = PIXEL_RATIO_KEY;
5056
5594
  exports.RunInProgressError = RunInProgressError;
5057
5595
  exports.RunStore = RunStore;
5058
5596
  exports.ScreenshotFileSystem = ScreenshotFileSystem;
@@ -5074,7 +5612,9 @@ exports.compareImagesGMSD = compareImagesGMSD;
5074
5612
  exports.contextPadding = contextPadding;
5075
5613
  exports.defineConfig = defineConfig;
5076
5614
  exports.describeChange = describeChange;
5615
+ exports.describePixelRatioMismatch = describePixelRatioMismatch;
5077
5616
  exports.didScreenshotFail = didScreenshotFail;
5617
+ exports.ensurePlaywrightContainer = ensurePlaywrightContainer;
5078
5618
  exports.filterTasks = filterTasks;
5079
5619
  exports.findRefusedConnection = findRefusedConnection;
5080
5620
  exports.fingerprintImages = fingerprintImages;
@@ -5094,12 +5634,17 @@ exports.mergeCaptureManifest = mergeCaptureManifest;
5094
5634
  exports.normalizeChangeType = normalizeChangeType;
5095
5635
  exports.padAndClamp = padAndClamp;
5096
5636
  exports.parseAgentVerdict = parseAgentVerdict;
5637
+ exports.playwright = require_playwright.playwright;
5097
5638
  exports.readAgentReport = readAgentReport;
5098
5639
  exports.readCaptureManifest = readCaptureManifest;
5099
5640
  exports.readDiffMeta = readDiffMeta;
5641
+ exports.readPixelRatio = readPixelRatio;
5100
5642
  exports.recordCaptureOrigins = recordCaptureOrigins;
5643
+ exports.removePlaywrightContainers = removePlaywrightContainers;
5101
5644
  exports.renderJudgmentTiles = renderJudgmentTiles;
5102
5645
  exports.renderOverview = renderOverview;
5646
+ exports.resolveBrowserConfig = require_playwright.resolveBrowserConfig;
5647
+ exports.resolveContainerOptions = require_playwright.resolveContainerOptions;
5103
5648
  exports.resolveCrop = resolveCrop;
5104
5649
  exports.resolveWebServerConfig = resolveWebServerConfig;
5105
5650
  exports.runAgentCheck = runAgentCheck;
@@ -5114,6 +5659,7 @@ exports.toSerializedError = toSerializedError;
5114
5659
  exports.toSlimAgentReport = toSlimAgentReport;
5115
5660
  exports.toTaskStatus = toTaskStatus;
5116
5661
  exports.waitForUrl = waitForUrl;
5662
+ exports.withPixelRatio = withPixelRatio;
5117
5663
  exports.writeAgentVerdict = writeAgentVerdict;
5118
5664
 
5119
5665
  //# sourceMappingURL=index.cjs.map