| 6 | import fs from 'node:fs'; |
| 7 | import path from 'node:path'; |
| 8 | import { fileURLToPath } from 'node:url'; |
| 9 | import pixelmatch from 'pixelmatch'; |
| 10 | import { PNG } from 'pngjs'; |
| 11 |
| 12 | const here = path.dirname(fileURLToPath(import.meta.url)); |
| 13 | const [dumpDir, bin, outDir] = process.argv.slice(2); |
| 14 | if (!dumpDir || !bin || !outDir) throw new Error('usage: TW_SHARED_FONTS=1 corepack pnpm tsx scripts/blitz-experiment/compare.mts <dumpDir> <twidget_render binary> <outDir>'); |
| 15 | const reportMd = fs.readFileSync(path.join(here, '..', '..', 'docs', 'compat-report-generated.md'), 'utf8'); |
| 16 | // Sandbox-vs-reference diffs from the committed report (batch heading, then rows). |
| 17 | const sandboxDiffs = new Map<string, number>(); |
| 18 | { let batch = ''; for (const line of reportMd.split('\n')) { const h = /^## ([\w-]+):/.exec(line); if (h) batch = h[1]; const r = /^\| (\S+\.html) \| . \| ([\d.]+)% \|/.exec(line); if (r) sandboxDiffs.set(`${batch}/${r[1]}`, Number(r[2]) / 100); } } |
| 19 | fs.mkdirSync(outDir, { recursive: true }); |
| 20 |
| 21 | function diffImages(a: PNG, b: PNG, name: string): number { |
| 22 | const w = Math.max(a.width, b.width), h = Math.max(a.height, b.height); |
| 23 | const pad = (img: PNG) => { if (img.width === w && img.height === h) return img; const o = new PNG({ width: w, height: h }); o.data.fill(255); PNG.bitblt(img, o, 0, 0, img.width, img.height, 0, 0); return o; }; |
| 24 | const out = new PNG({ width: w, height: h }); |
| 25 | const n = pixelmatch(pad(a).data, pad(b).data, out.data, w, h, { threshold: 0.15, includeAA: true }); |
| 26 | fs.writeFileSync(path.join(outDir, `${name}.diff.png`), PNG.sync.write(out)); |
| 27 | return n / (w * h); |
| 28 | } |
| 29 |
| 30 | interface Row { file: string; batch: string; diff: number; sandboxDiff: number | null; parse: number; layout: number; paint: number; warm: number; passes: number; total: number; height: number; refHeight: number; clicks: number; canvas: number; svg: number; inputs: number; error: string } |
| 31 | const rows: Row[] = []; |
| 32 | const metas = fs.readdirSync(dumpDir).filter((f) => f.endsWith('.meta.json')).sort(); |
| 33 | for (const m of metas) { |
| 34 | const meta = JSON.parse(fs.readFileSync(path.join(dumpDir, m), 'utf8')); |
| 35 | const name = m.replace('.meta.json', ''); |
| 36 | const html = path.join(dumpDir, `${name}.html`); |
| 37 | const png = path.join(outDir, `${name}.blitz.png`); |
| 38 | // Second run is the one timed: the first run of the process pays the font |
| 39 | // database build (~300 ms on this machine), which a host would pay once. |
| 40 | let res = spawnSync(bin, [html, String(meta.width), png], { encoding: 'utf8', timeout: 60_000 }); |
| 41 | const t0 = process.hrtime.bigint(); |
| 42 | res = spawnSync(bin, [html, String(meta.width), png], { encoding: 'utf8', timeout: 60_000 }); |
| 43 | const total = Number(process.hrtime.bigint() - t0) / 1e6; |
| 44 | let diff = 1, parse = 0, layout = 0, paint = 0, height = 0, warm = 0, passes = 0, error = ''; |
| 45 | if (res.status !== 0 || !fs.existsSync(png)) { |
| 46 | error = (res.stderr || res.error?.message || `exit ${res.status}`).split('\n').find((l) => l.trim()) ?? 'failed'; |
| 47 | } else { |
| 48 | try { const t = JSON.parse(res.stdout.trim().split('\n').pop()!); parse = t.parse_ms; layout = t.layout_ms; paint = t.paint_ms; height = t.height; warm = t.warm_ms; passes = t.passes; } catch {} |
| 49 | const ref = PNG.sync.read(fs.readFileSync(path.join(dumpDir, `${name}.reference.png`))); |
| 50 | const bl = PNG.sync.read(fs.readFileSync(png)); |
| 51 | diff = diffImages(bl, ref, name); |
| 52 | } |
| 53 | const sandboxDiff: number | null = sandboxDiffs.get(meta.file) ?? null; |
| 54 | rows.push({ file: meta.file, batch: meta.file.split('/')[0], diff, sandboxDiff, parse, layout, paint, warm, passes, total, height, refHeight: meta.height, clicks: meta.clicks, canvas: meta.canvases, svg: meta.svgs, inputs: meta.inputs, error }); |
| 55 | console.log(`${meta.file}: blitz diff ${(diff * 100).toFixed(2)}% (sandbox ${sandboxDiff == null ? '?' : (sandboxDiff * 100).toFixed(2) + '%'}) parse ${parse} layout ${layout} paint ${paint} ms; h ${height}/${meta.height} ${error}`); |
| 56 | } |
| 57 | const TOL = 0.03; |
| 58 | const med = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; }; |
| 59 | const lines: string[] = []; |
| 60 | for (const b of [...new Set(rows.map((r) => r.batch))]) { |
| 61 | const rs = rows.filter((r) => r.batch === b); |
| 62 | const pass = rs.filter((r) => r.diff <= TOL).length; |
| 63 | const sbPass = rs.filter((r) => r.sandboxDiff != null && r.sandboxDiff <= TOL).length; |
| 64 | lines.push(`## ${b}: Blitz ${pass} / ${rs.length} within ${TOL * 100}% (sandbox WebKit/Chromium path: ${sbPass} / ${rs.length})`, '', '| Widget | Blitz diff | Sandbox diff | Blitz parse / layout / paint (ms) | Height Blitz / ref | Clicks | canvas / svg / inputs | Error |', '|---|---|---|---|---|---|---|---|'); |
| 65 | for (const r of rs) lines.push(`| ${r.file.split('/')[1]} | ${(r.diff * 100).toFixed(2)}% ${r.diff <= TOL ? '✅' : '❌'} | ${r.sandboxDiff == null ? '—' : (r.sandboxDiff * 100).toFixed(2) + '%'} | ${r.parse.toFixed(0)} / ${r.layout.toFixed(0)} / ${r.paint.toFixed(0)} | ${r.height} / ${r.refHeight} | ${r.clicks} | ${r.canvas} / ${r.svg} / ${r.inputs} | ${r.error.replace(/\|/g, '\\|')} |`); |
| 66 | lines.push(''); |
| 67 | } |
| 68 | const ok = rows.filter((r) => !r.error); |
| 69 | lines.push(`Medians over ${ok.length} rendered widgets: Blitz diff ${(med(ok.map((r) => r.diff)) * 100).toFixed(2)}%, sandbox diff ${(med(ok.filter((r) => r.sandboxDiff != null).map((r) => r.sandboxDiff!)) * 100).toFixed(2)}%; Blitz parse ${med(ok.map((r) => r.parse)).toFixed(1)} ms, layout ${med(ok.map((r) => r.layout)).toFixed(1)} ms, paint ${med(ok.map((r) => r.paint)).toFixed(1)} ms, first document in the process (one-time init included) ${med(ok.map((r) => r.warm)).toFixed(0)} ms, whole process ${med(ok.map((r) => r.total)).toFixed(0)} ms.`); |
| 70 | fs.writeFileSync(path.join(outDir, 'table.md'), lines.join('\n') + '\n'); |
| 71 | fs.writeFileSync(path.join(outDir, 'rows.json'), JSON.stringify(rows, null, 2)); |
| 72 |