Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ renderdiff <left-origin> <right-origin> <route…> [options]
| `--sitemap[=<url>]` | Add the paths in the right side's sitemap. Default `<right>/sitemap.xml`; give another URL or path with `=`. |
| `--dry-run` | Print the URL pairs and exit. No browser. |
| `--open` | Open the report when the run finishes. |
| `--progress` | A line per shot as it finishes, then the worst scores. The default on a terminal; piped, renderdiff prints one compact summary at the end. |
| `--progress` | A line per shot as it finishes, then the worst scores. The default on a terminal; piped, renderdiff prints one compact summary at the end, and `renderdiff: n/N shots` on stderr every tenth of the run. |
| `--no-progress` | The compact summary even on a terminal. |
| `-h, --help` / `-v, --version` | |

Expand Down
8 changes: 4 additions & 4 deletions docs/case-study.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,10 @@ not verified: dark mode, hover and focus states, the open mobile menu, and the p
off the end of a truncated line.
- **A flaky error on this site.** About 1 shot in 15 failed with
`ERROR page.addStyleTag: Loading the script 'https://cloud.umami.is/script.js' violates …
Content Security Policy`. The site's own CSP blocks its own analytics script, and that
violation seems to land on renderdiff's style injection. It moves between routes and widths
from run to run, so `--rerun-failed` usually clears it and the next run brings a new one.
The message doesn't say which side failed.
Content Security Policy`. The site's own CSP blocks its own analytics script, and
Playwright's `addStyleTag` fails on any CSP violation logged while it runs, so it hit
whichever shot the script loaded during. Since fixed: renderdiff now injects its CSS as a
constructed stylesheet.
- **Shots that can't be accepted.** The two long posts end up 1px shorter on some widths
(`h-1 unaligned`). Accepting is documented not to cover unaligned height changes, so these
stay red forever, but `--accept` said only `accepted 353 difference(s)` and didn't mention
Expand Down
2 changes: 1 addition & 1 deletion docs/github-action.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ To run the action twice in one job, give each run its own `out` and `artifact-na
matrix, put the matrix value in `artifact-name`. The action sets up Node 24, which later
steps in the job then use.

Outputs: `exit-code` (0 pass, 1 a difference or below `threshold`, 2 bad input or an origin down, 3 a route
Outputs: `exit-code` (0 pass, 1 a difference or below `threshold`, 2 bad input or an origin down (at the start or mid-run), 3 a route
errored) and `results` (the path to `results.json`).

A Vercel preview behind Deployment Protection answers the runner with its login page: a
Expand Down
3 changes: 2 additions & 1 deletion docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,8 @@ with `--rerun-failed`: rerun into a new `--out` and merge again.
## results.json

Written on every run, errors included, one result per line (so `grep '"url":"/about"'`
pulls a route), scores rounded down to four decimals (so a shot that differs never reads as
pulls a route; the lines sit inside one JSON document and end in commas, so parse the whole
file, not each line), scores rounded down to four decimals (so a shot that differs never reads as
`1`). Paths are relative to the out dir; results are in route-then-width order. Its types
(`Results` and friends) are exported from the package.

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"typecheck": "tsc --noEmit -p tsconfig.test.json",
"prepare": "tsc",
"test": "node --test tests/unit/*.test.ts",
"test:visual": "node --test --test-timeout=300000 tests/visual/*.test.ts",
"test:visual": "node --test --test-timeout=600000 tests/visual/*.test.ts",
"test:all": "npm test && npm run test:visual",
"lint": "oxlint --deny-warnings",
"format": "oxfmt src tests renderdiff.config.example.ts",
Expand Down
2 changes: 2 additions & 0 deletions skills/renderdiff/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Pixels decide the score and the exit code in every mode.
*rule*) → `findings:` (one cause on many routes: fix it once) → `computed:` → `Read` the
`crops` for what `dom` doesn't explain (multi-width row: widest and narrowest). Every
token: § Output.
Hundreds of shots take many minutes: run it in the background and watch stderr's
`renderdiff: n/N shots` lines (`--progress` for a line per shot), not the PNG count.
4. **Decide every band, region, line and text line:**

