visual-regression-ci 0.0.0-stage → 0.9.1

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +953 -2
  3. package/package.json +76 -4
  4. package/src/ci/actionReport.js +340 -0
  5. package/src/ci/prComment.js +420 -0
  6. package/src/cli/capture.js +243 -0
  7. package/src/cli/compare.js +190 -0
  8. package/src/cli/config.js +287 -0
  9. package/src/cli/database.js +69 -0
  10. package/src/cli/display.js +119 -0
  11. package/src/cli/errors.js +17 -0
  12. package/src/cli/index.js +577 -0
  13. package/src/cli/installBrowsers.js +59 -0
  14. package/src/cli/invocation.js +66 -0
  15. package/src/cli/jsonTarget.js +100 -0
  16. package/src/cli/logger.js +15 -0
  17. package/src/cli/manifest.js +139 -0
  18. package/src/cli/naming.js +60 -0
  19. package/src/cli/reporter.js +172 -0
  20. package/src/cli/result.js +225 -0
  21. package/src/cli/serve.js +64 -0
  22. package/src/server/app.js +135 -0
  23. package/src/server/db.js +691 -0
  24. package/src/server/importRuns.js +839 -0
  25. package/src/server/paths.js +107 -0
  26. package/src/server/public/css/styles.css +2362 -0
  27. package/src/server/public/js/common.js +32 -0
  28. package/src/server/public/js/dashboard.js +140 -0
  29. package/src/server/public/js/import-upload.js +169 -0
  30. package/src/server/public/js/review-actions.js +379 -0
  31. package/src/server/public/js/shortcuts.js +242 -0
  32. package/src/server/public/js/slider.js +104 -0
  33. package/src/server/public/js/tabs.js +85 -0
  34. package/src/server/public/js/theme.js +83 -0
  35. package/src/server/routes/api.js +141 -0
  36. package/src/server/routes/views.js +68 -0
  37. package/src/server/security.js +79 -0
  38. package/src/server/uploadImport.js +227 -0
  39. package/src/server/urls.js +31 -0
  40. package/src/server/viewModels.js +366 -0
  41. package/src/server/views/history.ejs +111 -0
  42. package/src/server/views/index.ejs +283 -0
  43. package/src/server/views/layout.ejs +11 -0
  44. package/src/server/views/partials/footer.ejs +11 -0
  45. package/src/server/views/partials/header.ejs +93 -0
  46. package/src/server/views/run-detail.ejs +295 -0
  47. package/src/shared/packageSpec.js +49 -0
  48. package/src/shared/text.js +59 -0
