@cappa/core 0.18.0 → 0.19.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 +386 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +99 -3
- package/dist/index.d.mts +99 -3
- package/dist/index.mjs +381 -21
- package/dist/index.mjs.map +1 -1
- package/dist/playwright.cjs +77 -0
- package/dist/playwright.cjs.map +1 -0
- package/dist/playwright.d.cts +117 -0
- package/dist/playwright.d.mts +117 -0
- package/dist/playwright.mjs +73 -0
- package/dist/playwright.mjs.map +1 -0
- package/package.json +5 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import
|
|
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. */
|
|
@@ -1991,9 +2229,56 @@ const LOG_SINK_LEVELS = [
|
|
|
1991
2229
|
];
|
|
1992
2230
|
/** A logger-shaped object that forwards every call to `sink`. */
|
|
1993
2231
|
const toSinkLogger = (sink) => Object.fromEntries(LOG_SINK_LEVELS.map((level) => [level, (message, ...args) => sink(level, String(message), ...args)]));
|
|
2232
|
+
const browserMap = {
|
|
2233
|
+
chromium,
|
|
2234
|
+
firefox,
|
|
2235
|
+
webkit
|
|
2236
|
+
};
|
|
2237
|
+
/** Where the remote-browser recipe lives; linked from connection errors. */
|
|
2238
|
+
const REMOTE_BROWSER_DOCS = "https://tim-richter.github.io/cappa/configuration/#connecting-to-a-remote-browser";
|
|
2239
|
+
/** The installed `playwright-core` version, or `null` if it cannot be read. */
|
|
2240
|
+
const clientPlaywrightVersion = () => {
|
|
2241
|
+
try {
|
|
2242
|
+
return createRequire(import.meta.url)("playwright-core/package.json").version;
|
|
2243
|
+
} catch {
|
|
2244
|
+
return null;
|
|
2245
|
+
}
|
|
2246
|
+
};
|
|
2247
|
+
/** The installed `playwright-core` directory, symlinks resolved, or `null`. */
|
|
2248
|
+
const clientPlaywrightPackageDir = () => {
|
|
2249
|
+
try {
|
|
2250
|
+
const require = createRequire(import.meta.url);
|
|
2251
|
+
return realpathSync(path.dirname(require.resolve("playwright-core/package.json")));
|
|
2252
|
+
} catch {
|
|
2253
|
+
return null;
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
/**
|
|
2257
|
+
* Turn a raw `browserType.connect()` failure into something actionable.
|
|
2258
|
+
*
|
|
2259
|
+
* Exported for tests.
|
|
2260
|
+
*/
|
|
2261
|
+
const describeConnectError = (error, wsEndpoint, clientVersion = clientPlaywrightVersion(), container) => {
|
|
2262
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2263
|
+
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 });
|
|
2264
|
+
if (/version mismatch/i.test(message) || /\b428\b/.test(message)) {
|
|
2265
|
+
const image = clientVersion ? `mcr.microsoft.com/playwright:v${clientVersion}-noble` : "the mcr.microsoft.com/playwright image matching your playwright-core";
|
|
2266
|
+
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 });
|
|
2267
|
+
}
|
|
2268
|
+
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 });
|
|
2269
|
+
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 });
|
|
2270
|
+
};
|
|
1994
2271
|
var ScreenshotTool = class {
|
|
1995
2272
|
browserType;
|
|
1996
2273
|
headless;
|
|
2274
|
+
/** Browser provider, headless mode and instance — see `UserConfig.browser`. */
|
|
2275
|
+
browserConfig;
|
|
2276
|
+
/**
|
|
2277
|
+
* Set when the browser goes away underneath the tool — a remote browser
|
|
2278
|
+
* server restarting, or a local browser crashing. `WarmBrowser` checks it so
|
|
2279
|
+
* it starts a fresh browser instead of handing out a dead one.
|
|
2280
|
+
*/
|
|
2281
|
+
disconnected = false;
|
|
1997
2282
|
viewport;
|
|
1998
2283
|
fullPage;
|
|
1999
2284
|
/** Default content crop; a screenshot's own `crop` overrides it. */
|
|
@@ -2018,14 +2303,20 @@ var ScreenshotTool = class {
|
|
|
2018
2303
|
filesystem;
|
|
2019
2304
|
logConsoleEvents;
|
|
2020
2305
|
connectionTimeout;
|
|
2306
|
+
/** The container `init()` started or reused, when `container` is on. */
|
|
2307
|
+
container = null;
|
|
2021
2308
|
defaultUserAgent = "";
|
|
2022
2309
|
/** The real logger, kept so `setLogSink(null)` restores the same instance. */
|
|
2023
2310
|
baseLogger;
|
|
2024
2311
|
/** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
|
|
2025
2312
|
captureSink = null;
|
|
2026
2313
|
constructor(options) {
|
|
2027
|
-
this.
|
|
2028
|
-
|
|
2314
|
+
this.browserConfig = resolveBrowserConfig(options.browser ?? {
|
|
2315
|
+
headless: options.headless !== false,
|
|
2316
|
+
instances: [{ browser: options.browserType || "chromium" }]
|
|
2317
|
+
});
|
|
2318
|
+
this.browserType = this.browserConfig.instances[0].browser;
|
|
2319
|
+
this.headless = this.browserConfig.headless;
|
|
2029
2320
|
this.viewport = options.viewport || {
|
|
2030
2321
|
width: 1920,
|
|
2031
2322
|
height: 1080
|
|
@@ -2100,34 +2391,85 @@ var ScreenshotTool = class {
|
|
|
2100
2391
|
* Initialize playwright and page
|
|
2101
2392
|
*/
|
|
2102
2393
|
async init() {
|
|
2103
|
-
const
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2394
|
+
const browserType = browserMap[this.browserType];
|
|
2395
|
+
if (!browserType) throw new Error(`Unsupported browser type: ${this.browserType}`);
|
|
2396
|
+
const { launchOptions, connectOptions, contextOptions } = this.browserConfig.provider.options;
|
|
2397
|
+
const launch = {
|
|
2398
|
+
...launchOptions,
|
|
2399
|
+
headless: this.headless
|
|
2400
|
+
};
|
|
2401
|
+
const container = resolveContainerOptions(this.browserConfig.provider.options.container);
|
|
2402
|
+
let connect = connectOptions?.wsEndpoint ? {
|
|
2403
|
+
...connectOptions,
|
|
2404
|
+
wsEndpoint: connectOptions.wsEndpoint
|
|
2405
|
+
} : null;
|
|
2406
|
+
if (connect && container) this.logger.debug(`connectOptions.wsEndpoint is set (${connect.wsEndpoint}); not starting a container.`);
|
|
2407
|
+
else if (container) {
|
|
2408
|
+
const version = clientPlaywrightVersion();
|
|
2409
|
+
const packageDir = clientPlaywrightPackageDir();
|
|
2410
|
+
if (!version || !packageDir) throw new Error("playwright({ container }) needs the installed playwright-core, but its package.json could not be read.");
|
|
2411
|
+
this.container = await ensurePlaywrightContainer({
|
|
2412
|
+
...container,
|
|
2413
|
+
version,
|
|
2414
|
+
packageDir,
|
|
2415
|
+
log: (message) => this.logger.info(message)
|
|
2416
|
+
});
|
|
2417
|
+
connect = {
|
|
2418
|
+
exposeNetwork: "<loopback>",
|
|
2419
|
+
...connectOptions,
|
|
2420
|
+
wsEndpoint: this.container.wsEndpoint
|
|
2421
|
+
};
|
|
2422
|
+
}
|
|
2423
|
+
let browser;
|
|
2424
|
+
if (connect) {
|
|
2425
|
+
const { wsEndpoint, ...options } = connect;
|
|
2426
|
+
try {
|
|
2427
|
+
browser = await browserType.connect(wsEndpoint, {
|
|
2428
|
+
...options,
|
|
2429
|
+
headers: {
|
|
2430
|
+
"x-playwright-launch-options": JSON.stringify(launch),
|
|
2431
|
+
...options.headers
|
|
2432
|
+
}
|
|
2433
|
+
});
|
|
2434
|
+
} catch (error) {
|
|
2435
|
+
throw describeConnectError(error, wsEndpoint, void 0, this.container ?? void 0);
|
|
2436
|
+
}
|
|
2437
|
+
} else browser = await browserType.launch(launch);
|
|
2110
2438
|
if (!browser) throw new Error("Something went wrong with starting the browser.");
|
|
2111
2439
|
this.browser = browser;
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2440
|
+
this.disconnected = false;
|
|
2441
|
+
browser.on("disconnected", () => {
|
|
2442
|
+
if (this.browser === browser) this.disconnected = true;
|
|
2443
|
+
});
|
|
2444
|
+
if (!contextOptions?.userAgent) {
|
|
2445
|
+
const tempCtx = await browser.newContext();
|
|
2446
|
+
const tempPage = await tempCtx.newPage();
|
|
2447
|
+
this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
|
|
2448
|
+
await tempCtx.close();
|
|
2449
|
+
}
|
|
2116
2450
|
await this.createContexts();
|
|
2117
2451
|
}
|
|
2118
2452
|
/**
|
|
2119
2453
|
* Create the pool of browser contexts and pages.
|
|
2454
|
+
*
|
|
2455
|
+
* `contextOptions` from the provider merge over cappa's defaults; the
|
|
2456
|
+
* viewport and the `CappaStorybook` user-agent suffix always win, because
|
|
2457
|
+
* plugins and `isCappa()` rely on them.
|
|
2120
2458
|
*/
|
|
2121
2459
|
async createContexts() {
|
|
2122
2460
|
const browser = this.browser;
|
|
2123
2461
|
if (!browser) throw new Error("Browser not initialized");
|
|
2462
|
+
const { contextOptions, actionTimeout } = this.browserConfig.provider.options;
|
|
2463
|
+
const { viewport: _ignored, ...extraContextOptions } = contextOptions ?? {};
|
|
2124
2464
|
const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
|
|
2125
2465
|
const context = await browser.newContext({
|
|
2126
2466
|
reducedMotion: "reduce",
|
|
2127
2467
|
deviceScaleFactor: 2,
|
|
2128
|
-
|
|
2468
|
+
...extraContextOptions,
|
|
2469
|
+
userAgent: `${contextOptions?.userAgent ?? this.defaultUserAgent} CappaStorybook`,
|
|
2129
2470
|
viewport: this.viewport
|
|
2130
2471
|
});
|
|
2472
|
+
if (actionTimeout) context.setDefaultTimeout(actionTimeout);
|
|
2131
2473
|
return {
|
|
2132
2474
|
context,
|
|
2133
2475
|
page: await context.newPage()
|
|
@@ -2182,13 +2524,23 @@ var ScreenshotTool = class {
|
|
|
2182
2524
|
this.context = null;
|
|
2183
2525
|
this.page = null;
|
|
2184
2526
|
}
|
|
2185
|
-
|
|
2527
|
+
const browser = this.browser;
|
|
2528
|
+
if (browser) {
|
|
2529
|
+
this.browser = null;
|
|
2186
2530
|
try {
|
|
2187
|
-
await
|
|
2531
|
+
await browser.close();
|
|
2188
2532
|
} catch (error) {
|
|
2189
2533
|
getLogger().debug("Error closing the browser:", error);
|
|
2190
2534
|
}
|
|
2191
|
-
|
|
2535
|
+
}
|
|
2536
|
+
this.disconnected = false;
|
|
2537
|
+
const container = this.container;
|
|
2538
|
+
this.container = null;
|
|
2539
|
+
const options = resolveContainerOptions(this.browserConfig.provider.options.container);
|
|
2540
|
+
if (container && options && !options.keepAlive && !container.reused) try {
|
|
2541
|
+
await container.stop();
|
|
2542
|
+
} catch (error) {
|
|
2543
|
+
getLogger().debug("Error removing the Playwright container:", error);
|
|
2192
2544
|
}
|
|
2193
2545
|
}
|
|
2194
2546
|
/**
|
|
@@ -3426,6 +3778,13 @@ var WarmBrowser = class {
|
|
|
3426
3778
|
if (this.closed) throw new Error("WarmBrowser has been closed");
|
|
3427
3779
|
this.cancelIdleTimer();
|
|
3428
3780
|
this.inUse = true;
|
|
3781
|
+
if (this.tool?.disconnected === true) {
|
|
3782
|
+
const dead = this.tool;
|
|
3783
|
+
this.tool = null;
|
|
3784
|
+
try {
|
|
3785
|
+
await dead.close();
|
|
3786
|
+
} catch {}
|
|
3787
|
+
}
|
|
3429
3788
|
if (this.tool) {
|
|
3430
3789
|
await this.tool.recycleContexts();
|
|
3431
3790
|
return this.tool;
|
|
@@ -3972,7 +4331,8 @@ var LocalEngine = class {
|
|
|
3972
4331
|
width: 1920,
|
|
3973
4332
|
height: 1080
|
|
3974
4333
|
},
|
|
3975
|
-
connectionTimeout: this.options.connectionTimeout
|
|
4334
|
+
connectionTimeout: this.options.connectionTimeout,
|
|
4335
|
+
browser: this.options.browser
|
|
3976
4336
|
});
|
|
3977
4337
|
}
|
|
3978
4338
|
async listPlugins() {
|
|
@@ -5009,6 +5369,6 @@ function resolveWebServerConfig(webServer, configDir, env = process.env) {
|
|
|
5009
5369
|
});
|
|
5010
5370
|
}
|
|
5011
5371
|
//#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 };
|
|
5372
|
+
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, RunInProgressError, RunStore, ScreenshotFileSystem, ScreenshotTool, UnknownTargetsError, VERDICT_LABELS, WarmBrowser, WatchInProgressError, WatchSession, WebServerError, WebServerPool, agentDir, agentReportPath, attachConsoleLogging, clearJudgment, collectScreenshots, compareImages, compareImagesGMSD, contextPadding, defineConfig, describeChange, 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, recordCaptureOrigins, removePlaywrightContainers, renderJudgmentTiles, renderOverview, resolveBrowserConfig, resolveContainerOptions, resolveCrop, resolveWebServerConfig, runAgentCheck, sameServer, sanitizeScreenshotFilename, selectTasks, spawnServerProcess, toConsoleLogLevel, toDiffMetaPath, toManifestKey, toSerializedError, toSlimAgentReport, toTaskStatus, waitForUrl, writeAgentVerdict };
|
|
5013
5373
|
|
|
5014
5374
|
//# sourceMappingURL=index.mjs.map
|