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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,11 @@ and writes `evidence.html` there: one self-contained page (a Parity / Differs /
banner, your verdict, crops embedded) to attach to a ticket or publish as proof:
[docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md#evidencehtml).

`renderdiff merge <full-out> <partial-out> --out <dir>` writes the full run's results to a new
out dir with the shots a partial run also took (say, a few routes rerun under a new mask)
replaced by its, and its other shots added. Each merged shot carries `from`:
[docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md#merge).

## Why a clean result is trustworthy

- **Refuses to start** unless both origins answer: two error pages would score ~100%.
Expand Down
18 changes: 17 additions & 1 deletion docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,12 +278,27 @@ rewrites `report.html` from it, and writes `evidence.html` beside it: one file w
outside references, so it can be attached to a ticket or published on its own. It opens with
a banner: **Parity** (every shot clean or accepted, no errors), **Differs** (a shot that
would exit 1), or **Not verified** (errors, unstable pixels, failed assets, diffs under
`--threshold`, or a `--rerun-failed` run that reused shots). Then the `renderdiff:` line,
`--threshold`, a `--rerun-failed` run that reused shots, or a merged run). Then the `renderdiff:` line,
the verdict file as plain text, coverage (clean and accepted routes, errors, stale accepts),
and a card per shot that isn't clean, then one per accepted shot, with crops embedded as
WebP. Crops past 12MB, or missing from the out dir, are left out and the banner says so.
Build it after a fresh full run.

## merge

`renderdiff merge <full-out> <partial-out> --out <dir>` writes a new out dir: the full run's
results, each shot the partial run also took replaced by the partial run's (files included),
and the partial run's other shots added after them. No browser. Each shot taken from the
partial run gets `from`, that run's `generatedAt`. `meta` is the full run's, with `widths`,
`masks`, `hideSelectors` and `blockUrlPatterns` the union of both, and `rightReplayedFrom`
recomputed; the summary is recomputed against the full run's threshold. Each shot keeps the
`accepted` flag its own run gave it: `renderdiff.accepted.json` is not reread. The shots
were taken at different times, so `evidence.html` says Not verified; chain
`renderdiff report <dir> --verdict …` for one. Exits 2 when the two runs compare different
origins, `--out` is or is inside an input or holds files renderdiff didn't write, a referenced file is missing, or two shots would
write the same file (run both into one `--out` instead). A merged out dir can't be continued
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"'`
Expand All @@ -310,6 +325,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev
"results": [
{
"url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b"
"from": "…", // renderdiff merge: generatedAt of the run this shot came from; absent otherwise
"selector": null, "hook": false, // hook: a before or beforeShot hook ran
"width": 1440, "status": "compared",
"score": 0.9714, // share of measured pixels that match
Expand Down
13 changes: 12 additions & 1 deletion skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so
| --- | --- |
| 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. |
| 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. |
| 3 | A route errored (unmeasured), or the run crashed (e.g. no browser). |

## Iterating
Expand All @@ -231,6 +231,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so
(differences, unstable shots, failed assets, errors), merging back into results.json. Same
origins, routes, widths, config (masks, hooks, hidden selectors, CSS, storage state,
`--computed`) and version as the run it continues, or it exits 2.
- **Hand-picked reruns with a changed config** (a new mask for a few routes): run them into a
new `--out`, then `renderdiff merge <full-out> <that-out> --out <dir>`.
- **`--cache-right`** replays the right side's recorded traffic (`<out>/.cache/`, kept by the
wipe) for up to an hour, if the recording covers every shot; otherwise loads live and records.
The page still renders live, so `dom` and the refusals hold, but a deploy to the reference
Expand Down Expand Up @@ -303,6 +305,15 @@ the verdict file as plain text, coverage, and cards for shots that aren't clean,
accepted ones, with crops embedded (past 12MB or missing, left out and noted). No external
references. Exits 2 without `results.json` or a readable verdict file.

## `merge`

`renderdiff merge <full-out> <partial-out> --out <dir>`, no browser: the full run's results
with each shot the partial run also took replaced by its (files too), the rest added; each
such shot has `from` (that run's `generatedAt`). Masks, hidden selectors, blocked URLs and
widths are unioned in `meta`; accepted flags stay as each run set them. `evidence.html` says
Not verified. Exits 2 on different origins, an `--out` that is or is inside an input or holds foreign
files, or two shots writing one file. A merged out dir refuses `--rerun-failed`.

## results.json

For scripts and drilling into one route; the loop doesn't need it. One result per line, so
Expand Down
30 changes: 30 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ const HELP = `
renderdiff http://localhost:3000 https://example.com / /about
renderdiff http://localhost:3000 https://example.com /pricing::/plans
renderdiff report <out-dir> [--verdict <file>] [--title <text>]
renderdiff merge <full-out> <partial-out> --out <dir>

An argument starting with http:// or https:// is an origin: the first is left (your
change), the second right (the reference); or pass --left / --right. A route is a
Expand All @@ -204,6 +205,9 @@ const HELP = `
evidence.html beside it: one self-contained page (crops embedded) with a parity banner and
the --verdict file's text.

renderdiff merge writes <full-out>'s results to --out with each shot <partial-out> also
has replaced by the partial run's, and its other shots added. Both must compare the same origins.

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
Expand Down Expand Up @@ -385,7 +389,33 @@ async function report(argv: string[]): Promise<never> {
}
}

/** `renderdiff merge <full-out> <partial-out> --out <dir>`: no browser, so never exit 1 or 3. */
async function merge(argv: string[]): Promise<never> {
try {
const dirs: string[] = [];
let out: string | undefined;
for (let i = 0; i < argv.length; i++) {
const v = argv[i]!;
if (v === "--out") {
out = argv[++i];
if (out === undefined) throw new Error("--out needs a value");
} else if (v.startsWith("-") || dirs.length === 2)
throw new Error(`unexpected argument: ${v}`);
else dirs.push(v);
}
if (dirs.length !== 2 || !out)
throw new Error("usage: renderdiff merge <full-out> <partial-out> --out <dir>");
const { merge } = await import("./run.ts");
await merge(dirs[0]!, dirs[1]!, out);
process.exit(0);
} catch (e) {
console.error(`✗ ${e instanceof Error ? e.message : String(e)}`);
process.exit(2);
}
}

if (process.argv[2] === "report") await report(process.argv.slice(3));
if (process.argv[2] === "merge") await merge(process.argv.slice(3));

let args: Args;
try {
Expand Down
8 changes: 7 additions & 1 deletion src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ interface BaseResult {
/** A `before` or `beforeShot` hook ran on both sides before the shot, so the page was measured in its state. */
hook: boolean;
width: number;
/** With `renderdiff merge`: generatedAt of the run the shot came from; absent for the run in `meta`. */
from?: string;
}

/** A route that was captured on both sides and diffed. */
Expand Down Expand Up @@ -667,11 +669,15 @@ export async function writeEvidence(
"shot(s) differ under threshold",
),
...count(meta.rerun?.reused ?? 0, "shot(s) reused by --rerun-failed"),
...count(results.filter((r) => r.from).length, "shot(s) merged from a later run"),
...count(omitted, "crop(s) omitted (over the size budget or missing)"),
];
const [cls, label] = compared.some((r) => fails(r, meta.threshold))
? ["bad", "Differs"]
: !results.length || meta.rerun?.reused || !results.every(reusable)
: !results.length ||
meta.rerun?.reused ||
results.some((r) => r.from) ||
!results.every(reusable)
? ["warn", "Not verified"]
: ["good", "Parity"];

Expand Down
97 changes: 97 additions & 0 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
fails,
fmtPixelFindings,
stats,
writeEvidence,
writeReport,
writeResults,
type ComparedResult,
Expand Down Expand Up @@ -160,6 +161,8 @@ function previous(file: string, now: Record<string, unknown>): Results | string
} catch {
return `${file} is not valid JSON; run without --rerun-failed`;
}
if (prev.results?.some((r) => r.from))
return `${file} was written by renderdiff merge; rerun into a new --out and merge again`;
const was: Record<string, unknown> = {
...prev.meta,
routes: [...new Set(prev.results?.map(name))],
Expand Down Expand Up @@ -677,6 +680,100 @@ export async function run({
return below.length ? 1 : results.some((r) => r.status === "error") ? 3 : 0;
}

function readResults(dir: string): Results {
const file = path.join(dir, "results.json");
if (!fs.existsSync(file)) throw new Error(`no ${file}; run renderdiff with --out ${dir} first`);
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
throw new Error(`${file} is not valid JSON`);
}
}

/** `renderdiff merge`: the full run's results with the partial run's shots replacing or added. */
export async function merge(fullDir: string, partialDir: string, outDir: string): Promise<void> {
const full = readResults(fullDir);
const partial = readResults(partialDir);
for (const side of ["left", "right"] as const) {
if (full.meta[side] !== partial.meta[side])
throw new Error(
`${side} differs: ${full.meta[side]} in ${fullDir}, ${partial.meta[side]} in ${partialDir}`,
);
}
const real = (p: string): string => {
try {
return fs.realpathSync.native(p);
} catch {
return path.join(real(path.dirname(path.resolve(p))), path.basename(p));
}
};
for (const dir of [fullDir, partialDir]) {
const rel = path.relative(real(dir), real(outDir));
if (!rel || (rel.split(path.sep)[0] !== ".." && !path.isAbsolute(rel)))
throw new Error(`--out ${outDir} is or is inside ${dir}; pass a new directory`);
}
if (!wipeable(outDir))
throw new Error(
`output directory ${outDir} holds files renderdiff didn't write — ` +
`refusing to wipe it. Pass --out with a new or empty directory.`,
);

const key = (r: RouteResult) => `${name(r)}@${r.width}`;
const taken = new Map(
partial.results.map((r) => [key(r), { ...r, from: r.from ?? partial.meta.generatedAt }]),
);
const results = full.results.map((r) => taken.get(key(r)) ?? r);
const replaced = results.filter((r) => taken.has(key(r))).length;
const kept = new Set(full.results.map(key));
results.push(...[...taken.values()].filter((r) => !kept.has(key(r))));

const copies = new Map<string, { src: string; shot: string }>();
for (const r of results) {
const src = taken.has(key(r)) ? partialDir : fullDir;
for (const f of files(r)) {
if (!fs.existsSync(path.join(src, f))) throw new Error(`${path.join(src, f)} is missing`);
const had = copies.get(f);
if (had)
throw new Error(`${had.shot} and ${key(r)} both write ${f}; rerun both into one --out`);
copies.set(f, { src, shot: key(r) });
}
}

if (fs.existsSync(outDir)) {
for (const f of fs.readdirSync(outDir))
fs.rmSync(path.join(outDir, f), { recursive: true, force: true });
}
fs.mkdirSync(outDir, { recursive: true });
for (const [f, { src }] of copies) fs.copyFileSync(path.join(src, f), path.join(outDir, f));

const union = <T>(a: T[], b: T[]) => [
...new Map([...a, ...b].map((v) => [JSON.stringify(v), v])).values(),
];
const replays = results.flatMap((r) =>
r.status === "compared" && r.rightReplayedFrom ? [r.rightReplayedFrom] : [],
);
const meta = {
...full.meta,
widths: union(full.meta.widths, partial.meta.widths),
masks: union(full.meta.masks, partial.meta.masks),
hideSelectors: union(full.meta.hideSelectors, partial.meta.hideSelectors),
blockUrlPatterns: union(full.meta.blockUrlPatterns, partial.meta.blockUrlPatterns),
rightReplayedFrom: replays.sort()[0] ?? null,
};
const stale = [
...(full.summary.stale ?? []).filter((a) => !taken.has(`${a.route}@${a.width}`)),
...(partial.summary.stale ?? []),
];
await writeReport(results, meta, outDir, stale);
const resultsPath = writeResults(results, meta, outDir, stale);
await writeEvidence(readResults(outDir), outDir, null);
console.log(
`merged ${taken.size} shot(s) from ${partialDir} (${replaced} replaced, ` +
`${taken.size - replaced} added) into ${outDir}`,
);
console.log(compact(results, [...new Set(results.map(name))], resultsPath, meta.threshold));
}

const browserOf = (l: { browser: Browser; channel: string | null }) => ({
name: l.channel ?? "chromium",
version: l.browser.version(),
Expand Down
Loading
Loading