@pixsame/playwright-visual-regression-diff 0.0.0-stage → 0.0.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.
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.expect = exports.test = exports.visualRegressionFixtures = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const test_1 = require("@playwright/test");
9
+ const compare_1 = require("./compare");
10
+ const constants_1 = require("./constants");
11
+ const fs_utils_1 = require("./fs.utils");
12
+ const manifest_utils_1 = require("./manifest.utils");
13
+ const screenshotPath_1 = require("./screenshotPath");
14
+ const withDefaults = (globals, options) => {
15
+ const merged = { ...globals, ...options };
16
+ return {
17
+ imagesPath: merged.imagesPath ?? constants_1.DEFAULT_IMAGES_PATH,
18
+ maxDiffThreshold: merged.maxDiffThreshold ?? 0.01,
19
+ diffConfig: merged.diffConfig ?? {},
20
+ createMissingImages: merged.createMissingImages ?? true,
21
+ updateImages: merged.updateImages ?? false,
22
+ title: merged.title,
23
+ matchAgainstPath: merged.matchAgainstPath,
24
+ screenshotConfig: merged.screenshotConfig ?? {},
25
+ deterministicRendering: merged.deterministicRendering ?? true,
26
+ };
27
+ };
28
+ exports.visualRegressionFixtures = {
29
+ visualRegression: [{}, { option: true }],
30
+ visualRegressionManifestPath: [undefined, { option: true, scope: 'worker' }],
31
+ visualRegressionManifest: [
32
+ async ({ browser, browserName, headless, visualRegressionManifestPath }, use, workerInfo) => {
33
+ const { config, project, parallelIndex, workerIndex } = workerInfo;
34
+ const manifestPath = (0, manifest_utils_1.manifestPathFor)(visualRegressionManifestPath, {
35
+ rootDir: config.rootDir,
36
+ outputDir: project.outputDir,
37
+ workerIndex,
38
+ });
39
+ const options = {
40
+ ...(project.use
41
+ .visualRegression ?? {}),
42
+ ...(visualRegressionManifestPath !== undefined && {
43
+ manifestPath: visualRegressionManifestPath,
44
+ }),
45
+ };
46
+ const writer = manifestPath
47
+ ? (0, manifest_utils_1.createManifestWriter)(manifestPath, {
48
+ config,
49
+ project,
50
+ parallelIndex,
51
+ workerIndex,
52
+ browser: {
53
+ name: browserName,
54
+ version: browser.version(),
55
+ headless,
56
+ },
57
+ options,
58
+ })
59
+ : null;
60
+ await use(writer);
61
+ },
62
+ { scope: 'worker' },
63
+ ],
64
+ visualRegressionComparer: [
65
+ async ({ visualRegressionManifest }, use, workerInfo) => {
66
+ const comparer = await (0, compare_1.createComparison)(visualRegressionManifest, {
67
+ rootDir: workerInfo.config.rootDir,
68
+ });
69
+ await use(comparer);
70
+ await comparer.close();
71
+ },
72
+ { scope: 'worker' },
73
+ ],
74
+ matchImage: async ({ page, browser, browserName, headless, visualRegression, visualRegressionComparer, }, use, testInfo) => {
75
+ const namer = new screenshotPath_1.ScreenshotNamer();
76
+ const rootDir = testInfo.config.rootDir;
77
+ const specPath = (0, fs_utils_1.toPosix)(path_1.default.relative(rootDir, testInfo.file));
78
+ const renderer = (0, manifest_utils_1.rendererFor)(browserName, browser.version());
79
+ await use(async (target = page, options = {}) => {
80
+ const cfg = withDefaults(visualRegression, options);
81
+ const dir = (0, screenshotPath_1.resolveImagesDir)({
82
+ imagesPath: cfg.imagesPath,
83
+ specPath,
84
+ rootDir,
85
+ pathVariables: { os: process.platform, browser: browserName },
86
+ });
87
+ const title = cfg.title ?? testInfo.titlePath.slice(1).join(' ');
88
+ const name = namer.next(dir, title);
89
+ const actualPath = path_1.default.join(dir, `${name}${constants_1.FILE_SUFFIX.actual}.png`);
90
+ const baselinePath = cfg.matchAgainstPath
91
+ ? path_1.default.resolve(rootDir, cfg.matchAgainstPath)
92
+ : path_1.default.join(dir, `${name}.png`);
93
+ const imgNew = await target.screenshot({
94
+ ...(cfg.deterministicRendering && {
95
+ animations: 'disabled',
96
+ caret: 'hide',
97
+ }),
98
+ ...cfg.screenshotConfig,
99
+ });
100
+ const viewport = page.viewportSize() ?? undefined;
101
+ const result = await (0, compare_1.compareImages)({
102
+ imgNew,
103
+ actualPath,
104
+ baselinePath,
105
+ createMissingImages: cfg.createMissingImages,
106
+ updateImages: cfg.updateImages,
107
+ maxDiffThreshold: cfg.maxDiffThreshold,
108
+ diffConfig: cfg.diffConfig,
109
+ name,
110
+ test: {
111
+ filePath: testInfo.file,
112
+ titlePath: testInfo.titlePath.slice(1),
113
+ retry: testInfo.retry,
114
+ },
115
+ platform: {
116
+ osPlatform: process.platform,
117
+ arch: process.arch,
118
+ browser: {
119
+ name: browserName,
120
+ version: browser.version(),
121
+ headless,
122
+ },
123
+ },
124
+ viewport,
125
+ entry: { options: (0, manifest_utils_1.toManifestOptions)(cfg), renderer },
126
+ }, visualRegressionComparer);
127
+ const matchImageResult = {
128
+ status: result.status,
129
+ message: result.message,
130
+ diffValue: result.imgOld ? result.diffRatio : undefined,
131
+ imgPath: baselinePath,
132
+ imgNewPath: actualPath,
133
+ imgDiffPath: result.diffPath,
134
+ imgNew: result.imgNew,
135
+ img: result.imgOld,
136
+ imgDiff: result.imgDiff,
137
+ };
138
+ if (result.error) {
139
+ // the three images land in the HTML report next to the failure
140
+ const attach = (label, body) => body &&
141
+ testInfo.attach(`${name} (${label})`, {
142
+ body,
143
+ contentType: 'image/png',
144
+ });
145
+ // one after another, so the report lists them in a stable order
146
+ await attach('baseline', result.imgOld);
147
+ await attach('actual', result.imgNew ?? imgNew);
148
+ await attach('diff', result.imgDiff);
149
+ throw new Error(`[${name}] ${result.message}`);
150
+ }
151
+ return matchImageResult;
152
+ });
153
+ },
154
+ };
155
+ exports.test = test_1.test.extend(exports.visualRegressionFixtures);
156
+ var test_2 = require("@playwright/test");
157
+ Object.defineProperty(exports, "expect", { enumerable: true, get: function () { return test_2.expect; } });
@@ -0,0 +1,5 @@
1
+ export declare const toPosix: (p: string) => string;
2
+ export declare const unlinkSafe: (file: string) => void;
3
+ /** Moves a file, falling back to copy + delete when the target is on another device. */
4
+ export declare const moveFile: (from: string, to: string) => void;
5
+ export declare const writeFileEnsuringDir: (file: string, data: Buffer | string) => void;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.writeFileEnsuringDir = exports.moveFile = exports.unlinkSafe = exports.toPosix = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const toPosix = (p) => path_1.default.sep === '/' ? p : p.split(path_1.default.sep).join('/');
10
+ exports.toPosix = toPosix;
11
+ const unlinkSafe = (file) => {
12
+ if (fs_1.default.existsSync(file))
13
+ fs_1.default.unlinkSync(file);
14
+ };
15
+ exports.unlinkSafe = unlinkSafe;
16
+ /** Moves a file, falling back to copy + delete when the target is on another device. */
17
+ const moveFile = (from, to) => {
18
+ fs_1.default.mkdirSync(path_1.default.dirname(to), { recursive: true });
19
+ try {
20
+ fs_1.default.renameSync(from, to);
21
+ }
22
+ catch (error) {
23
+ /* c8 ignore next 4 */
24
+ if (error.code !== 'EXDEV')
25
+ throw error;
26
+ fs_1.default.copyFileSync(from, to);
27
+ fs_1.default.unlinkSync(from);
28
+ }
29
+ };
30
+ exports.moveFile = moveFile;
31
+ const writeFileEnsuringDir = (file, data) => {
32
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
33
+ fs_1.default.writeFileSync(file, data);
34
+ };
35
+ exports.writeFileEnsuringDir = writeFileEnsuringDir;
@@ -0,0 +1,13 @@
1
+ type PluginMetadata = {
2
+ version: string;
3
+ testingType?: string;
4
+ };
5
+ /** Stamps the plugin marker into the PNG so the file is recognised as plugin output later. */
6
+ export declare const addPNGMetadata: (png: Buffer) => Buffer;
7
+ export declare const getPNGMetadata: (png: Buffer) => PluginMetadata | undefined;
8
+ export declare const isImageCurrentVersion: (png: Buffer) => boolean;
9
+ export type ImageInfo = {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ export {};
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isImageCurrentVersion = exports.getPNGMetadata = exports.addPNGMetadata = void 0;
4
+ // named imports: meta-png is a UMD bundle without an ES default export
5
+ const meta_png_1 = require("meta-png");
6
+ const constants_1 = require("./constants");
7
+ /** Stamps the plugin marker into the PNG so the file is recognised as plugin output later. */
8
+ const addPNGMetadata = (png) => {
9
+ const stamped = (0, meta_png_1.addMetadata)(new Uint8Array(png), constants_1.METADATA_KEY, JSON.stringify({
10
+ version: constants_1.DIFF_IMAGES_VERSION,
11
+ testingType: 'playwright',
12
+ }));
13
+ return Buffer.from(stamped.buffer, stamped.byteOffset, stamped.byteLength);
14
+ };
15
+ exports.addPNGMetadata = addPNGMetadata;
16
+ const getPNGMetadata = (png) => {
17
+ const metadataString = (0, meta_png_1.getMetadata)(new Uint8Array(png), constants_1.METADATA_KEY);
18
+ if (metadataString === undefined)
19
+ return;
20
+ try {
21
+ return JSON.parse(metadataString);
22
+ }
23
+ catch {
24
+ return { version: metadataString };
25
+ }
26
+ };
27
+ exports.getPNGMetadata = getPNGMetadata;
28
+ const isImageCurrentVersion = (png) => (0, exports.getPNGMetadata)(png)?.version === constants_1.DIFF_IMAGES_VERSION;
29
+ exports.isImageCurrentVersion = isImageCurrentVersion;
@@ -0,0 +1,4 @@
1
+ export { test, expect, visualRegressionFixtures, type MatchImage, type MatchImageOptions, type MatchImageResult, type VisualRegressionOptions, type VisualRegressionTestFixtures, type VisualRegressionWorkerFixtures, } from './fixture';
2
+ export { compareImages, createComparison, type CompareInput, type CompareResult, type CompareStatus, } from './compare';
3
+ export { manifestFileNameFor, rendererFor, type ManifestWorkerInput, } from './manifest.utils';
4
+ export { DEFAULT_IMAGES_PATH, PATH_VARIABLES } from './constants';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PATH_VARIABLES = exports.DEFAULT_IMAGES_PATH = exports.rendererFor = exports.manifestFileNameFor = exports.createComparison = exports.compareImages = exports.visualRegressionFixtures = exports.expect = exports.test = void 0;
4
+ var fixture_1 = require("./fixture");
5
+ Object.defineProperty(exports, "test", { enumerable: true, get: function () { return fixture_1.test; } });
6
+ Object.defineProperty(exports, "expect", { enumerable: true, get: function () { return fixture_1.expect; } });
7
+ Object.defineProperty(exports, "visualRegressionFixtures", { enumerable: true, get: function () { return fixture_1.visualRegressionFixtures; } });
8
+ var compare_1 = require("./compare");
9
+ Object.defineProperty(exports, "compareImages", { enumerable: true, get: function () { return compare_1.compareImages; } });
10
+ Object.defineProperty(exports, "createComparison", { enumerable: true, get: function () { return compare_1.createComparison; } });
11
+ var manifest_utils_1 = require("./manifest.utils");
12
+ Object.defineProperty(exports, "manifestFileNameFor", { enumerable: true, get: function () { return manifest_utils_1.manifestFileNameFor; } });
13
+ Object.defineProperty(exports, "rendererFor", { enumerable: true, get: function () { return manifest_utils_1.rendererFor; } });
14
+ var constants_1 = require("./constants");
15
+ Object.defineProperty(exports, "DEFAULT_IMAGES_PATH", { enumerable: true, get: function () { return constants_1.DEFAULT_IMAGES_PATH; } });
16
+ Object.defineProperty(exports, "PATH_VARIABLES", { enumerable: true, get: function () { return constants_1.PATH_VARIABLES; } });
@@ -0,0 +1,76 @@
1
+ import type { FullConfig, FullProject } from '@playwright/test';
2
+ import { ManifestWriter, type ManifestEntryOptions, type ManifestRenderer, type ManifestRunner } from 'visual-regression-manifest';
3
+ /**
4
+ * The Playwright side of the run manifest: maps a worker's config onto
5
+ * `ManifestWriter` from `visual-regression-manifest`, which owns
6
+ * the format and the file. Nothing here knows the manifest shape itself.
7
+ */
8
+ /**
9
+ * `visual-regression-manifest.playwright.w<workerIndex>.json`: one file per
10
+ * worker process, merged by the consumer like manifests of several machines.
11
+ *
12
+ * The label is `workerIndex`, not `parallelIndex`: Playwright restarts a
13
+ * worker after a test failure, and the new process keeps the `parallelIndex`
14
+ * but gets a fresh `workerIndex`. A file named after `parallelIndex` would be
15
+ * overwritten by the restarted worker, dropping every entry the earlier
16
+ * process recorded, the failed one included.
17
+ */
18
+ export declare const manifestFileNameFor: (workerIndex: number) => string;
19
+ /** `reports/run.json` -> `reports/run.w3.json`: a configured path still gets one file per worker process. */
20
+ export declare const withWorkerLabel: (file: string, workerIndex: number) => string;
21
+ /**
22
+ * Resolves where a worker writes its manifest: the configured path relative
23
+ * to `rootDir` (with the worker label inserted before the extension), the
24
+ * project's `outputDir` by default, `null` when disabled.
25
+ */
26
+ export declare const manifestPathFor: (option: string | false | undefined, { rootDir, outputDir, workerIndex, }: {
27
+ rootDir: string;
28
+ outputDir: string;
29
+ workerIndex: number;
30
+ }) => string | null;
31
+ /** `tool.name` of the manifests this package writes. */
32
+ export declare const PACKAGE_NAME = "@pixsame/playwright-visual-regression-diff";
33
+ export declare const playwrightVersion: () => string | undefined;
34
+ /** This package's own version, for the manifest's `tool` block. */
35
+ export declare const packageVersion: () => string | undefined;
36
+ /**
37
+ * Where the pixels came from: the remote Docker browser started by
38
+ * `remoteBrowser()` when it is in use (`backend: 'docker'`, identified by the
39
+ * Playwright version of the image and its digest), the local browser
40
+ * otherwise (`backend: 'native'`).
41
+ */
42
+ export declare const rendererFor: (browserName: string, browserVersion: string, env?: NodeJS.ProcessEnv) => ManifestRenderer;
43
+ /** The resolved `matchImage` options an entry records; the same keys as the Cypress plugin's. */
44
+ export type ResolvedMatchImageOptions = {
45
+ imagesPath: string;
46
+ maxDiffThreshold: number;
47
+ /** pixelmatch options. */
48
+ diffConfig: object;
49
+ createMissingImages: boolean;
50
+ updateImages: boolean | 'failures-only';
51
+ title?: string;
52
+ matchAgainstPath?: string;
53
+ /** Playwright's screenshot options; only JSON-serialisable keys are recorded. */
54
+ screenshotConfig: object;
55
+ };
56
+ export declare const toManifestOptions: (cfg: ResolvedMatchImageOptions) => ManifestEntryOptions;
57
+ export type ManifestWorkerInput = {
58
+ config: Pick<FullConfig, 'rootDir' | 'configFile' | 'workers' | 'shard'>;
59
+ project: Pick<FullProject, 'name' | 'testDir' | 'outputDir' | 'retries' | 'use'>;
60
+ /** Slot of the worker, `0..workers - 1`; a restarted worker keeps it. */
61
+ parallelIndex: number;
62
+ /** Unique per worker process for the whole run; a restarted worker gets a new one. */
63
+ workerIndex: number;
64
+ browser: {
65
+ name: string;
66
+ version: string;
67
+ headless: boolean;
68
+ };
69
+ /** Global `matchImage` options as configured in `use`, verbatim. */
70
+ options: Record<string, unknown>;
71
+ env?: NodeJS.ProcessEnv;
72
+ };
73
+ /** The `runner` block: Playwright's identity and the parts of the config that reproduce the run. */
74
+ export declare const runnerFor: ({ config, project, parallelIndex, workerIndex, browser, }: ManifestWorkerInput) => ManifestRunner;
75
+ /** A `ManifestWriter` for one worker, with Playwright's `rootDir` as the project root. */
76
+ export declare const createManifestWriter: (manifestPath: string, input: ManifestWorkerInput) => ManifestWriter;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createManifestWriter = exports.runnerFor = exports.toManifestOptions = exports.rendererFor = exports.packageVersion = exports.playwrightVersion = exports.PACKAGE_NAME = exports.manifestPathFor = exports.withWorkerLabel = exports.manifestFileNameFor = void 0;
7
+ const module_1 = require("module");
8
+ const path_1 = __importDefault(require("path"));
9
+ const visual_regression_manifest_1 = require("visual-regression-manifest");
10
+ const fs_utils_1 = require("./fs.utils");
11
+ const remote_1 = require("./remote");
12
+ /**
13
+ * The Playwright side of the run manifest: maps a worker's config onto
14
+ * `ManifestWriter` from `visual-regression-manifest`, which owns
15
+ * the format and the file. Nothing here knows the manifest shape itself.
16
+ */
17
+ /**
18
+ * `visual-regression-manifest.playwright.w<workerIndex>.json`: one file per
19
+ * worker process, merged by the consumer like manifests of several machines.
20
+ *
21
+ * The label is `workerIndex`, not `parallelIndex`: Playwright restarts a
22
+ * worker after a test failure, and the new process keeps the `parallelIndex`
23
+ * but gets a fresh `workerIndex`. A file named after `parallelIndex` would be
24
+ * overwritten by the restarted worker, dropping every entry the earlier
25
+ * process recorded, the failed one included.
26
+ */
27
+ const manifestFileNameFor = (workerIndex) => (0, visual_regression_manifest_1.getManifestFileName)(`playwright.w${workerIndex}`);
28
+ exports.manifestFileNameFor = manifestFileNameFor;
29
+ /** `reports/run.json` -> `reports/run.w3.json`: a configured path still gets one file per worker process. */
30
+ const withWorkerLabel = (file, workerIndex) => {
31
+ const ext = path_1.default.extname(file);
32
+ return `${file.slice(0, file.length - ext.length)}.w${workerIndex}${ext}`;
33
+ };
34
+ exports.withWorkerLabel = withWorkerLabel;
35
+ /**
36
+ * Resolves where a worker writes its manifest: the configured path relative
37
+ * to `rootDir` (with the worker label inserted before the extension), the
38
+ * project's `outputDir` by default, `null` when disabled.
39
+ */
40
+ const manifestPathFor = (option, { rootDir, outputDir, workerIndex, }) => {
41
+ if (option === false)
42
+ return null;
43
+ if (option)
44
+ return (0, exports.withWorkerLabel)(path_1.default.resolve(rootDir, option), workerIndex);
45
+ return path_1.default.join(outputDir, (0, exports.manifestFileNameFor)(workerIndex));
46
+ };
47
+ exports.manifestPathFor = manifestPathFor;
48
+ /** `tool.name` of the manifests this package writes. */
49
+ exports.PACKAGE_NAME = '@pixsame/playwright-visual-regression-diff';
50
+ /* c8 ignore start */
51
+ const versionOf = (packageJson) => {
52
+ try {
53
+ return (0, module_1.createRequire)(__filename)(packageJson)
54
+ .version;
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ };
60
+ /* c8 ignore stop */
61
+ const playwrightVersion = () => versionOf('@playwright/test/package.json');
62
+ exports.playwrightVersion = playwrightVersion;
63
+ /** This package's own version, for the manifest's `tool` block. */
64
+ const packageVersion = () => versionOf('../package.json');
65
+ exports.packageVersion = packageVersion;
66
+ const relativeToRoot = (rootDir, p) => p ? (0, fs_utils_1.toPosix)(path_1.default.relative(rootDir, p)) || '.' : undefined;
67
+ /**
68
+ * Where the pixels came from: the remote Docker browser started by
69
+ * `remoteBrowser()` when it is in use (`backend: 'docker'`, identified by the
70
+ * Playwright version of the image and its digest), the local browser
71
+ * otherwise (`backend: 'native'`).
72
+ */
73
+ const rendererFor = (browserName, browserVersion, env = process.env) => {
74
+ const remote = (0, remote_1.readRemoteInfo)(env);
75
+ return remote
76
+ ? {
77
+ backend: 'docker',
78
+ browser: browserName,
79
+ browserVersion,
80
+ rendererVersion: remote.playwrightVersion,
81
+ ...(remote.imageDigest && { imageDigest: remote.imageDigest }),
82
+ }
83
+ : { backend: 'native', browser: browserName, browserVersion };
84
+ };
85
+ exports.rendererFor = rendererFor;
86
+ const toManifestOptions = (cfg) => ({
87
+ imagesPath: cfg.imagesPath,
88
+ ...(cfg.title !== undefined && { title: cfg.title }),
89
+ maxDiffRatio: cfg.maxDiffThreshold,
90
+ diffConfig: cfg.diffConfig,
91
+ createMissingImages: cfg.createMissingImages,
92
+ updateImages: cfg.updateImages,
93
+ // Playwright screenshots come at the context's deviceScaleFactor (1 by default); nothing is rescaled
94
+ forceDeviceScaleFactor: false,
95
+ ...(cfg.matchAgainstPath !== undefined && {
96
+ matchAgainstPath: cfg.matchAgainstPath,
97
+ }),
98
+ screenshotConfig: Object.fromEntries(Object.entries(cfg.screenshotConfig).filter(([, value]) => typeof value !== 'function')),
99
+ });
100
+ exports.toManifestOptions = toManifestOptions;
101
+ /** The `runner` block: Playwright's identity and the parts of the config that reproduce the run. */
102
+ const runnerFor = ({ config, project, parallelIndex, workerIndex, browser, }) => ({
103
+ name: 'playwright',
104
+ version: (0, exports.playwrightVersion)(),
105
+ mode: 'run',
106
+ configFile: relativeToRoot(config.rootDir, config.configFile),
107
+ browser,
108
+ baseUrl: project.use.baseURL ?? null,
109
+ viewport: project.use.viewport ?? undefined,
110
+ retries: project.retries,
111
+ project: project.name || undefined,
112
+ testDir: relativeToRoot(config.rootDir, project.testDir),
113
+ outputDir: relativeToRoot(config.rootDir, project.outputDir),
114
+ workers: config.workers,
115
+ shard: config.shard ?? undefined,
116
+ parallelIndex,
117
+ workerIndex,
118
+ });
119
+ exports.runnerFor = runnerFor;
120
+ /** A `ManifestWriter` for one worker, with Playwright's `rootDir` as the project root. */
121
+ const createManifestWriter = (manifestPath, input) => new visual_regression_manifest_1.ManifestWriter(manifestPath, {
122
+ projectRoot: input.config.rootDir,
123
+ tool: { name: exports.PACKAGE_NAME, version: (0, exports.packageVersion)() },
124
+ options: input.options,
125
+ runner: (0, exports.runnerFor)(input),
126
+ ...(input.env && { env: input.env }),
127
+ });
128
+ exports.createManifestWriter = createManifestWriter;
@@ -0,0 +1,104 @@
1
+ export type RemoteBrowserOptions = {
2
+ /** Host port the container publishes `playwright run-server` on. Fixed, because `playwright.config` needs the endpoint before anything runs. @default 3000 */
3
+ port?: number;
4
+ /** Interface the port is published on. @default '127.0.0.1' */
5
+ host?: string;
6
+ /** Must match the `@playwright/test` version of the project exactly; detected from `node_modules` by default. */
7
+ playwrightVersion?: string;
8
+ /** @default `mcr.microsoft.com/playwright:v<playwrightVersion>-noble` */
9
+ image?: string;
10
+ /** Leave the container running after the run so the next `playwright test` reuses it. @default false */
11
+ keepAlive?: boolean;
12
+ /**
13
+ * Lets the remote browser reach hosts that only the machine running the
14
+ * tests can see, e.g. your dev server on `localhost`. `false` turns it off
15
+ * (then use `host.docker.internal` in `baseURL`). @default '<loopback>'
16
+ */
17
+ exposeNetwork?: string | false;
18
+ /** Extra `docker run` arguments, e.g. `['--platform=linux/amd64']`. */
19
+ dockerArgs?: string[];
20
+ /** How long to wait for the container (including the image pull on first use). @default 600_000 */
21
+ startTimeoutMs?: number;
22
+ };
23
+ export type ResolvedRemote = Required<RemoteBrowserOptions> & {
24
+ wsEndpoint: string;
25
+ labels: Record<string, string>;
26
+ };
27
+ /** What the global setup learned about the running container; every worker reads it for the manifest. */
28
+ export type RemoteInfo = {
29
+ containerId: string;
30
+ image: string;
31
+ imageDigest?: string;
32
+ playwrightVersion: string;
33
+ wsEndpoint: string;
34
+ /** `true` when a container from an earlier run was picked up. */
35
+ reused: boolean;
36
+ };
37
+ export type RemoteErrorCode = 'DAEMON_UNREACHABLE' | 'PLAYWRIGHT_VERSION_UNKNOWN' | 'CONTAINER_START_FAILED' | 'CONTAINER_UNHEALTHY' | 'NOT_CONFIGURED';
38
+ /** Every failure has a stable code, a cause and a fix, printed verbatim. */
39
+ export declare class RemoteBrowserError extends Error {
40
+ readonly code: RemoteErrorCode;
41
+ constructor(code: RemoteErrorCode, reason: string, fix: string, options?: {
42
+ cause?: unknown;
43
+ });
44
+ }
45
+ export declare const LABELS: {
46
+ readonly renderer: "frsource.visual-renderer";
47
+ readonly kind: "frsource.renderer";
48
+ readonly version: "frsource.playwright";
49
+ readonly port: "frsource.port";
50
+ };
51
+ export declare const detectPlaywrightVersion: (from?: string) => string | undefined;
52
+ export declare const resolveRemote: (options?: RemoteBrowserOptions, detectVersion?: () => string | undefined) => ResolvedRemote;
53
+ /** The `docker run` arguments for a resolved configuration (exported for tests and `doctor`-style output). */
54
+ export declare const dockerRunArgs: (remote: ResolvedRemote) => string[];
55
+ /** The side effects the lifecycle code needs; swapped out in unit tests. */
56
+ export type RemoteDeps = {
57
+ /** Runs `docker <args>`; resolves with trimmed stdout, rejects with the CLI's stderr. */
58
+ run: (args: string[]) => Promise<string>;
59
+ /** `true` once `run-server` answers HTTP on host:port (a bare TCP connect is not enough: Docker's port proxy accepts before anything listens inside). */
60
+ probe: (host: string, port: number) => Promise<boolean>;
61
+ sleep: (ms: number) => Promise<void>;
62
+ now: () => number;
63
+ };
64
+ export declare const defaultDeps: RemoteDeps;
65
+ /**
66
+ * Starts (or reuses) the container running `playwright run-server` and waits
67
+ * until it accepts connections. Idempotent: a container with the same labels
68
+ * is picked up instead of started again.
69
+ */
70
+ export declare const startRemoteBrowser: (remote: ResolvedRemote, log?: (message: string) => void, deps?: RemoteDeps) => Promise<RemoteInfo>;
71
+ export declare const stopRemoteBrowser: (info: Pick<RemoteInfo, "containerId">, deps?: RemoteDeps) => Promise<void>;
72
+ export declare const readResolvedRemote: (env?: NodeJS.ProcessEnv) => ResolvedRemote | undefined;
73
+ export declare const readRemoteInfo: (env?: NodeJS.ProcessEnv) => RemoteInfo | undefined;
74
+ export type RemoteBrowser = ResolvedRemote & {
75
+ /** Put this under `use` in `playwright.config`. */
76
+ connectOptions: {
77
+ wsEndpoint: string;
78
+ exposeNetwork?: string;
79
+ };
80
+ /** Module paths for `globalSetup` / `globalTeardown` in `playwright.config`. */
81
+ globalSetup: string;
82
+ globalTeardown: string;
83
+ start: (log?: (message: string) => void) => Promise<RemoteInfo>;
84
+ stop: (info: Pick<RemoteInfo, 'containerId'>) => Promise<void>;
85
+ };
86
+ /**
87
+ * Runs the tests against a browser inside the official Playwright Docker
88
+ * image instead of the one installed locally. The runner, the test code and
89
+ * your app stay on the host; only the browser is containerised, so
90
+ * screenshots have full fidelity and are byte-identical to the ones the same
91
+ * image produces in CI.
92
+ *
93
+ * ```ts
94
+ * // playwright.config.ts
95
+ * import { remoteBrowser } from '@pixsame/playwright-visual-regression-diff/remote';
96
+ * const remote = remoteBrowser();
97
+ * export default defineConfig({
98
+ * globalSetup: remote.globalSetup,
99
+ * globalTeardown: remote.globalTeardown,
100
+ * use: { connectOptions: remote.connectOptions },
101
+ * });
102
+ * ```
103
+ */
104
+ export declare const remoteBrowser: (options?: RemoteBrowserOptions) => RemoteBrowser;
@@ -0,0 +1,2 @@
1
+ /** `globalSetup` for `playwright.config`: starts the remote browser configured by `remoteBrowser()`. */
2
+ export default function globalSetup(): Promise<void>;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = globalSetup;
4
+ const constants_1 = require("./constants");
5
+ const remote_1 = require("./remote");
6
+ /** `globalSetup` for `playwright.config`: starts the remote browser configured by `remoteBrowser()`. */
7
+ async function globalSetup() {
8
+ const remote = (0, remote_1.readResolvedRemote)();
9
+ if (!remote) {
10
+ throw new remote_1.RemoteBrowserError('NOT_CONFIGURED', 'The remote browser global setup ran, but remoteBrowser() was not called in playwright.config.', 'Call `const remote = remoteBrowser()` in the config and use `remote.globalSetup`.');
11
+ }
12
+ const info = await (0, remote_1.startRemoteBrowser)(remote, (message) => process.stderr.write(`[visual-regression] ${message}\n`));
13
+ process.env[constants_1.REMOTE_INFO_ENV_KEY] = JSON.stringify(info);
14
+ }
@@ -0,0 +1,2 @@
1
+ /** `globalTeardown` for `playwright.config`: stops the container unless `keepAlive` is set. */
2
+ export default function globalTeardown(): Promise<void>;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = globalTeardown;
4
+ const remote_1 = require("./remote");
5
+ /** `globalTeardown` for `playwright.config`: stops the container unless `keepAlive` is set. */
6
+ async function globalTeardown() {
7
+ const remote = (0, remote_1.readResolvedRemote)();
8
+ const info = (0, remote_1.readRemoteInfo)();
9
+ if (!remote || !info || remote.keepAlive)
10
+ return;
11
+ await (0, remote_1.stopRemoteBrowser)(info);
12
+ }