@pixsame/playwright-visual-regression-diff 0.0.0-canary-20261113-8e3iy1gd

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/remote.js ADDED
@@ -0,0 +1,263 @@
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.remoteBrowser = exports.readRemoteInfo = exports.readResolvedRemote = exports.stopRemoteBrowser = exports.startRemoteBrowser = exports.defaultDeps = exports.dockerRunArgs = exports.resolveRemote = exports.detectPlaywrightVersion = exports.LABELS = exports.RemoteBrowserError = void 0;
7
+ const child_process_1 = require("child_process");
8
+ const http_1 = __importDefault(require("http"));
9
+ const module_1 = require("module");
10
+ const path_1 = __importDefault(require("path"));
11
+ const util_1 = require("util");
12
+ const constants_1 = require("./constants");
13
+ const exec = (0, util_1.promisify)(child_process_1.execFile);
14
+ /** Every failure has a stable code, a cause and a fix, printed verbatim. */
15
+ class RemoteBrowserError extends Error {
16
+ code;
17
+ constructor(code, reason, fix, options) {
18
+ super(`${code}: ${reason}\n${fix}`, options);
19
+ this.code = code;
20
+ this.name = 'RemoteBrowserError';
21
+ }
22
+ }
23
+ exports.RemoteBrowserError = RemoteBrowserError;
24
+ exports.LABELS = {
25
+ renderer: 'frsource.visual-renderer',
26
+ kind: 'frsource.renderer',
27
+ version: 'frsource.playwright',
28
+ port: 'frsource.port',
29
+ };
30
+ /* c8 ignore start */
31
+ const detectPlaywrightVersion = (from = process.cwd()) => {
32
+ const req = (0, module_1.createRequire)(path_1.default.join(from, 'package.json'));
33
+ for (const pkg of ['@playwright/test', 'playwright', 'playwright-core']) {
34
+ try {
35
+ const { version } = req(`${pkg}/package.json`);
36
+ if (version)
37
+ return version;
38
+ }
39
+ catch {
40
+ // try the next one
41
+ }
42
+ }
43
+ return undefined;
44
+ };
45
+ exports.detectPlaywrightVersion = detectPlaywrightVersion;
46
+ /* c8 ignore stop */
47
+ const resolveRemote = (options = {}, detectVersion = exports.detectPlaywrightVersion) => {
48
+ const playwrightVersion = options.playwrightVersion ?? detectVersion();
49
+ if (!playwrightVersion) {
50
+ throw new RemoteBrowserError('PLAYWRIGHT_VERSION_UNKNOWN', 'Could not find @playwright/test in node_modules to pick a matching image.', 'Pass `playwrightVersion` to remoteBrowser(); it has to equal the version your tests run with.');
51
+ }
52
+ const port = options.port ?? 3000;
53
+ const host = options.host ?? '127.0.0.1';
54
+ return {
55
+ port,
56
+ host,
57
+ playwrightVersion,
58
+ image: options.image ??
59
+ `mcr.microsoft.com/playwright:v${playwrightVersion}-noble`,
60
+ keepAlive: options.keepAlive ?? false,
61
+ exposeNetwork: options.exposeNetwork ?? '<loopback>',
62
+ dockerArgs: options.dockerArgs ?? [],
63
+ startTimeoutMs: options.startTimeoutMs ?? 600_000,
64
+ wsEndpoint: `ws://${host}:${port}/`,
65
+ labels: {
66
+ [exports.LABELS.renderer]: '1',
67
+ [exports.LABELS.kind]: 'playwright-remote',
68
+ [exports.LABELS.version]: playwrightVersion,
69
+ [exports.LABELS.port]: String(port),
70
+ },
71
+ };
72
+ };
73
+ exports.resolveRemote = resolveRemote;
74
+ /** The `docker run` arguments for a resolved configuration (exported for tests and `doctor`-style output). */
75
+ const dockerRunArgs = (remote) => [
76
+ 'run',
77
+ '--detach',
78
+ '--rm',
79
+ '--init',
80
+ '--ipc=host',
81
+ '--user',
82
+ 'pwuser',
83
+ '--workdir',
84
+ '/home/pwuser',
85
+ '--publish',
86
+ `${remote.host}:${remote.port}:${remote.port}`,
87
+ '--add-host=host.docker.internal:host-gateway',
88
+ ...Object.entries(remote.labels).map(([k, v]) => `--label=${k}=${v}`),
89
+ ...remote.dockerArgs,
90
+ remote.image,
91
+ '/bin/sh',
92
+ '-c',
93
+ `npx -y playwright@${remote.playwrightVersion} run-server --port ${remote.port} --host 0.0.0.0`,
94
+ ];
95
+ exports.dockerRunArgs = dockerRunArgs;
96
+ /* c8 ignore start */
97
+ exports.defaultDeps = {
98
+ run: async (args) => {
99
+ try {
100
+ const { stdout } = await exec('docker', args, {
101
+ maxBuffer: 16 * 1024 * 1024,
102
+ });
103
+ return stdout.trim();
104
+ }
105
+ catch (error) {
106
+ const err = error;
107
+ if (err.code === 'ENOENT') {
108
+ throw new RemoteBrowserError('DAEMON_UNREACHABLE', 'The `docker` CLI is not on PATH.', 'Install Docker Desktop, OrbStack, Colima, Podman (with the docker CLI shim) or Rancher Desktop, or switch the tests back to a local browser.', { cause: error });
109
+ }
110
+ throw new Error(err.stderr?.trim() || err.message, { cause: error });
111
+ }
112
+ },
113
+ probe: (host, port) => new Promise((resolve) => {
114
+ // any HTTP answer (run-server replies 400/426 to a plain GET) means the
115
+ // server is up; a reset or hang-up means only docker-proxy is there
116
+ const request = http_1.default.get({ host, port, path: '/', timeout: 2000 }, (res) => {
117
+ res.resume();
118
+ resolve(true);
119
+ });
120
+ request.once('timeout', () => request.destroy());
121
+ request.once('error', () => resolve(false));
122
+ }),
123
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
124
+ now: () => Date.now(),
125
+ };
126
+ /* c8 ignore stop */
127
+ const assertDaemon = async ({ run }) => {
128
+ try {
129
+ await run(['version', '--format', '{{.Server.Version}}']);
130
+ }
131
+ catch (error) {
132
+ if (error instanceof RemoteBrowserError)
133
+ throw error;
134
+ const where = process.env.DOCKER_HOST
135
+ ? `DOCKER_HOST=${process.env.DOCKER_HOST}`
136
+ : 'the default socket';
137
+ throw new RemoteBrowserError('DAEMON_UNREACHABLE', `Docker daemon not reachable at ${where}: ${error.message}`, 'Start Docker Desktop (or your Docker-compatible runtime), or remove `remoteBrowser()` from playwright.config to use a local browser.', { cause: error });
138
+ }
139
+ };
140
+ const findRunningContainer = async (remote, { run }) => {
141
+ const filters = Object.entries(remote.labels).flatMap(([k, v]) => [
142
+ '--filter',
143
+ `label=${k}=${v}`,
144
+ ]);
145
+ const id = await run(['ps', '--quiet', ...filters]);
146
+ return id.split('\n')[0] || undefined;
147
+ };
148
+ const waitForPort = async (remote, containerId, deps) => {
149
+ const deadline = deps.now() + remote.startTimeoutMs;
150
+ while (deps.now() < deadline) {
151
+ if (await deps.probe(remote.host, remote.port))
152
+ return;
153
+ const running = await deps
154
+ .run(['inspect', '--format', '{{.State.Running}}', containerId])
155
+ .catch(() => 'false');
156
+ if (running !== 'true') {
157
+ const logs = await deps
158
+ .run(['logs', '--tail', '20', containerId])
159
+ .catch(() => '');
160
+ throw new RemoteBrowserError('CONTAINER_UNHEALTHY', `The remote browser container exited before it started listening on ${remote.wsEndpoint}.${logs ? `\n${logs}` : ''}`, `Run \`docker run --rm -it ${remote.image} npx -y playwright@${remote.playwrightVersion} --version\` to check the image, and make sure port ${remote.port} is free.`);
161
+ }
162
+ await deps.sleep(500);
163
+ }
164
+ throw new RemoteBrowserError('CONTAINER_UNHEALTHY', `The remote browser did not start listening on ${remote.wsEndpoint} within ${remote.startTimeoutMs} ms.`, `A first run pulls a ~2 GB image; run \`docker pull ${remote.image}\` ahead of time or raise \`startTimeoutMs\`.`);
165
+ };
166
+ const imageDigest = async (image, { run }) => {
167
+ const digest = await run([
168
+ 'image',
169
+ 'inspect',
170
+ '--format',
171
+ '{{index .RepoDigests 0}}',
172
+ image,
173
+ ]).catch(() => '');
174
+ return digest || undefined;
175
+ };
176
+ /**
177
+ * Starts (or reuses) the container running `playwright run-server` and waits
178
+ * until it accepts connections. Idempotent: a container with the same labels
179
+ * is picked up instead of started again.
180
+ */
181
+ const startRemoteBrowser = async (remote, log = () => undefined, deps = exports.defaultDeps) => {
182
+ await assertDaemon(deps);
183
+ const existing = await findRunningContainer(remote, deps);
184
+ let containerId = existing;
185
+ if (containerId) {
186
+ log(`Reusing remote browser container ${containerId.slice(0, 12)} on ${remote.wsEndpoint}`);
187
+ }
188
+ else {
189
+ log(`Starting ${remote.image} (first use pulls the image, which can take a few minutes)`);
190
+ try {
191
+ containerId = await deps.run((0, exports.dockerRunArgs)(remote));
192
+ }
193
+ catch (error) {
194
+ if (error instanceof RemoteBrowserError)
195
+ throw error;
196
+ throw new RemoteBrowserError('CONTAINER_START_FAILED', `docker run failed: ${error.message}`, `Check that the image ${remote.image} exists (the tag has to match your @playwright/test version) and that port ${remote.port} is free.`, { cause: error });
197
+ }
198
+ }
199
+ await waitForPort(remote, containerId, deps);
200
+ log(`Remote browser ready on ${remote.wsEndpoint}`);
201
+ return {
202
+ containerId,
203
+ image: remote.image,
204
+ imageDigest: await imageDigest(remote.image, deps),
205
+ playwrightVersion: remote.playwrightVersion,
206
+ wsEndpoint: remote.wsEndpoint,
207
+ reused: !!existing,
208
+ };
209
+ };
210
+ exports.startRemoteBrowser = startRemoteBrowser;
211
+ const stopRemoteBrowser = async (info, deps = exports.defaultDeps) => {
212
+ await deps.run(['stop', info.containerId]).catch(() => undefined);
213
+ };
214
+ exports.stopRemoteBrowser = stopRemoteBrowser;
215
+ const readResolvedRemote = (env = process.env) => {
216
+ const raw = env[constants_1.REMOTE_ENV_KEY];
217
+ return raw ? JSON.parse(raw) : undefined;
218
+ };
219
+ exports.readResolvedRemote = readResolvedRemote;
220
+ const readRemoteInfo = (env = process.env) => {
221
+ const raw = env[constants_1.REMOTE_INFO_ENV_KEY];
222
+ return raw ? JSON.parse(raw) : undefined;
223
+ };
224
+ exports.readRemoteInfo = readRemoteInfo;
225
+ const sibling = (name) => path_1.default.join(__dirname, `${name}${path_1.default.extname(__filename)}`);
226
+ /**
227
+ * Runs the tests against a browser inside the official Playwright Docker
228
+ * image instead of the one installed locally. The runner, the test code and
229
+ * your app stay on the host; only the browser is containerised, so
230
+ * screenshots have full fidelity and are byte-identical to the ones the same
231
+ * image produces in CI.
232
+ *
233
+ * ```ts
234
+ * // playwright.config.ts
235
+ * import { remoteBrowser } from '@pixsame/playwright-visual-regression-diff/remote';
236
+ * const remote = remoteBrowser();
237
+ * export default defineConfig({
238
+ * globalSetup: remote.globalSetup,
239
+ * globalTeardown: remote.globalTeardown,
240
+ * use: { connectOptions: remote.connectOptions },
241
+ * });
242
+ * ```
243
+ */
244
+ const remoteBrowser = (options = {}) => {
245
+ const resolved = (0, exports.resolveRemote)(options);
246
+ // the config module is evaluated in the same process that runs the global
247
+ // setup, and env is inherited by the workers - the cheapest way to hand the
248
+ // resolved options over without a second config file
249
+ process.env[constants_1.REMOTE_ENV_KEY] = JSON.stringify(resolved);
250
+ return {
251
+ ...resolved,
252
+ connectOptions: {
253
+ wsEndpoint: resolved.wsEndpoint,
254
+ ...(resolved.exposeNetwork && { exposeNetwork: resolved.exposeNetwork }),
255
+ },
256
+ // sibling modules with this file's extension: `.js` in dist, `.ts` under vitest
257
+ globalSetup: sibling('remote.global-setup'),
258
+ globalTeardown: sibling('remote.global-teardown'),
259
+ start: (log) => (0, exports.startRemoteBrowser)(resolved, log),
260
+ stop: (info) => (0, exports.stopRemoteBrowser)(info),
261
+ };
262
+ };
263
+ exports.remoteBrowser = remoteBrowser;
@@ -0,0 +1,30 @@
1
+ /** What `{platform}`, `{os}` and `{browser}` expand to. `browser` is the browser that rendered the screenshot. */
2
+ export type PathVariables = {
3
+ os: string;
4
+ browser: string;
5
+ };
6
+ /** Expands `{platform}`, `{os}` and `{browser}` anywhere in a segment; unknown `{...}` stay literal. */
7
+ export declare const expandPathVariables: (pathPart: string, { os, browser }: PathVariables) => string;
8
+ export type ImagesDirInput = {
9
+ /** The `imagesPath` option, always with `/` separators. */
10
+ imagesPath: string;
11
+ /** Test file path relative to `rootDir`, with `/` separators. */
12
+ specPath: string;
13
+ /** Playwright's `config.rootDir`; relative `imagesPath` values resolve against it. */
14
+ rootDir: string;
15
+ pathVariables: PathVariables;
16
+ };
17
+ /**
18
+ * Resolves `imagesPath` to an absolute directory. `{spec_path}` has to be a
19
+ * whole segment (it expands to several); the other tokens can sit anywhere.
20
+ * Absolute unix (`/x`) and windows (`C:/x`) paths are kept absolute.
21
+ */
22
+ export declare const resolveImagesDir: ({ imagesPath, specPath, rootDir, pathVariables, }: ImagesDirInput) => string;
23
+ /**
24
+ * Hands out `<title>_#n` names, counting repeated titles within one test
25
+ * attempt like the Cypress plugin does within one spec.
26
+ */
27
+ export declare class ScreenshotNamer {
28
+ private readonly counters;
29
+ next(dir: string, title: string): string;
30
+ }
@@ -0,0 +1,55 @@
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.ScreenshotNamer = exports.resolveImagesDir = exports.expandPathVariables = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const sanitize_filename_1 = __importDefault(require("sanitize-filename"));
9
+ const constants_1 = require("./constants");
10
+ const toPathToken = (value) => (0, sanitize_filename_1.default)(value) || 'unknown';
11
+ const replaceToken = (text, token, value) => text.split(token).join(value);
12
+ /** Expands `{platform}`, `{os}` and `{browser}` anywhere in a segment; unknown `{...}` stay literal. */
13
+ const expandPathVariables = (pathPart, { os, browser }) => {
14
+ const osToken = toPathToken(os);
15
+ const browserToken = toPathToken(browser);
16
+ return [
17
+ [constants_1.PATH_VARIABLES.platform, `${osToken}-${browserToken}`],
18
+ [constants_1.PATH_VARIABLES.os, osToken],
19
+ [constants_1.PATH_VARIABLES.browser, browserToken],
20
+ ].reduce((result, [token, value]) => replaceToken(result, token, value), pathPart);
21
+ };
22
+ exports.expandPathVariables = expandPathVariables;
23
+ /**
24
+ * Resolves `imagesPath` to an absolute directory. `{spec_path}` has to be a
25
+ * whole segment (it expands to several); the other tokens can sit anywhere.
26
+ * Absolute unix (`/x`) and windows (`C:/x`) paths are kept absolute.
27
+ */
28
+ const resolveImagesDir = ({ imagesPath, specPath, rootDir, pathVariables, }) => {
29
+ const parts = imagesPath.split('/').map((part, i) => {
30
+ if (part === constants_1.PATH_VARIABLES.specPath)
31
+ return path_1.default.dirname(specPath);
32
+ if (i === 0 && !part)
33
+ return path_1.default.sep; // unix-like absolute path
34
+ if (i === 0 && constants_1.WINDOWS_LIKE_DRIVE_REGEX.test(part))
35
+ return `${part}${path_1.default.sep}`;
36
+ return (0, exports.expandPathVariables)(part, pathVariables);
37
+ });
38
+ const joined = path_1.default.join(...parts);
39
+ return path_1.default.isAbsolute(joined) ? joined : path_1.default.resolve(rootDir, joined);
40
+ };
41
+ exports.resolveImagesDir = resolveImagesDir;
42
+ /**
43
+ * Hands out `<title>_#n` names, counting repeated titles within one test
44
+ * attempt like the Cypress plugin does within one spec.
45
+ */
46
+ class ScreenshotNamer {
47
+ counters = new Map();
48
+ next(dir, title) {
49
+ const stem = path_1.default.join(dir, (0, sanitize_filename_1.default)(title));
50
+ const n = (this.counters.get(stem) ?? -1) + 1;
51
+ this.counters.set(stem, n);
52
+ return `${(0, sanitize_filename_1.default)(title)}_#${n}`;
53
+ }
54
+ }
55
+ exports.ScreenshotNamer = ScreenshotNamer;
package/package.json ADDED
@@ -0,0 +1,84 @@
1
+ {
2
+ "name": "@pixsame/playwright-visual-regression-diff",
3
+ "description": "Pixsame for Playwright: visual regression testing for Playwright with the matchImage flow, baseline layout, run manifest and CI tooling of @frsource/cypress-plugin-visual-regression-diff, plus a pinned remote browser in Docker for drift-free pixels.",
4
+ "version": "0.0.0-canary-20261113-8e3iy1gd",
5
+ "author": "Jakub Freisler <jakub.freisler@frsource.org>",
6
+ "homepage": "https://pixsame.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/pixsame/pixsame.git",
10
+ "directory": "packages/playwright-visual-regression-diff"
11
+ },
12
+ "license": "MIT",
13
+ "main": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./remote": {
21
+ "types": "./dist/remote.d.ts",
22
+ "default": "./dist/remote.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "engines": {
27
+ "node": ">=20.9.0"
28
+ },
29
+ "peerDependencies": {
30
+ "@playwright/test": ">=1.40.0"
31
+ },
32
+ "dependencies": {
33
+ "@pixsame/analysis": "0.0.0-canary-20261113-8e3iy1gd",
34
+ "meta-png": "1.0.6",
35
+ "pixelmatch": "7.2.0",
36
+ "sanitize-filename": "1.6.4",
37
+ "visual-regression-compare": "1.0.0-beta.4",
38
+ "visual-regression-manifest": "1.0.0-beta.2"
39
+ },
40
+ "devDependencies": {
41
+ "@frsource/prettier-config": "^1.11.0",
42
+ "@playwright/test": "1.63.0",
43
+ "@types/node": "20.19.43",
44
+ "@types/tmp": "0.2.6",
45
+ "@vitest/coverage-v8": "4.1.11",
46
+ "del-cli": "7.0.0",
47
+ "prettier": "3.9.8",
48
+ "sharp": "0.35.5",
49
+ "tmp-promise": "3.0.3",
50
+ "typescript": "6.0.3",
51
+ "vitest": "4.1.11"
52
+ },
53
+ "keywords": [
54
+ "Playwright",
55
+ "Playwright fixture",
56
+ "visual regression testing",
57
+ "visual diff",
58
+ "image diff",
59
+ "visual comparison",
60
+ "image comparison",
61
+ "screenshot testing",
62
+ "image snapshot"
63
+ ],
64
+ "publishConfig": {
65
+ "access": "public"
66
+ },
67
+ "files": [
68
+ "dist",
69
+ "package.json",
70
+ "README.md",
71
+ "LICENSE"
72
+ ],
73
+ "scripts": {
74
+ "build": "del-cli dist && tsc -p tsconfig.build.json",
75
+ "format": "prettier --write .",
76
+ "format:ci": "prettier --check .",
77
+ "test:integration": "vitest run",
78
+ "test:integration:watch": "vitest",
79
+ "test:integration:coverage": "vitest run --coverage",
80
+ "test:integration:ci": "CI=true vitest run --coverage",
81
+ "test:smoke": "playwright test -c e2e/playwright.config.ts",
82
+ "test:smoke:remote": "playwright test -c e2e/playwright.remote.config.ts"
83
+ }
84
+ }