| It is | Do |
Expand Down
12 changes: 7 additions & 5 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ results.json · Gotchas.

## Output

Piped (what an agent sees), stdout is one compact summary; `--progress` prints a line per shot
instead, `--no-progress` forces the summary on a terminal.
Piped (what an agent sees), stdout is one compact summary, and stderr gets
`renderdiff: n/N shots` every tenth of the run; `--progress` prints a line per shot instead,
`--no-progress` forces the summary on a terminal.

```
Routes: 3
Expand Down Expand Up @@ -124,7 +125,7 @@ Report (`--open`, for a human): green from 99.5%, amber to 97%, red below.
| `not an HTML page: server sent … at …` | The route is a file (PDF, image, JSON, download), not a page. Drop it from the routes. Never retried. |
| `page did not render on either side (…)` | Both sides under 200 chars of text and no visible image, SVG, canvas, video, iframe or form control. Usually a failed asset or an app that never mounted. One blank side isn't refused; it scores low. |
| `page did not settle: Npx unstable at …` | Over 25% of the page kept changing, on two loads. `<shot>.<side>.unsettled-a/-b.png` are the two differing frames, and the message gives the box they differ in. Mask or stop the moving part. |
| `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. |
| `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. A long page still compares one element with `--selector` or `@sel` (`element is …` when that element itself is past it). |
| `selector "…" matched N elements on left (/a), expected 1` | Make it unique (an id, `data-test`, `>> nth=0`), or list the route once per element. |
| `selector "…" has no box on …` / `is off the page on …` | Matched an element not rendered (`display: none`, zero size) or outside the page. |
| `before hook failed on left: …` | The hook threw (`beforeShot hook failed …` for that hook). Never retried. |
Expand Down Expand Up @@ -250,7 +251,7 @@ aria: identical on 2 of 3 route(s), differs /pricing
| --- | --- |
| 0 | No unaccepted shot differs (with `--threshold`: none scores below it) and no route errored. Unstable pixels or a failed asset alone exit 0: read their rows. |
| 1 | An unaccepted shot differs (with `--threshold`: scores below it; `--threshold 0` never fails). Also on an `--accept` run for what can't be accepted. Wins over 3. |
| 2 | Bad arguments or config; an origin not responding; a bad storage state or `renderdiff.accepted.json`; an out dir holding files renderdiff didn't write; `--rerun-failed` that doesn't repeat the last run; `merge` refusing. |
| 2 | Bad arguments or config; an origin not responding, at the start or mid-run (no report is written); a bad storage state or `renderdiff.accepted.json`; an out dir holding files renderdiff didn't write; `--rerun-failed` that doesn't repeat the last run; `merge` refusing. |
| 3 | A route errored (unmeasured), or the run crashed (e.g. no browser). |

## Iterating
Expand Down Expand Up @@ -359,7 +360,8 @@ One width (the first default without `--width`), no `--selector`, no `--out`. Ex
## results.json

For scripts and drilling into one route; the loop doesn't need it. One result per line, so
`grep '"url":"/about"'` pulls a route. Paths are relative to the out dir.
`grep '"url":"/about"'` pulls a route, but the lines sit inside one JSON document and end in
commas: `JSON.parse` the whole file, not each line. Paths are relative to the out dir.

- **Each result:** `url`, `left`, `right`, `selector` (`{ left, right }` or null), `hook`,
`width`, `status` (`compared`, or `error` with `error`, and `frames` when it did not settle); `score`, `alignedScore`,
Expand Down
25 changes: 16 additions & 9 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,13 @@ export async function prepare(page: Page, cfg: ResolvedConfig, now: number): Pro
});
}

/** Not addStyleTag: it fails on any CSP violation logged meanwhile, and a <style> is subject to style-src. */
function adoptCss(css: string) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(css);
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
}

export async function capture(
page: Page,
url: string,
Expand Down Expand Up @@ -288,7 +295,7 @@ export async function capture(
};
await hook("before");
step.set(page, "settle");
await page.addStyleTag({ content: cfg.neutralizeCss });
await page.evaluate(adoptCss, cfg.neutralizeCss);
// Before the scroll too, so autoplay never starts and page state driven by playback stays put.
if (cfg.freezeVideo) await page.evaluate(freezeVideo);

Expand Down Expand Up @@ -337,7 +344,7 @@ export async function capture(
if (cfg.freezeVideo) await page.evaluate(freezeVideo);
const failed = [...new Set([...network.get(page)!.failed, ...fonts.failed])];
const loadedFonts = [...new Set(fonts.loaded)].sort();
await page.addStyleTag({ content: cfg.neutralizeCss }); // anything injected late
await page.evaluate(adoptCss, cfg.neutralizeCss); // anything injected late
if (cfg.lottieFrame !== undefined) await page.evaluate(freezeLottie, cfg.lottieFrame);
await hook("beforeShot");
step.set(page, "settle");
Expand Down Expand Up @@ -400,13 +407,6 @@ export async function capture(
.map((line) => line.replace(/\s+/g, " ").trim())
.filter(Boolean);
const blank = pageText < 200 && !media ? `height=${scrollHeight}, text=${pageText} chars` : null;
if (scrollHeight > maxHeight) {
throw new Error(
`page is ${scrollHeight}px tall at ${width}px wide, past the ${maxHeight}px sanity ceiling ` +
`for that width (${MAX_PAGE_AREA.toLocaleString("en-US")} pixels) ` +
`at ${url} — likely a broken layout, not a real page`,
);
}

step.set(page, "screenshot");
const measure = async (l: Locator) => {
Expand Down Expand Up @@ -446,6 +446,13 @@ export async function capture(
.filter((b) => b !== null)
.map((b) => (clip ? { ...b, x: b.x - clip.x, y: b.y - clip.y } : b));
const area = clip ?? { x: 0, y: 0, width, height: scrollHeight };
if (area.height > maxHeight) {
throw new Error(
`${el ? "element" : "page"} is ${area.height}px tall at ${width}px wide, past the ${maxHeight}px sanity ceiling ` +
`for that width (${MAX_PAGE_AREA.toLocaleString("en-US")} pixels) ` +
`at ${url} — likely a broken layout, not a real page`,
);
}
const tiled = area.height > MAX_CAPTURE_HEIGHT;
// Read on both sides of the shot, so a box that moves while it is taken stays covered.
const shoot = async () => {
Expand Down
23 changes: 5 additions & 18 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import path from "node:path";
import { ACCEPTED_FILE } from "./accept.ts";
import type { Results } from "./report.ts";
import {
alive,
label,
loadConfig,
normalize,
Expand Down Expand Up @@ -220,8 +221,8 @@ const HELP = `
Writes report.html, results.json and crops of each change to --out. Exits 1 if any
shot differs and isn't accepted (with --threshold, only if one scores below it;
--threshold 0 never fails on a diff), 3 if a route errored (unmeasured) or the run
crashed, 2 on bad arguments or config, an origin that is down, a sitemap it can't use,
or an out dir it won't wipe.
crashed, 2 on bad arguments or config, an origin that is down (at the start or mid-run),
a sitemap it can't use, or an out dir it won't wipe.

