visual-regression-ci 0.0.0-stage → 0.9.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.
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 +837 -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,420 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import fs from 'node:fs';
3
+ import { mdCode, sanitizeForDisplay, truncate } from '../shared/text.js';
4
+ import { readReport } from './actionReport.js';
5
+ import { npxCommand, packageSpec } from '../shared/packageSpec.js';
6
+
7
+ export { mdCode };
8
+
9
+ /**
10
+ * The GitHub Action's pull request comment (action.yml, step "comment", run through
11
+ * actions/github-script): one "sticky" comment per pull request (and comment-id) that
12
+ * every run of the action updates in place, so the PR always shows the latest result.
13
+ *
14
+ * Pure helpers (renderComment, upsertStickyComment) plus the step's entry point run().
15
+ * Only node: builtins and src/ modules without dependencies, so github-script can load
16
+ * it from the action checkout without `npm ci`.
17
+ *
18
+ * Everything that comes from the run (routes, viewports, error messages) is untrusted:
19
+ * a route is chosen by whoever edits the config, and an error message can quote the app
20
+ * under test. It only ever reaches the comment through mdCode (a code span), so it can't
21
+ * ping people, add links or images, or break out of the table.
22
+ *
23
+ * Which comment is updated: the oldest one that starts with this comment-id's hidden
24
+ * marker AND was written by the bot (github-actions[bot], type Bot). Anyone can post a
25
+ * comment containing the marker; matching the author too means the action never
26
+ * overwrites a person's comment.
27
+ */
28
+
29
+ export const COMMENT_ID_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
30
+ /**
31
+ * GitHub refuses comment bodies over 65,536 characters; stay well below. Checked in
32
+ * UTF-8 bytes (never fewer than characters), so it holds whichever GitHub counts.
33
+ */
34
+ export const MAX_COMMENT_LENGTH = 60000;
35
+ export const MAX_TABLE_ROWS = 50;
36
+ /** A route or viewport longer than this (in code points) is shortened in the table. */
37
+ export const MAX_CELL_LENGTH = 2000;
38
+ /**
39
+ * The version of this copy of visual-ci: package.json two folders up from this file.
40
+ * That holds in a checkout, in the npm package, and in the action's read-only scripts
41
+ * copy ($RUNNER_TEMP/visual-ci-scripts: src/ci, src/shared and package.json), which is
42
+ * where the comment step loads this module from. Null if it can't be read.
43
+ *
44
+ * @param {URL|string} [file]
45
+ * @returns {string|null}
46
+ */
47
+ export function readOwnVersion(file = new URL('../../package.json', import.meta.url)) {
48
+ try {
49
+ const version = JSON.parse(fs.readFileSync(file, 'utf8')).version;
50
+ return typeof version === 'string' ? version : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Where the import command in the comment gets visual-ci from: `visual-regression-ci@<this
58
+ * version>` on npm (see src/shared/packageSpec.js), the version that wrote the result.
59
+ * Null when the version can't be read; the comment then has no import snippet.
60
+ */
61
+ const OWN_VERSION = readOwnVersion();
62
+ export const IMPORT_PACKAGE_SPEC = packageSpec(OWN_VERSION);
63
+ export const MAX_ERROR_MESSAGE_LENGTH = 500;
64
+ export const DEFAULT_BOT_LOGIN = 'github-actions[bot]';
65
+ /** Every output the comment step sets (action.yml maps its outputs onto these). */
66
+ export const COMMENT_OUTPUT_NAMES = Object.freeze(['comment-url', 'comment-action']);
67
+
68
+ const STATUSES = ['passed', 'failed', 'error'];
69
+ const EXIT_CODES = { passed: 0, failed: 1, error: 2 };
70
+ const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
71
+ const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
72
+ const ARTIFACT_NAME = /^[A-Za-z0-9._-][A-Za-z0-9._ -]{0,99}$/; // the action's own input rule
73
+ const SHA = /^[0-9a-f]{7,64}$/i;
74
+
75
+ /** The hidden first line that identifies the sticky comment of one comment-id. */
76
+ export function stickyMarker(commentId) {
77
+ if (typeof commentId !== 'string' || !COMMENT_ID_PATTERN.test(commentId)) {
78
+ throw new TypeError('comment-id may only contain letters, digits, ".", "_" and "-" (at most 64).');
79
+ }
80
+ return `<!-- visual-ci:sticky id=${commentId} -->`;
81
+ }
82
+
83
+ /** Whether a comment body is a sticky comment for `marker`: the marker is its first line. */
84
+ export function hasMarker(body, marker) {
85
+ return typeof body === 'string' && body.split(/\r?\n/, 1)[0].trim() === marker;
86
+ }
87
+
88
+ /** The hidden first line of a sticky comment that was replaced by a newer one (never matched again). */
89
+ export function supersededMarker(commentId) {
90
+ return stickyMarker(commentId).replace('visual-ci:sticky', 'visual-ci:superseded');
91
+ }
92
+
93
+ /**
94
+ * Create or update? Decided by the action's status (the job's truth), not by the
95
+ * report. A run that did not pass (anything but exactly "passed", or a pass whose
96
+ * artifact upload failed, which fails the job) always gets a comment. A passing run
97
+ * only updates an existing one (to say everything matches again), never starts a new
98
+ * one: a PR that was green from the start stays free of bot comments.
99
+ */
100
+ export function shouldCreateComment(status, { uploadFailed = false } = {}) {
101
+ return status !== 'passed' || uploadFailed === true;
102
+ }
103
+
104
+ const count = (value) => (Number.isInteger(value) && value >= 0 ? value : 0);
105
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
106
+ const byteLength = (text) => Buffer.byteLength(text, 'utf8');
107
+
108
+ /** The report reduced to what the comment shows; anything unusable becomes an error. */
109
+ function normalize(report) {
110
+ if (!report || typeof report !== 'object' || !STATUSES.includes(report.status)) {
111
+ return {
112
+ status: 'error',
113
+ error: { code: 'NO_RESULT', message: 'visual-ci produced no usable result. See the job log.' },
114
+ counts: { total: 0, passed: 0, changed: 0, missing_baseline: 0, new_baseline: 0 },
115
+ snapshots: []
116
+ };
117
+ }
118
+ const snapshots = Array.isArray(report.snapshots) ? report.snapshots.filter((s) => s && typeof s === 'object') : [];
119
+ const c = report.counts && typeof report.counts === 'object' ? report.counts : {};
120
+ return {
121
+ status: report.status,
122
+ error: report.status === 'error' ? (report.error && typeof report.error === 'object' ? report.error : { code: 'INTERNAL', message: '' }) : null,
123
+ counts: {
124
+ total: count(c.total),
125
+ passed: count(c.passed),
126
+ changed: count(c.changed),
127
+ missing_baseline: count(c.missing_baseline),
128
+ new_baseline: count(c.new_baseline)
129
+ },
130
+ snapshots
131
+ };
132
+ }
133
+
134
+ function formatPercent(value) {
135
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return '—';
136
+ if (value > 0 && value < 0.01) return '<0.01%';
137
+ return `${value.toFixed(2)}%`;
138
+ }
139
+
140
+ /** An https URL as a Markdown link destination, or null. */
141
+ function safeUrl(value) {
142
+ if (typeof value !== 'string' || value.length > 2000) return null;
143
+ let url;
144
+ try {
145
+ url = new URL(value);
146
+ } catch {
147
+ return null;
148
+ }
149
+ if (url.protocol !== 'https:' || url.username || url.password) return null;
150
+ return url.href.replace(/\(/g, '%28').replace(/\)/g, '%29');
151
+ }
152
+
153
+ const shQuote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
154
+
155
+ function utcStamp(date) {
156
+ const d = date instanceof Date && !Number.isNaN(date.getTime()) ? date : new Date();
157
+ return `${d.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
158
+ }
159
+
160
+ function headline(r, commentId, uploadFailed) {
161
+ const label = commentId && commentId !== 'default' ? ` (${mdCode(commentId, { table: false })})` : '';
162
+ const { total, passed, changed, missing_baseline: missing, new_baseline: created } = r.counts;
163
+ const newBaselines = created > 0 ? `, ${plural(created, 'new baseline')} created` : '';
164
+ const uploadLine = ['', '⚠️ **Uploading the artifact failed**, so the job fails. Artifact names must be unique within a workflow run: in a matrix, give each use its own `artifact-name`.'];
165
+ if (r.status === 'passed') {
166
+ const all = total === 0 ? 'No snapshots were checked' : `All ${plural(total, 'snapshot')} match the baselines`;
167
+ if (uploadFailed) return [`### ⚠️ Visual CI: the snapshots match, but the job failed${label}`, '', `${all}${newBaselines}.`, ...uploadLine];
168
+ return [`### ✅ Visual CI passed${label}`, '', `${all}${newBaselines}.`];
169
+ }
170
+ const extra = uploadFailed ? uploadLine : [];
171
+ if (r.status === 'failed') {
172
+ const parts = [`${changed} changed`];
173
+ if (missing > 0) parts.push(plural(missing, 'missing baseline'));
174
+ parts.push(`${passed} passed`);
175
+ return [`### ❌ Visual CI found visual changes${label}`, '', `${plural(total, 'snapshot')}: ${parts.join(', ')}${newBaselines}.`, ...extra];
176
+ }
177
+ const code = typeof r.error?.code === 'string' && ERROR_CODE.test(r.error.code) ? r.error.code : 'INTERNAL';
178
+ const message = truncate(r.error?.message ?? '', MAX_ERROR_MESSAGE_LENGTH).trim();
179
+ return [
180
+ `### ⚠️ Visual CI failed with an error${label}`,
181
+ '',
182
+ `${mdCode(code, { table: false })}${message ? `: ${mdCode(message, { table: false })}` : ''}`,
183
+ ...extra
184
+ ];
185
+ }
186
+
187
+ /** A table cell for a route or viewport: a code span, or — when empty. */
188
+ function cell(value) {
189
+ const text = truncate(value ?? '', MAX_CELL_LENGTH);
190
+ return text === '' ? '—' : mdCode(text);
191
+ }
192
+
193
+ function tableRow(s) {
194
+ const status = s.status === 'DIFF' ? '🔴 Changed' : '🟠 Missing baseline';
195
+ const mismatch = s.status === 'DIFF' ? formatPercent(s.mismatch_percentage) : '—';
196
+ return `| ${status} | ${cell(s.route)} | ${cell(s.viewport)} | ${mismatch} |`;
197
+ }
198
+
199
+ /**
200
+ * The shell command that downloads the artifact and imports it (only fixed, validated
201
+ * parts), with visual-ci pinned to `version` (default: this copy's). Null without a
202
+ * release version: never an unpinned `npx visual-ci`.
203
+ */
204
+ export function importCommand({ runId, repo, artifactName, version = OWN_VERSION }) {
205
+ const npx = npxCommand(version);
206
+ if (!npx) return null;
207
+ const dir = `vrt-${runId}`;
208
+ return `gh run download ${runId} -R ${repo} -n ${shQuote(artifactName)} -D ${dir} && ` +
209
+ `${npx} import ${dir}`;
210
+ }
211
+
212
+ /**
213
+ * The comment's Markdown.
214
+ *
215
+ * @param {object|null} report - The `visual-ci test --json` result (schema visual-ci-result v1); null when there is none
216
+ * @param {object} options
217
+ * @param {string} options.commentId - Validated against COMMENT_ID_PATTERN (throws otherwise)
218
+ * @param {string} [options.artifactUrl] - The uploaded artifact (empty: none)
219
+ * @param {string} [options.artifactName]
220
+ * @param {string} [options.runUrl] - The workflow run
221
+ * @param {string} [options.repo] - owner/repo, for the import snippet
222
+ * @param {string|number} [options.runId] - The workflow run id, for the import snippet
223
+ * @param {string} [options.headSha] - The pull request's head commit
224
+ * @param {boolean} [options.uploadFailed] - The artifact upload failed (the job then fails)
225
+ * @param {string|null} [options.version] - visual-ci version for the import snippet (default: this copy's)
226
+ * @param {Date} [options.now]
227
+ * @returns {string} At most MAX_COMMENT_LENGTH UTF-8 bytes, the marker always on the first line
228
+ */
229
+ export function renderComment(report, { artifactUrl, runUrl, repo, runId, headSha, commentId = 'default', artifactName, uploadFailed = false, version = OWN_VERSION, now } = {}) {
230
+ const marker = stickyMarker(commentId);
231
+ const r = normalize(report);
232
+ const head = [marker, ...headline(r, commentId, uploadFailed === true)];
233
+
234
+ // Only the rows that can be shown are rendered; the count covers the rest.
235
+ const changed = r.snapshots.filter((s) => s.status === 'DIFF' || s.status === 'MISSING_BASELINE');
236
+ const rows = changed.slice(0, MAX_TABLE_ROWS).map(tableRow);
237
+ const table = (shown) => {
238
+ if (changed.length === 0) return [];
239
+ const lines = ['', '| Status | Route | Viewport | Mismatch |', '| :--- | :--- | :--- | ---: |', ...rows.slice(0, shown)];
240
+ const hidden = changed.length - shown;
241
+ if (hidden > 0) {
242
+ const capped = shown < rows.length ? ' (the comment size limit)' : '';
243
+ lines.push('', `…and ${hidden} more${capped}: see the step summary${artifactUrl ? ' or the artifact' : ''}.`);
244
+ }
245
+ return lines;
246
+ };
247
+
248
+ const tail = [''];
249
+ const artifact = safeUrl(artifactUrl);
250
+ const run = safeUrl(runUrl);
251
+ const links = [];
252
+ if (run) links.push(`[Workflow run and step summary](${run})`);
253
+ if (artifact) {
254
+ const name = typeof artifactName === 'string' && artifactName ? ` ${mdCode(truncate(artifactName, 100), { table: false })}` : '';
255
+ links.push(`[Artifact${name}](${artifact})`);
256
+ }
257
+ if (links.length > 0) tail.push(`**Details:** ${links.join(' · ')}`);
258
+
259
+ if (artifact) {
260
+ if (r.status === 'error') {
261
+ tail.push('', 'The artifact holds the screenshots taken before the error, for debugging only: it has no `run.json` and cannot be imported.');
262
+ } else if (typeof repo === 'string' && REPO.test(repo) && /^\d{1,20}$/.test(String(runId ?? '')) &&
263
+ typeof artifactName === 'string' && ARTIFACT_NAME.test(artifactName)) {
264
+ const command = importCommand({ runId, repo, artifactName, version });
265
+ if (command) tail.push('', 'Review it in your local dashboard:', '', '```sh', command, '```');
266
+ }
267
+ }
268
+ const sha = typeof headSha === 'string' && SHA.test(headSha) ? `commit ${mdCode(headSha.slice(0, 7), { table: false })} · ` : '';
269
+ tail.push('', `<sub>visual-ci · ${sha}updated ${utcStamp(now)}</sub>`);
270
+
271
+ for (let shown = rows.length; shown >= 0; shown--) {
272
+ const body = [...head, ...table(shown), ...tail].join('\n');
273
+ if (byteLength(body) <= MAX_COMMENT_LENGTH) return body;
274
+ }
275
+ // Unreachable with the limits above; still never more than the cap, marker and headline kept.
276
+ let body = [...head, '', 'The details did not fit in a comment: see the workflow run.'].join('\n');
277
+ while (byteLength(body) > MAX_COMMENT_LENGTH) body = Array.from(body).slice(0, -1000).join('');
278
+ return body;
279
+ }
280
+
281
+ /**
282
+ * Updates this action's sticky comment on a pull request, or creates it.
283
+ *
284
+ * The oldest comment that starts with `marker` and was written by `botLogin` (type Bot)
285
+ * is the sticky one. Any newer matching bot comments (two overlapping runs that both
286
+ * created one) are edited to a short "superseded" note pointing at it, under a
287
+ * different marker, so a stale result never lingers and they are never matched again.
288
+ *
289
+ * @param {object} github - An Octokit client (github-script's `github`): paginate + rest.issues
290
+ * @param {object} options
291
+ * @param {string} options.owner
292
+ * @param {string} options.repo
293
+ * @param {number} options.issue_number
294
+ * @param {string} options.body
295
+ * @param {string} options.marker - stickyMarker(commentId)
296
+ * @param {string} [options.supersededMarker] - First line of a replaced duplicate (default: derived from marker)
297
+ * @param {string} [options.botLogin] - Only comments by this login, of type Bot, are ever updated
298
+ * @param {boolean} options.createIfMissing
299
+ * @returns {Promise<{ action: 'created'|'updated'|'skipped', id: number|null, url: string, superseded: number[], supersedeErrors: string[] }>}
300
+ */
301
+ export async function upsertStickyComment(github, { owner, repo, issue_number, body, marker, supersededMarker: replaced, botLogin = DEFAULT_BOT_LOGIN, createIfMissing }) {
302
+ const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 });
303
+ const ours = (Array.isArray(comments) ? comments : [])
304
+ .filter((c) => c && c.user?.login === botLogin && c.user?.type === 'Bot' && hasMarker(c.body, marker))
305
+ .sort((a, b) => (Date.parse(a.created_at) || 0) - (Date.parse(b.created_at) || 0) || a.id - b.id);
306
+ if (ours.length === 0) {
307
+ if (!createIfMissing) return { action: 'skipped', id: null, url: '', superseded: [], supersedeErrors: [] };
308
+ const { data } = await github.rest.issues.createComment({ owner, repo, issue_number, body });
309
+ return { action: 'created', id: data?.id ?? null, url: data?.html_url || '', superseded: [], supersedeErrors: [] };
310
+ }
311
+ const [kept, ...duplicates] = ours;
312
+ const { data } = await github.rest.issues.updateComment({ owner, repo, comment_id: kept.id, body });
313
+ const url = data?.html_url || kept.html_url || '';
314
+ const superseded = [];
315
+ const supersedeErrors = [];
316
+ const link = safeUrl(url);
317
+ const note = [replaced || marker.replace('visual-ci:sticky', 'visual-ci:superseded'), '',
318
+ link ? `Superseded by [the current visual-ci comment](${link}).` : 'Superseded by a newer visual-ci comment.'].join('\n');
319
+ for (const dup of duplicates) {
320
+ try {
321
+ await github.rest.issues.updateComment({ owner, repo, comment_id: dup.id, body: note });
322
+ superseded.push(dup.id);
323
+ } catch (err) {
324
+ supersedeErrors.push(`${dup.id}: ${truncate(sanitizeForDisplay(err?.message ?? err), 200)}`);
325
+ }
326
+ }
327
+ return { action: 'updated', id: kept.id, url, superseded, supersedeErrors };
328
+ }
329
+
330
+ /**
331
+ * The report to show: the JSON result when it agrees with the action's status, else
332
+ * null (rendered as an error). The action's status is the truth: it is what the job
333
+ * reports, and it is "error" whenever the result was missing or inconsistent.
334
+ */
335
+ export function loadReportForComment({ reportPath, status, fs: fsImpl } = {}) {
336
+ if (!reportPath || !STATUSES.includes(status)) return null;
337
+ const { report } = readReport(reportPath, fsImpl);
338
+ if (!report || report.status !== status || report.exit_code !== EXIT_CODES[status]) return null;
339
+ return report;
340
+ }
341
+
342
+ /**
343
+ * Entry point for the action's comment step. Never throws and never fails the step: a
344
+ * comment problem must not change the visual result. Sets comment-url and
345
+ * comment-action (created, updated, skipped or failed).
346
+ *
347
+ * @param {{ core: object, github: object, context: object }} ctx - github-script's core, github and context
348
+ * @param {NodeJS.ProcessEnv} [env]
349
+ * @returns {Promise<{ action: string, url: string }>}
350
+ */
351
+ export async function run({ core, github, context }, env = process.env) {
352
+ const finish = (action, url = '') => {
353
+ core.setOutput('comment-url', url);
354
+ core.setOutput('comment-action', action);
355
+ return { action, url };
356
+ };
357
+ try {
358
+ const commentId = env.VISUAL_CI_COMMENT_ID ?? '';
359
+ if (!COMMENT_ID_PATTERN.test(commentId)) {
360
+ core.warning('visual-ci: no pull request comment: comment-id may only contain letters, digits, ".", "_" and "-" (at most 64).');
361
+ return finish('skipped');
362
+ }
363
+ const pr = context?.payload?.pull_request;
364
+ // pull_request only: with pull_request_target the job usually tests the base
365
+ // branch, and naming the PR's head commit in the comment would be wrong.
366
+ if (context?.eventName !== 'pull_request' || !pr || !Number.isInteger(pr.number)) {
367
+ core.notice('visual-ci: no pull request comment: comments are only written for pull_request events.');
368
+ return finish('skipped');
369
+ }
370
+ const repo = `${context.repo.owner}/${context.repo.repo}`;
371
+ if (pr.head?.repo?.full_name !== repo) {
372
+ // The token of a pull_request run from a fork is read-only: posting would fail.
373
+ core.notice('visual-ci: no pull request comment for a pull request from a fork (its token cannot write comments). ' +
374
+ 'The results are in the step summary and the artifact.');
375
+ return finish('skipped');
376
+ }
377
+
378
+ const status = env.VISUAL_CI_STATUS;
379
+ const uploadFailed = env.VISUAL_CI_UPLOAD_OUTCOME === 'failure';
380
+ const report = loadReportForComment({ reportPath: env.VISUAL_CI_REPORT_PATH, status });
381
+ const runUrl = context.serverUrl && context.runId ? `${context.serverUrl}/${repo}/actions/runs/${context.runId}` : '';
382
+ const body = renderComment(report, {
383
+ commentId,
384
+ artifactUrl: env.VISUAL_CI_ARTIFACT_URL,
385
+ artifactName: env.VISUAL_CI_ARTIFACT_NAME,
386
+ runUrl,
387
+ repo,
388
+ runId: context.runId,
389
+ headSha: pr.head?.sha, // the PR's commit, not GITHUB_SHA (the merge commit)
390
+ uploadFailed
391
+ });
392
+ const result = await upsertStickyComment(github, {
393
+ owner: context.repo.owner,
394
+ repo: context.repo.repo,
395
+ issue_number: pr.number,
396
+ body,
397
+ marker: stickyMarker(commentId),
398
+ supersededMarker: supersededMarker(commentId),
399
+ createIfMissing: shouldCreateComment(status, { uploadFailed })
400
+ });
401
+ if (result.superseded.length > 0) {
402
+ core.info(`visual-ci: marked ${result.superseded.length} older duplicate comment(s) as superseded.`);
403
+ }
404
+ for (const problem of result.supersedeErrors) core.warning(`visual-ci: could not mark a duplicate comment as superseded (${problem}).`);
405
+ core.info(result.action === 'skipped'
406
+ ? 'visual-ci: the run passed and there is no earlier comment to update: no pull request comment.'
407
+ : `visual-ci: pull request comment ${result.action}: ${result.url}`);
408
+ return finish(result.action, result.url);
409
+ } catch (err) {
410
+ const message = truncate(sanitizeForDisplay(err?.message ?? err), 300);
411
+ if (err?.status === 403 || err?.status === 404) {
412
+ core.warning(`visual-ci: could not write the pull request comment: HTTP ${err.status}: ${message}. ` +
413
+ 'Probably the token lacks permission to write pull request comments: give the job "permissions: pull-requests: write" ' +
414
+ '(and keep "contents: read"), or set "comment: false". A locked conversation also answers 403. The visual result is not affected.');
415
+ } else {
416
+ core.warning(`visual-ci: could not write the pull request comment: ${message}. The visual result is not affected.`);
417
+ }
418
+ return finish('failed');
419
+ }
420
+ }
@@ -0,0 +1,243 @@
1
+ import fs from 'node:fs'; // import node file system
2
+ import path from 'node:path';// import node path
3
+ // Playwright (chromium: the engine Google Chrome is built on, driven headless) is loaded
4
+ // in captureScreenshots, not here: it is most of the CLI's start-up time, and --help,
5
+ // --version, serve and install-browsers never need it.
6
+
7
+ export { getRouteSlug, getSnapshotFilename } from './naming.js';
8
+ import { getSnapshotFilename } from './naming.js';
9
+ import { CliError } from './errors.js';
10
+ import { redactUrl, redactUrlsInText } from './display.js';
11
+ import { sanitizeMessage } from './result.js';
12
+ import { cliCommand } from './invocation.js';
13
+
14
+ const firstLine = (err) => String(err?.message ?? err).split('\n')[0];
15
+
16
+ /**
17
+ * The error to throw when Chromium fails to launch: BROWSER_MISSING (with the command
18
+ * that fixes it) when the browser or its system libraries are not installed,
19
+ * otherwise the original error.
20
+ *
21
+ * @param {unknown} err
22
+ * @returns {unknown}
23
+ */
24
+ export function toLaunchError(err) {
25
+ const message = String(err?.message ?? err);
26
+ if (message.includes("Executable doesn't exist")) {
27
+ return new CliError('BROWSER_MISSING',
28
+ `Playwright's Chromium is not installed (${firstLine(err)}). Install it with: ${cliCommand()} install-browsers`, { cause: err });
29
+ }
30
+ if (message.includes('Host system is missing dependencies')) {
31
+ return new CliError('BROWSER_MISSING',
32
+ `Chromium cannot start: the host system is missing libraries it needs. Install them with: ${cliCommand()} install-browsers --with-deps`, { cause: err });
33
+ }
34
+ return err;
35
+ }
36
+
37
+ /**
38
+ * The error to throw when page.goto fails: NAVIGATION_FAILED naming the (redacted)
39
+ * URL, except when the browser itself went away, which is not the site's fault and
40
+ * stays an internal error.
41
+ *
42
+ * @param {unknown} err
43
+ * @param {string} url
44
+ * @returns {unknown}
45
+ */
46
+ export function toNavigationError(err, url) {
47
+ const message = String(err?.message ?? err);
48
+ if (/Target page, context or browser has been closed|Target closed|Browser has been closed/i.test(message)) {
49
+ return new CliError('INTERNAL', `The browser closed while loading ${redactUrl(url)}: ${redactUrlsInText(firstLine(err))}`, { cause: err });
50
+ }
51
+ // First line only: the rest is Playwright's call log. Redacted: the URL can carry
52
+ // credentials, and this message ends up in logs and the JSON result.
53
+ return new CliError('NAVIGATION_FAILED', `Could not load ${redactUrl(url)}: ${redactUrlsInText(firstLine(err))}`, { cause: err });
54
+ }
55
+
56
+ /** Closes a page context or the browser; a failure is a warning, never the run's error. */
57
+ async function closeQuietly(target, what) {
58
+ try {
59
+ await target.close();
60
+ } catch (err) {
61
+ console.warn(` [WARN] Could not close the ${what}: ${sanitizeMessage(firstLine(err))}`);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Throws (INVALID_ARGUMENT) unless the run id is safe to use as a folder name.
67
+ *
68
+ * @param {string} runId
69
+ */
70
+ export function assertValidRunId(runId) {
71
+ if (typeof runId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(runId)) {
72
+ throw new CliError('INVALID_ARGUMENT', `Invalid runId "${runId}": must contain only alphanumeric characters, dashes, and underscores.`);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * CSS injected into every page to ensure deterministic captures:
78
+ * - Freezes all CSS animations and transitions
79
+ * - Hides the typing caret
80
+ * (maskSelectors are not handled here: they are painted as black boxes by
81
+ * page.screenshot's `mask` option, see MASK_COLOR.)
82
+ *
83
+ * @returns {string} Injected CSS string
84
+ */
85
+ export const MASK_COLOR = '#000000';
86
+
87
+ export function buildDeterministicStyle() {// this function mutes the css
88
+ const css = `
89
+ *, *::before, *::after {
90
+ -webkit-transition: none !important;
91
+ -moz-transition: none !important;
92
+ -o-transition: none !important;
93
+ -ms-transition: none !important;
94
+ transition: none !important;
95
+ -webkit-animation: none !important;
96
+ -moz-animation: none !important;
97
+ -o-animation: none !important;
98
+ -ms-animation: none !important;
99
+ animation: none !important;
100
+ caret-color: transparent !important;
101
+ scroll-behavior: auto !important;
102
+ }
103
+ `;// this is a custome block of css which is designed to block all the animations on a website .
104
+ // this first line applies the css to each element of the webpage. * in css means all
105
+
106
+ return css;
107
+ }
108
+
109
+ /**
110
+ * Fails fast, naming the offending entry, if a maskSelectors entry isn't a valid
111
+ * Playwright selector (pseudo-elements such as ::after are not supported).
112
+ *
113
+ * @param {import('playwright').Page} page
114
+ * @param {string[]} [maskSelectors]
115
+ */
116
+ async function assertValidMaskSelectors(page, maskSelectors = []) {
117
+ for (const [i, selector] of maskSelectors.entries()) {
118
+ try {
119
+ await page.locator(selector).count();
120
+ } catch (err) {
121
+ throw new CliError('CONFIG_INVALID', `maskSelectors[${i}] "${selector}" is not a valid selector: ${firstLine(err)}`, { cause: err });
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Captures screenshots for all configured routes and viewports.
128
+ *
129
+ * @param {object} config - Validated configuration object
130
+ * @param {object} [options={}] - Execution options
131
+ * @param {string} [options.runId] - Run ID folder name (defaults to "run_<timestamp>")
132
+ * @param {string} [options.outputDir] - Base output directory (defaults to config.storageDir/runs)
133
+ * @param {Function} [options.onProgress] - Callback invoked after each screenshot
134
+ * @param {number} [options.navigationTimeout=30000] - Max ms for the page's load event (failing this aborts the capture)
135
+ * @param {number} [options.networkIdleTimeout=10000] - Max ms to additionally wait for network idle (best effort)
136
+ * @returns {Promise<Array<object>>} Array of captured snapshot results
137
+ */
138
+ export async function captureScreenshots(config, options = {}) {
139
+ const runId = options.runId || `run_${Date.now()}`;
140
+ assertValidRunId(runId);
141
+ const navigationTimeout = options.navigationTimeout ?? 30000;
142
+ const networkIdleTimeout = options.networkIdleTimeout ?? 10000;
143
+ const baseStorage = options.outputDir || path.resolve(process.cwd(), config.storageDir || 'storage', 'runs');
144
+ const targetDir = path.resolve(baseStorage, runId);
145
+
146
+ fs.mkdirSync(targetDir, { recursive: true });
147
+
148
+ const deterministicCss = buildDeterministicStyle();
149
+ const { chromium, errors: playwrightErrors } = await import('playwright');
150
+ let browser;
151
+ try {
152
+ browser = await chromium.launch({ headless: true });
153
+ } catch (err) {
154
+ throw toLaunchError(err);
155
+ }
156
+ const results = [];
157
+ let masksChecked = false;
158
+
159
+ try {
160
+ for (const route of config.routes) {
161
+ const fullUrl = `${config.baseUrl}${route}`;
162
+
163
+ for (const viewport of config.viewports) {
164
+ const context = await browser.newContext({
165
+ viewport: {
166
+ width: viewport.width,
167
+ height: viewport.height
168
+ },
169
+ deviceScaleFactor: 1
170
+ });
171
+
172
+ const page = await context.newPage();
173
+
174
+ try {
175
+ // The load event is required: a page that can't load is a real failure.
176
+ try {
177
+ await page.goto(fullUrl, { waitUntil: 'load', timeout: navigationTimeout });
178
+ } catch (navErr) {
179
+ throw toNavigationError(navErr, fullUrl);
180
+ }
181
+
182
+ // Network idle is best effort. Pages with analytics beacons, long-polling or
183
+ // websockets never go idle; for those, capture the already-loaded page.
184
+ let networkIdle = true;
185
+ try {
186
+ await page.waitForLoadState('networkidle', { timeout: networkIdleTimeout });
187
+ } catch (idleErr) {
188
+ if (!(idleErr instanceof playwrightErrors.TimeoutError)) throw idleErr;
189
+ networkIdle = false;
190
+ }
191
+
192
+ if (!masksChecked) {
193
+ await assertValidMaskSelectors(page, config.maskSelectors);
194
+ masksChecked = true;
195
+ }
196
+
197
+ // Inject deterministic styles to freeze animations and hide the caret
198
+ await page.addStyleTag({ content: deterministicCss });
199
+
200
+ // Brief pause to allow any synchronous style recalculation
201
+ await page.waitForTimeout(200);
202
+
203
+ const filename = getSnapshotFilename(route, viewport.name);
204
+ const filepath = path.join(targetDir, filename);
205
+
206
+ // Full page capture. Masked elements are painted over with solid black boxes;
207
+ // unlike hiding them with CSS this also covers canvases, iframes and elements
208
+ // whose inline styles would override an injected rule.
209
+ await page.screenshot({
210
+ path: filepath,
211
+ fullPage: true,
212
+ mask: (config.maskSelectors || []).map((selector) => page.locator(selector)),
213
+ maskColor: MASK_COLOR
214
+ });
215
+
216
+ const snapshotResult = {
217
+ runId,
218
+ route,
219
+ viewport: viewport.name,
220
+ width: viewport.width,
221
+ height: viewport.height,
222
+ filepath,
223
+ filename,
224
+ url: fullUrl,
225
+ networkIdle
226
+ };
227
+
228
+ results.push(snapshotResult);
229
+
230
+ if (typeof options.onProgress === 'function') {
231
+ options.onProgress(snapshotResult);
232
+ }
233
+ } finally {
234
+ await closeQuietly(context, 'browser context');
235
+ }
236
+ }
237
+ }
238
+ } finally {
239
+ await closeQuietly(browser, 'browser');
240
+ }
241
+
242
+ return results;
243
+ }