@@ -0,0 +1,225 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getToolVersion } from './manifest.js';
5
+ import { sanitizeForDisplay } from '../shared/text.js';
6
+ import { redactUrl, redactUrlsInText, redactLocalPaths, toDisplayPath } from './display.js';
7
+
8
+ export { CliError } from './errors.js';
9
+ export { redactUrl } from './display.js';
10
+
11
+ /**
12
+ * The machine-readable result of a CLI command (`visual-ci test --json <file>`).
13
+ *
14
+ * Schema "visual-ci-result", version 1. Changes must stay additive: new fields may be
15
+ * added, existing fields keep their name, type and meaning. Paths are relative to the
16
+ * working directory and use "/", so they mean the same thing inside a container whose
17
+ * workspace lives elsewhere (a path outside the working directory, e.g. a
18
+ * VISUAL_STORAGE_DIR elsewhere, is given absolute). Percentages: 1 = 1%.
19
+ *
20
+ * {
21
+ * schema: 'visual-ci-result', version: 1, tool: { name: 'visual-ci', version },
22
+ * command: 'test', status: 'passed' | 'failed' | 'error', exit_code: 0 | 1 | 2,
23
+ * error: null | { code, message },
24
+ * run: null | { id, mode: 'compare' | 'update-baselines', strict, base_url, branch,
25
+ * commit_sha, created_at, duration_ms, threshold_percentage,
26
+ * run_dir, manifest, summary },
27
+ * counts: { total, passed, changed, missing_baseline, new_baseline },
28
+ * snapshots: [{ route, viewport, status: 'MATCH' | 'DIFF' | 'NEW_BASELINE' |
29
+ * 'MISSING_BASELINE', mismatch_percentage, current, baseline,
30
+ * baseline_snapshot, diff }]
31
+ * }
32
+ *
33
+ * baseline is the shared baseline file (baselines/<name>.png, which later approvals
34
+ * change); baseline_snapshot is the run's own copy of the baseline it was compared
35
+ * against, inside the run folder (so it travels with the CI artifact), or null.
36
+ */
37
+
38
+ export const RESULT_SCHEMA = 'visual-ci-result';
39
+ export const RESULT_VERSION = 1;
40
+
41
+ /** Process exit codes: 0 all good, 1 visual differences (or missing baselines in strict mode), 2 anything else went wrong. */
42
+ export const EXIT = Object.freeze({ PASS: 0, DIFF: 1, ERROR: 2 });
43
+
44
+ export const ERROR_CODES = Object.freeze([
45
+ 'CONFIG_NOT_FOUND',
46
+ 'CONFIG_INVALID',
47
+ 'NAVIGATION_FAILED',
48
+ 'BROWSER_MISSING',
49
+ 'INVALID_ARGUMENT',
50
+ 'INTERNAL'
51
+ ]);
52
+
53
+ /** `--json -` writes the result to stdout. */
54
+ export const STDOUT_TARGET = '-';
55
+
56
+ const MAX_MESSAGE_LENGTH = 2000;
57
+
58
+ /**
59
+ * Makes an error message safe for a terminal or the JSON: URLs lose credentials and
60
+ * token-like query values (redactUrl), each line goes through sanitizeForDisplay
61
+ * (control, bidi and other invisible characters become visible escapes), line breaks
62
+ * are kept, and very long messages are shortened.
63
+ *
64
+ * @param {unknown} text
65
+ * @returns {string}
66
+ */
67
+ export function sanitizeMessage(text) {
68
+ const lines = redactUrlsInText(text).split(/\r?\n/).map((line) => sanitizeForDisplay(line).trimEnd());
69
+ while (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
70
+ const joined = lines.join('\n');
71
+ return joined.length > MAX_MESSAGE_LENGTH ? `${joined.slice(0, MAX_MESSAGE_LENGTH - 3)}...` : joined;
72
+ }
73
+
74
+ /**
75
+ * Something thrown, as an error buildResult can report: Errors (and error-like objects)
76
+ * as they are, anything else (undefined, null, a string...) wrapped in an Error.
77
+ *
78
+ * @param {unknown} err
79
+ * @returns {Error}
80
+ */
81
+ export function toError(err) {
82
+ if (err instanceof Error || (err && typeof err === 'object' && 'message' in err)) return err;
83
+ return new Error(String(err));
84
+ }
85
+
86
+ /**
87
+ * Maps an error to one of ERROR_CODES. Errors thrown by this tool carry their code
88
+ * (CliError); a few third-party failures are recognised by their message.
89
+ *
90
+ * @param {unknown} err
91
+ * @returns {string}
92
+ */
93
+ export function classifyError(err) {
94
+ if (err && typeof err.code === 'string' && ERROR_CODES.includes(err.code)) return err.code;
95
+ const message = String(err?.message ?? err ?? '');
96
+ // Playwright launch failures that reach here without going through capture's toLaunchError
97
+ if (message.includes("Executable doesn't exist") || message.includes('Host system is missing dependencies')) return 'BROWSER_MISSING';
98
+ return 'INTERNAL';
99
+ }
100
+
101
+ /** A path as the result records it (see toDisplayPath in display.js). */
102
+ export const toResultPath = toDisplayPath;
103
+
104
+ const round6 = (value) => Math.round(value * 1e6) / 1e6; // no float noise like 3.4200000000000004
105
+ const percentage = (ratio) => round6(ratio * 100); // 0.07 * 100 is 7.000000000000001
106
+
107
+ /**
108
+ * Builds the visual-ci-result object.
109
+ *
110
+ * @param {object} options
111
+ * @param {string} [options.command='test']
112
+ * @param {unknown} [options.error] - Set when the command failed with an error (status 'error', exit 2)
113
+ * @param {object|null} [options.run] - What is known about the run (null if it never started):
114
+ * { id, mode, strict, baseUrl, gitInfo: { branch, commit_sha }, createdAt: Date,
115
+ * durationMs, threshold (ratio, 0.01 = 1%), runDir, manifestPath, summaryPath }
116
+ * @param {object[]} [options.results] - Comparison results as produced by the CLI
117
+ * @param {string} [options.cwd=process.cwd()] - Paths are recorded relative to this
118
+ * @returns {object}
119
+ */
120
+ export function buildResult({ command = 'test', error = null, run = null, results = [], cwd = process.cwd() } = {}) {
121
+ const snapshots = results.map((r) => ({
122
+ route: r.route,
123
+ viewport: r.viewport,
124
+ status: r.status,
125
+ mismatch_percentage: round6(r.mismatchPercentage || 0),
126
+ current: toResultPath(r.currentPath || r.filepath, cwd),
127
+ baseline: toResultPath(r.baselinePath, cwd),
128
+ baseline_snapshot: toResultPath(r.baselineSnapshotPath, cwd),
129
+ diff: toResultPath(r.diffPath, cwd)
130
+ }));
131
+
132
+ const countOf = (status) => snapshots.filter((s) => s.status === status).length;
133
+ const counts = {
134
+ total: snapshots.length,
135
+ passed: countOf('MATCH'),
136
+ changed: countOf('DIFF'),
137
+ missing_baseline: countOf('MISSING_BASELINE'),
138
+ new_baseline: countOf('NEW_BASELINE')
139
+ };
140
+
141
+ let status;
142
+ let exitCode;
143
+ if (error) {
144
+ status = 'error';
145
+ exitCode = EXIT.ERROR;
146
+ } else if (counts.changed + counts.missing_baseline > 0) {
147
+ status = 'failed';
148
+ exitCode = EXIT.DIFF;
149
+ } else {
150
+ status = 'passed';
151
+ exitCode = EXIT.PASS;
152
+ }
153
+
154
+ return {
155
+ schema: RESULT_SCHEMA,
156
+ version: RESULT_VERSION,
157
+ tool: { name: 'visual-ci', version: getToolVersion() },
158
+ command,
159
+ status,
160
+ exit_code: exitCode,
161
+ // No host paths in the published message: cwd becomes ".", the home directory "~".
162
+ error: error ? { code: classifyError(error), message: redactLocalPaths(sanitizeMessage(error.message ?? error), { cwd }) } : null,
163
+ run: run ? {
164
+ id: run.id,
165
+ mode: run.mode,
166
+ strict: run.strict,
167
+ base_url: run.baseUrl ? redactUrl(run.baseUrl) : null, // credentials and tokens never go in the JSON
168
+ branch: run.gitInfo?.branch || null,
169
+ commit_sha: run.gitInfo?.commit_sha || null,
170
+ created_at: run.createdAt ? run.createdAt.toISOString() : null,
171
+ duration_ms: run.durationMs ?? null,
172
+ threshold_percentage: typeof run.threshold === 'number' ? percentage(run.threshold) : null,
173
+ run_dir: toResultPath(run.runDir, cwd),
174
+ manifest: toResultPath(run.manifestPath, cwd),
175
+ summary: toResultPath(run.summaryPath, cwd)
176
+ } : null,
177
+ counts,
178
+ snapshots
179
+ };
180
+ }
181
+
182
+ /** Writes all of `data` to a file descriptor, waiting out EAGAIN on a non-blocking pipe. */
183
+ function writeAllSync(fd, data) {
184
+ const buffer = Buffer.from(data, 'utf8');
185
+ let offset = 0;
186
+ while (offset < buffer.length) {
187
+ try {
188
+ offset += fs.writeSync(fd, buffer, offset, buffer.length - offset);
189
+ } catch (err) {
190
+ if (err.code !== 'EAGAIN') throw err;
191
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5); // brief pause, then retry
192
+ }
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Writes the result as JSON, synchronously (so it also works right before
198
+ * process.exit, e.g. on a crash). A file is written via a temp file + rename (like
199
+ * run.json), so a reader never sees a half-written result; "-" writes to stdout.
200
+ *
201
+ * @param {object} result
202
+ * @param {string} target - File path (relative to cwd) or "-"
203
+ * @param {{ fd?: number, cwd?: string }} [options] - fd: where "-" writes (default 1, stdout)
204
+ * @returns {string} The absolute path written, or "-"
205
+ */
206
+ export function writeResult(result, target, { fd = 1, cwd = process.cwd() } = {}) {
207
+ const json = `${JSON.stringify(result, null, 2)}\n`;
208
+ if (target === STDOUT_TARGET) {
209
+ writeAllSync(fd, json);
210
+ return STDOUT_TARGET;
211
+ }
212
+
213
+ const file = path.resolve(cwd, target);
214
+ fs.mkdirSync(path.dirname(file), { recursive: true });
215
+ // Random suffix: in a container the pid is often 1 for every run.
216
+ const temp = `${file}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
217
+ try {
218
+ fs.writeFileSync(temp, json, 'utf8');
219
+ fs.renameSync(temp, file);
220
+ } catch (err) {
221
+ fs.rmSync(temp, { force: true });
222
+ throw err;
223
+ }
224
+ return file;
225
+ }
@@ -0,0 +1,64 @@
1
+ import net from 'node:net';
2
+ import { CliError } from './errors.js';
3
+
4
+ export const DEFAULT_PORT = 4000;
5
+ export const DEFAULT_HOST = '127.0.0.1';
6
+
7
+ /**
8
+ * A TCP port from a flag or an environment variable: a whole number from 0 to 65535
9
+ * (0 picks a free port).
10
+ *
11
+ * @param {unknown} value
12
+ * @param {string} source - Where it came from, for the error message (e.g. "--port")
13
+ * @returns {number}
14
+ * @throws {CliError} INVALID_ARGUMENT
15
+ */
16
+ export function parsePort(value, source) {
17
+ const text = String(value ?? '').trim();
18
+ if (/^\d{1,5}$/.test(text) && Number(text) <= 65535) return Number(text);
19
+ throw new CliError('INVALID_ARGUMENT', `Invalid port ${JSON.stringify(String(value ?? ''))} (from ${source}): use a whole number from 0 to 65535.`);
20
+ }
21
+
22
+ /**
23
+ * Port and host for `visual-ci serve`: the flags, else PORT / VISUAL_CI_HOST from the
24
+ * environment, else 4000 and 127.0.0.1. Not the plain HOST variable that
25
+ * `node src/server/app.js` (npm start, Docker) uses: tcsh, among others, sets HOST to
26
+ * the machine's name, which would quietly put the dashboard on the network.
27
+ *
28
+ * @param {{ port?: string, host?: string }} options - Parsed flags
29
+ * @param {NodeJS.ProcessEnv} [env=process.env]
30
+ * @returns {{ port: number, host: string }}
31
+ */
32
+ export function resolveServeOptions(options, env = process.env) {
33
+ const port = options.port !== undefined
34
+ ? parsePort(options.port, '--port')
35
+ : env.PORT ? parsePort(env.PORT, 'the PORT environment variable') : DEFAULT_PORT;
36
+
37
+ let host = DEFAULT_HOST;
38
+ if (options.host !== undefined) {
39
+ host = String(options.host).trim();
40
+ if (!host) throw new CliError('INVALID_ARGUMENT', '--host cannot be empty.');
41
+ } else if (env.VISUAL_CI_HOST && env.VISUAL_CI_HOST.trim()) {
42
+ host = env.VISUAL_CI_HOST.trim();
43
+ }
44
+ return { port, host };
45
+ }
46
+
47
+ /**
48
+ * True when only this computer can connect: localhost, 127.0.0.0/8 or ::1. Anything
49
+ * else (0.0.0.0, ::, a LAN address, a host name) may be reachable from the network.
50
+ *
51
+ * @param {string} host
52
+ * @returns {boolean}
53
+ */
54
+ export function isLoopbackHost(host) {
55
+ const h = String(host).trim().toLowerCase().replace(/^\[|\]$/g, '');
56
+ if (h === 'localhost' || h === '::1') return true;
57
+ return net.isIPv4(h) && h.startsWith('127.');
58
+ }
59
+
60
+ /** The warning `visual-ci serve` prints when it listens on more than loopback. */
61
+ export function exposedWarning(host) {
62
+ return `[WARN] Listening on ${host}, which other computers may be able to reach. The dashboard has no login: ` +
63
+ 'anyone who can reach it can import runs and approve or reject baselines. Only do this on a trusted network.';
64
+ }
@@ -0,0 +1,135 @@
1
+ import express from 'express';
2
+ import fs from 'node:fs';
3
+ import net from 'node:net';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import apiRouter from './routes/api.js';
7
+ import viewRouter from './routes/views.js';
8
+ import { getDb } from './db.js';
9
+ import { getStorageRoot, resolvePngInside } from './paths.js';
10
+ import { hostAllowlist, requireSameOriginForWrites } from './security.js';
11
+ import { makeUrl } from './urls.js';
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = path.dirname(__filename);
15
+
16
+ const app = express();
17
+
18
+ // Reject requests whose Host header isn't localhost, an IP, or in ALLOWED_HOSTS (DNS rebinding)
19
+ app.use(hostAllowlist);
20
+
21
+ // View engine setup
22
+ app.set('view engine', 'ejs');
23
+ app.set('views', path.join(__dirname, 'views'));
24
+
25
+ // Every local link in the views goes through url() (see urls.js). The live server
26
+ // renders at the site root. To render under a sub-path (the static Pages build),
27
+ // pass pageLocals({ base, mode }) as render options rather than changing app.locals,
28
+ // so base, mode and url() always agree and live requests are unaffected.
29
+ app.locals.base = '';
30
+ app.locals.mode = 'live';
31
+ app.locals.url = (p) => makeUrl(app.locals.base)(p);
32
+
33
+ // Static assets
34
+ app.use(express.static(path.join(__dirname, 'public')));
35
+
36
+ // Serve screenshots at /storage. Allowlist: only .png files under runs/ or baselines/.
37
+ // Everything else in storage (SQLite DB, summaries, stray files) is refused.
38
+ const SERVABLE_STORAGE_PATH = /^\/(runs|baselines)\/[A-Za-z0-9_\-./]+\.png$/i;
39
+
40
+ app.use('/storage', (req, res, next) => {
41
+ if (req.method !== 'GET' && req.method !== 'HEAD') return next();
42
+
43
+ let relPath;
44
+ try {
45
+ relPath = decodeURIComponent(req.path);
46
+ } catch {
47
+ return res.status(400).type('text/plain').send('Bad request');
48
+ }
49
+
50
+ // No dot-segments at all: blocks '..' and hidden folders such as an import's
51
+ // temporary runs/.import-* copy or a baseline's .x.png.<id>.bak backup.
52
+ if (!SERVABLE_STORAGE_PATH.test(relPath) || relPath.split('/').some((seg) => seg.startsWith('.'))) {
53
+ return res.status(403).type('text/plain').send('Access denied');
54
+ }
55
+
56
+ const storageRoot = getStorageRoot();
57
+ const subDir = relPath.split('/')[1];
58
+ let realFile;
59
+ try {
60
+ realFile = resolvePngInside(path.join(storageRoot, relPath), path.join(storageRoot, subDir));
61
+ } catch (err) {
62
+ return err.message.startsWith('Access denied')
63
+ ? res.status(403).type('text/plain').send('Access denied')
64
+ : res.status(404).type('text/plain').send('Not found');
65
+ }
66
+
67
+ const realRoot = fs.realpathSync(storageRoot);
68
+ res.sendFile(path.relative(realRoot, realFile), { root: realRoot }, (err) => {
69
+ if (err && !res.headersSent) res.status(404).type('text/plain').send('Not found');
70
+ });
71
+ });
72
+
73
+ // Route mounting
74
+ app.use('/api', requireSameOriginForWrites, apiRouter);
75
+ app.use('/', viewRouter);
76
+
77
+ const LOOPBACK_OR_ANY = new Set(['127.0.0.1', 'localhost', '::1', '0.0.0.0', '::']);
78
+
79
+ /** The address to open in a browser for a server listening on host:port. */
80
+ export function dashboardUrl(host, port) {
81
+ if (LOOPBACK_OR_ANY.has(host)) return `http://localhost:${port}`;
82
+ return `http://${net.isIPv6(host) ? `[${host}]` : host}:${port}`;
83
+ }
84
+
85
+ /**
86
+ * Starts the dashboard, then opens the database. Defaults: PORT env or 4000, and
87
+ * HOST env or 127.0.0.1 (loopback only; HOST=0.0.0.0 exposes it on the network,
88
+ * which Docker does). The database is opened (and created) only once the port is
89
+ * ours, so a busy port never leaves a new data.sqlite behind. Prints the URL when it
90
+ * is ready. Listen errors (port in use...) and a database that can't be opened are
91
+ * emitted as the returned server's 'error' event (the server is then closed).
92
+ *
93
+ * @param {object} [options]
94
+ * @param {number|string} [options.port]
95
+ * @param {string} [options.host]
96
+ * @param {(line: string) => void} [options.log=console.log]
97
+ * @returns {import('node:http').Server}
98
+ */
99
+ export function startServer({ port = process.env.PORT || 4000, host = process.env.HOST || '127.0.0.1', log = console.log } = {}) {
100
+ const server = app.listen(port, host, () => {
101
+ try {
102
+ getDb(); // before any request is handled: listeners run synchronously
103
+ } catch (err) {
104
+ server.close();
105
+ server.emit('error', err);
106
+ return;
107
+ }
108
+ const actualPort = server.address().port; // the real one when port 0 was asked for
109
+ log('──────────────────────────────────────────────────────');
110
+ log(' Visual Regression Dashboard running at:');
111
+ log(` ${dashboardUrl(host, actualPort)}`);
112
+ log(` (listening on ${host}:${actualPort})`);
113
+ log('──────────────────────────────────────────────────────');
114
+ });
115
+ return server;
116
+ }
117
+
118
+ // Start the server when this file is run directly (node src/server/app.js, npm start;
119
+ // also `node src/server/app`, which Node resolves to app.js), not when it is imported.
120
+ function isMainModule() {
121
+ const entry = process.argv[1];
122
+ if (!entry) return false;
123
+ const self = fs.realpathSync(__filename);
124
+ return [entry, `${entry}.js`].some((candidate) => {
125
+ try {
126
+ return fs.realpathSync(path.resolve(candidate)) === self;
127
+ } catch {
128
+ return false;
129
+ }
130
+ });
131
+ }
132
+
133
+ if (isMainModule()) startServer();
134
+
135
+ export default app;