Options
--left <url> Left origin, instead of the first positional one.
Expand Down Expand Up @@ -259,7 +260,8 @@ const HELP = `
--dry-run Print the URL pairs and exit. No browser.
--open Open the report when the run finishes.
--progress A line per shot as it finishes. The default on a terminal;
otherwise one summary of the differing routes at the end.
otherwise one summary of the differing routes at the end,
and an n/N shots line on stderr every tenth of the run.
--no-progress The end-of-run summary, even on a terminal.
-h, --help Show this.
-v, --version Print the version.
Expand All @@ -283,21 +285,6 @@ function die(message: string): never {
process.exit(2);
}

const alive = async (origin: string) => {
try {
return (
(
await fetch(origin, {
method: "HEAD",
signal: AbortSignal.timeout(3000),
})
).status < 500
);
} catch {
return false;
}
};

/**
* Refuse to start unless both origins answer — two error pages diffed against each
* other score well, which is the likeliest way this tool lies.
Expand Down
14 changes: 13 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ export const DEFAULT_BLOCK_URL_PATTERNS = [
"**://connect.facebook.net/**",
"**://*.onetrust.com/**",
"**://cdn.cookielaw.org/**",
// Geo-IP lookups that decide whether a consent banner shows.
"**://get.geojs.io/**",
];

/**
Expand Down Expand Up @@ -207,6 +209,16 @@ const STILL_CSS = `
html{scroll-behavior:auto!important}
`;

export const alive = async (origin: string) => {
try {
return (
(await fetch(origin, { method: "HEAD", signal: AbortSignal.timeout(3000) })).status < 500
);
} catch {
return false;
}
};

/**
* Browser-context settings pinned on both sides, so locale, timezone, theme and motion
* preferences can't differ between the two loads. Listed in the report.
Expand Down Expand Up @@ -286,7 +298,7 @@ export interface RenderdiffConfig {
blockUrlPatterns?: string[];
/** Extra selectors to hide, appended to {@link DEFAULT_HIDE_SELECTORS}. */
hideSelectors?: string[];
/** Raw CSS injected after the built-in rules. An escape hatch. */
/** Raw CSS injected after the built-in rules, as a constructed stylesheet, so `@import` is ignored. An escape hatch. */
extraCss?: string;
/** Per-route regions painted over on both sides. */
masks?: Mask[];
Expand Down
33 changes: 24 additions & 9 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { compare, crops, type Band, type Box, type Region } from "./compare.ts";
import { diffAria, diffSnapshots, fmtAria, fmtComputed, pageError } from "./computed.ts";
import { locate, snapshotStates, type ElementDiff } from "./locate.ts";
import {
alive,
CONTEXT_OPTIONS,
label,
masksFor,
Expand Down Expand Up @@ -276,6 +277,13 @@ export async function run({
const launched = jobs.length ? await launch() : null;
const queue = [...jobs];
let done = 0;
let down = "";
const every = Math.ceil(jobs.length / 10);
const tick = () => {
++done;
if (!progress && (done % every === 0 || done === jobs.length))
console.error(`renderdiff: ${done}/${jobs.length} shots`);
};
// Whole minute, so an HH:MM display reads the same on both sides.
const now = Math.floor(Date.now() / 60_000) * 60_000;
const har = launched && cacheRight ? cacheFile(cfg, browserOf(launched)) : null;
Expand Down Expand Up @@ -323,7 +331,7 @@ export async function run({
await prepare(pages.left, cfg, now);
await prepare(pages.right, cfg, now);

for (let job = queue.shift(); job; job = queue.shift()) {
for (let job = queue.shift(); job && !down; job = queue.shift()) {
const { route, width } = job;
const key = name(route);
const { before, beforeShot, ...where } = route;
Expand Down Expand Up @@ -567,7 +575,7 @@ export async function run({
? `aria: ${aria.aria.added.length} added, ${aria.aria.removed.length} removed`
: "",
].filter(Boolean);
++done;
tick();
if (!progress) continue;
console.log(
` [${done}/${jobs.length}] ${pct(metrics.score)} ${tag}` +
Expand All @@ -576,13 +584,16 @@ export async function run({
details.map((d) => `\n ${d}`).join(""),
);
} catch (e) {
results.push({
...entry,
status: "error",
error: e instanceof Error ? e.message : String(e),
...(frames && { frames }),
});
++done;
const error = e instanceof Error ? e.message : String(e);
results.push({ ...entry, status: "error", error, ...(frames && { frames }) });
// A refused third-party URL never reaches here; recheck the origins themselves.
if (/ERR_CONNECTION_REFUSED/.test(error) && !down) {
const [l, r] = await Promise.all([alive(cfg.left), alive(cfg.right)]);
down = [!l && `left (${cfg.left})`, !r && `right (${cfg.right})`]
.filter(Boolean)
.join(" and ");
}
tick();
if (progress) {
console.log(` [${done}/${jobs.length}] ERROR ${tag}` + (sel && `\n ${sel}`));
}
Expand All @@ -601,6 +612,10 @@ export async function run({
);
await launched.browser.close();
}
if (down) {
console.error(`✗ ${down} stopped responding mid-run. Start it again and rerun.`);
return 2;
}
const browserMeta = launched ? browserOf(launched) : prev!.meta.browser;
let unsaved = "";
if (har && !replayedAt) {
Expand Down
17 changes: 17 additions & 0 deletions tests/fixtures/pages/csp/left.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- GUARD RAIL for CSP: inline styles are refused, so renderdiff's own CSS must still apply. -->
<meta http-equiv="Content-Security-Policy" content="style-src 'self'">
<title>Layout parity</title>
<link rel="stylesheet" href="/shared/base.css">
</head>
<body>
<div id="onetrust-consent-sdk"><p>We value your privacy. Accept all cookies?</p></div>
<div class="page">
<h1>Content Security Policy guard rail</h1>
<p class="lede">This page refuses inline styles. Only the left side carries a consent banner; parity means the built-in hide selectors still applied, injected in a way the policy does not govern.</p>
</div>
</body>
</html>
16 changes: 16 additions & 0 deletions tests/fixtures/pages/csp/right.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- GUARD RAIL for CSP: inline styles are refused, so renderdiff's own CSS must still apply. -->
<meta http-equiv="Content-Security-Policy" content="style-src 'self'">
<title>Layout parity</title>
<link rel="stylesheet" href="/shared/base.css">
</head>
<body>
<div class="page">
<h1>Content Security Policy guard rail</h1>
<p class="lede">This page refuses inline styles. Only the left side carries a consent banner; parity means the built-in hide selectors still applied, injected in a way the policy does not govern.</p>
</div>
</body>
</html>
6 changes: 3 additions & 3 deletions tests/fixtures/pages/hang/left.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,21 @@
<link rel="stylesheet" href="/shared/base.css">
<style>
/* GUARD RAIL for the shot deadline. The page wedges its renderer on the first stylesheet
renderdiff injects, so the capture never returns and must error at the deadline. */
renderdiff adopts, so the capture never returns and must error at the deadline. */
</style>
</head>
<body>
<div class="page">
<h1>Hung page guard rail</h1>
<p class="lede">The page loads normally, then spins forever as soon as a style element is added to its head. Nothing after that point can run, so the shot has to be abandoned rather than waited on.</p>
<p class="lede">The page loads normally, then spins forever as soon as a stylesheet is adopted into the document. Nothing after that point can run, so the shot has to be abandoned rather than waited on.</p>

<section class="notes">
<h2>Notes</h2>
<p>A renderer that never answers would otherwise hold the run open with no output. Each shot has a deadline, and on expiry the page is replaced so the next route still compares.</p>
</section>
</div>
<script>
new MutationObserver(() => { for (;;); }).observe(document.head, { childList: true });
Object.defineProperty(document, "adoptedStyleSheets", { get: () => [], set: () => { for (;;); } });
</script>
</body>
</html>
Loading
Loading