| 1 | // Compares what two sandbox bundles render for the same widgets: each widget runs |
| 2 | // through packages/core/scripts/sandbox-node.ts with bundle A and bundle B (B is |
| 3 | // the one built from packages/core/src unless --b is given), the validated ops of |
| 4 | // each run are applied to a small document model, and the resulting trees are |
| 5 |
| 6 | // first runs once to find clickable elements in document order, then runs |
| 7 | // again with pointerdown/up + click on each of them (at most 24) before the |
| 8 | // timer rounds, so event paths are diffed too. `adopt` elements (html, head, |
| 9 | // body) are attached where the renderer maps them; the validator sends no `ins` |
| 10 | // for them. Inline style is compared as a property map whether it arrived as a `style` attribute or as |
| 11 | // `style` ops. Every widget also runs twice on A; a widget whose two A runs |
| 12 | // differ is reported as nondeterministic, not as a difference. Both bundles run |
| 13 | // with a fixed Date, a seeded Math.random and a virtual host clock and random |
| 14 | // source, so time- and random-driven widgets compare too. |
| 15 | // |
| 16 | // Usage: pnpm tsx scripts/ops-diff.ts --a path/to/sandbox-bundle.js [--b other.js] |
| 17 | // [--timers N] [--features canvasWords,binaryOps,webAnimations] [--policy strict] [--json out.json] corpus/compat corpus/generated/… file.html |
| 18 | import fs from 'node:fs'; |
| 19 | import path from 'node:path'; |
| 20 | import { fileURLToPath } from 'node:url'; |
| 21 | import { bundleSandbox, runWidget, type RunResult } from '../packages/core/scripts/sandbox-node.ts'; |
| 22 |
| 23 | interface Node { |
| 24 | id: number; |
| 25 | kind: 'el' | 'text' | 'comment'; |
| 26 | tag: string; |
| 27 | attrs: Map<string, string>; |
| 28 | style: Map<string, string>; |
| 29 | data: string; |
| 30 | css: string | null; |
| 31 | canvas: string[]; |
| 32 | parent: Node | null; |
| 33 | children: Node[]; |
| 34 | } |
| 35 |
| 36 | const ROOT_ID = 1; |
| 37 | const PROTOCOL_HOST_KINDS = new Set(['listen', 'pd', 'raf', 'stat']); |
| 38 |
| 39 | function parseStyle(text: string): Map<string, string> { |
| 40 | const out = new Map<string, string>(); |
| 41 | let depth = 0, quote = '', start = 0; |
| 42 | const parts: string[] = []; |
| 43 | for (let i = 0; i < text.length; i++) { |
| 44 | const c = text[i]; |
| 45 | if (quote) { if (c === '\\') i++; else if (c === quote) quote = ''; continue; } |
| 46 | if (c === '"' || c === "'") quote = c; |
| 47 | else if (c === '(') depth++; |
| 48 | else if (c === ')') depth = Math.max(0, depth - 1); |
| 49 | else if (c === ';' && depth === 0) { parts.push(text.slice(start, i)); start = i + 1; } |
| 50 | } |
| 51 | parts.push(text.slice(start)); |
| 52 | for (const part of parts) { |
| 53 | const i = part.indexOf(':'); |
| 54 | if (i < 0) continue; |
| 55 | const name = part.slice(0, i).trim().toLowerCase(); |
| 56 | const value = part.slice(i + 1).trim().replace(/\s+/g, ' '); |
| 57 | if (name) out.set(name, value); |
| 58 | } |
| 59 | return out; |
| 60 | } |
| 61 |
| 62 | export function applyOps(ops: any[]): Node { |
| 63 | const nodes = new Map<number, Node>(); |
| 64 | const root: Node = { id: ROOT_ID, kind: 'el', tag: '#document', attrs: new Map(), style: new Map(), data: '', css: null, canvas: [], parent: null, children: [] }; |
| 65 | nodes.set(ROOT_ID, root); |
| 66 | const make = (id: number, kind: Node['kind'], tag: string): Node => ({ id, kind, tag, attrs: new Map(), style: new Map(), data: '', css: null, canvas: [], parent: null, children: [] }); |
| 67 | const detach = (n: Node) => { |
| 68 | if (!n.parent) return; |
| 69 | const list = n.parent.children; |
| 70 | const i = list.indexOf(n); |
| 71 | if (i >= 0) list.splice(i, 1); |
| 72 | n.parent = null; |
| 73 | }; |
| 74 | const setAttr = (n: Node, name: string, value: string) => { |
| 75 | if (name === 'style') { n.style = parseStyle(value); return; } |
| 76 | n.attrs.set(name, value); |
| 77 | }; |
| 78 | for (const op of ops) { |
| 79 | const n = nodes.get(op.id); |
| 80 | switch (op.op) { |
| 81 | case 'el': { |
| 82 | const e = make(op.id, 'el', (op.ns === 'svg' ? 'svg:' : '') + op.tag); |
| 83 | for (const [k, v] of op.attrs ?? []) setAttr(e, k, v); |
| 84 | nodes.set(op.id, e); |
| 85 | if (op.adopt) { |
| 86 | const parent = op.adopt === 'html' ? root : root.children.find((c) => c.tag === 'html'); |
| 87 | if (parent) { e.parent = parent; parent.children.push(e); } |
| 88 | } |
| 89 | break; |
| 90 | } |
| 91 | case 'text': { const t = make(op.id, 'text', '#text'); t.data = op.data; nodes.set(op.id, t); break; } |
| 92 | case 'comment': { const t = make(op.id, 'comment', '#comment'); t.data = op.data; nodes.set(op.id, t); break; } |
| 93 | case 'data': if (n) n.data = op.data; break; |
| 94 | case 'attr': if (n) setAttr(n, op.name, op.value); break; |
| 95 | case 'rattr': if (n) { if (op.name === 'style') n.style.clear(); else n.attrs.delete(op.name); } break; |
| 96 | case 'style': |
| 97 | if (n) { if (op.value === '') n.style.delete(op.name); else n.style.set(op.name, op.value + (op.important ? ' !important' : '')); } |
| 98 | break; |
| 99 | case 'css': if (n) n.css = op.text; break; |
| 100 | case 'canvas': if (n) for (const c of op.cmds ?? []) n.canvas.push(JSON.stringify(c)); break; |
| 101 | case 'ins': { |
| 102 | if (!n) break; |
| 103 | detach(n); |
| 104 | if (op.parent === 0) break; |
| 105 | const p = op.parent === ROOT_ID ? root : nodes.get(op.parent); |
| 106 | if (!p) break; |
| 107 | n.parent = p; |
| 108 | const before = op.before == null ? null : nodes.get(op.before); |
| 109 | const i = before ? p.children.indexOf(before) : -1; |
| 110 | if (i >= 0) p.children.splice(i, 0, n); else p.children.push(n); |
| 111 | break; |
| 112 | } |
| 113 | case 'rm': if (n) { detach(n); nodes.delete(op.id); } break; |
| 114 | default: if (n) n.attrs.set(`#${op.op}:${op.name ?? op.method ?? ''}`, JSON.stringify(op.value ?? op.args ?? null)); break; |
| 115 | } |
| 116 | } |
| 117 | return root; |
| 118 | } |
| 119 |
| 120 | export function serialize(n: Node, indent = ''): string { |
| 121 | if (n.kind !== 'el') return `${indent}${n.tag} ${JSON.stringify(n.data)}\n`; |
| 122 | const attrs = [...n.attrs].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, v]) => ` ${k}=${JSON.stringify(v)}`).join(''); |
| 123 | const style = n.style.size ? ` {${[...n.style].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, v]) => `${k}:${v}`).join(';')}}` : ''; |
| 124 | let out = `${indent}<${n.tag}${attrs}${style}>\n`; |
| 125 | if (n.css !== null) out += `${indent} css ${JSON.stringify(n.css)}\n`; |
| 126 | if (n.canvas.length) out += `${indent} canvas ${n.canvas.length} ${hash(n.canvas.join('\n'))}\n`; |
| 127 | for (const c of n.children) out += serialize(c, indent + ' '); |
| 128 | return out; |
| 129 | } |
| 130 |
| 131 | function hash(s: string): string { |
| 132 | let h = 0x811c9dc5; |
| 133 | for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); } |
| 134 | return (h >>> 0).toString(16); |
| 135 | } |
| 136 |
| 137 | interface Outcome { |
| 138 | tree: string; |
| 139 | diags: string[]; |
| 140 | errors: string[]; |
| 141 | unknown: string[]; |
| 142 | } |
| 143 |
| 144 | const CLICKABLE = /^(button|a|input|select|label|summary|li|td|th|span|div|svg:rect|svg:circle|svg:path|canvas)$/; |
| 145 | const MAX_CLICKS = 24; |
| 146 |
| 147 | export function clickTargets(n: Node, out: number[] = []): number[] { |
| 148 | if (n.kind === 'el' && n.id !== ROOT_ID && (CLICKABLE.test(n.tag) || n.attrs.has('onclick') || n.attrs.has('role') || n.attrs.has('tabindex'))) out.push(n.id); |
| 149 | for (const c of n.children) clickTargets(c, out); |
| 150 | return out; |
| 151 | } |
| 152 |
| 153 | export const DETERMINISM = `(function () { |
| 154 | var seed = 42; |
| 155 | Math.random = function () { seed = (Math.imul(seed, 1103515245) + 12345) & 0x7fffffff; return seed / 0x80000000; }; |
| 156 | var NativeDate = Date, fixed = 1767225600000; |
| 157 | function FixedDate() { var a = Array.prototype.slice.call(arguments); if (!new.target) return new NativeDate(fixed).toString(); return a.length ? Reflect.construct(NativeDate, a, new.target) : Reflect.construct(NativeDate, [fixed], new.target); } |
| 158 | FixedDate.prototype = NativeDate.prototype; |
| 159 | FixedDate.now = function () { return fixed; }; |
| 160 | FixedDate.parse = NativeDate.parse; |
| 161 | FixedDate.UTC = NativeDate.UTC; |
| 162 | globalThis.Date = FixedDate; |
| 163 | })(); |
| 164 | `; |
| 165 |
| 166 | function deterministic() { |
| 167 | let clock = 0, seed = 7; |
| 168 | return { |
| 169 | now: () => (clock += 4), |
| 170 | random: (count: number) => Array.from({ length: count }, () => ((seed = (Math.imul(seed, 1103515245) + 12345) & 0x7fffffff) >>> 16) & 255), |
| 171 | }; |
| 172 | } |
| 173 |
| 174 | export async function run(html: string, bundle: string, timerRounds: number, features: string[] = [], policy: 'compat' | 'strict' = 'compat'): Promise<Outcome> { |
| 175 | const unknown: string[] = []; |
| 176 | const wire = { canvasWords: features.includes('canvasWords'), binaryOps: features.includes('binaryOps'), webAnimations: features.includes('webAnimations'), policy }; |
| 177 | const first = await runWidget(html, { bundle, timerRounds: 1, ...wire, ...deterministic() }); |
| 178 | const targets = clickTargets(applyOps(first.renderOps)).slice(0, MAX_CLICKS); |
| 179 | const events = targets.flatMap((targetId) => [{ type: 'pointerdown', targetId }, { type: 'pointerup', targetId }, { type: 'click', targetId }]); |
| 180 | const r: RunResult = await runWidget(html, { bundle, timerRounds, events, ...wire, ...deterministic(), unknownHost: (kind) => { if (!PROTOCOL_HOST_KINDS.has(kind)) unknown.push(kind); } }); |
| 181 | return { |
| 182 | tree: serialize(applyOps(r.renderOps)), |
| 183 | diags: r.diags.map((d) => d.kind).sort(), |
| 184 | errors: r.logs.filter((l) => l.level === 'error').map((l) => l.text.split('\n')[0]), |
| 185 | unknown: [...new Set(unknown)].sort(), |
| 186 | }; |
| 187 | } |
| 188 |
| 189 | function firstDifference(a: string, b: string): string { |
| 190 | const la = a.split('\n'), lb = b.split('\n'); |
| 191 | for (let i = 0; i < Math.max(la.length, lb.length); i++) { |
| 192 | if (la[i] !== lb[i]) return `line ${i + 1}:\n A: ${(la[i] ?? '<end>').slice(0, 300)}\n B: ${(lb[i] ?? '<end>').slice(0, 300)}`; |
| 193 | } |
| 194 | return ''; |
| 195 | } |
| 196 |
| 197 | function widgets(args: string[]): string[] { |
| 198 | const out: string[] = []; |
| 199 | for (const a of args) { |
| 200 | const st = fs.statSync(a); |
| 201 | if (st.isDirectory()) { |
| 202 | for (const f of fs.readdirSync(a).sort()) { |
| 203 | const p = path.join(a, f); |
| 204 | if (fs.statSync(p).isDirectory()) out.push(...widgets([p])); |
| 205 | else if (f.endsWith('.html')) out.push(p); |
| 206 | } |
| 207 | } else out.push(a); |
| 208 | } |
| 209 | return out; |
| 210 | } |
| 211 |
| 212 | if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { |
| 213 | const argv = process.argv.slice(2); |
| 214 | const opt = (name: string) => { const i = argv.indexOf(name); if (i < 0) return undefined; const v = argv[i + 1]; argv.splice(i, 2); return v; }; |
| 215 | const aPath = opt('--a'); |
| 216 | const bPath = opt('--b'); |
| 217 | const jsonOut = opt('--json'); |
| 218 | const timerRounds = Number(opt('--timers') ?? 3); |
| 219 | const features = (opt('--features') ?? '').split(',').filter(Boolean); |
| 220 | const policy = opt('--policy') === 'strict' ? 'strict' : 'compat'; |
| 221 | if (!aPath || !argv.length) { console.error('usage: tsx scripts/ops-diff.ts --a bundle.js [--b bundle.js] [--timers N] [--features a,b] [--policy strict] [--json out.json] <widget.html | dir>…'); process.exit(2); } |
| 222 | const a = DETERMINISM + fs.readFileSync(aPath, 'utf8'); |
| 223 | const b = DETERMINISM + (bPath ? fs.readFileSync(bPath, 'utf8') : await bundleSandbox()); |
| 224 | const report: { file: string; status: string; detail?: string }[] = []; |
| 225 | for (const file of widgets(argv)) { |
| 226 | const html = fs.readFileSync(file, 'utf8'); |
| 227 | let status = 'same', detail = ''; |
| 228 | try { |
| 229 | const [ra, ra2, rb] = [await run(html, a, timerRounds, features, policy), await run(html, a, timerRounds, features, policy), await run(html, b, timerRounds, features, policy)]; |
| 230 | if (ra.tree !== ra2.tree) status = 'nondeterministic'; |
| 231 | else if (ra.tree !== rb.tree) { status = 'tree'; detail = firstDifference(ra.tree, rb.tree); } |
| 232 | else if (ra.errors.join('\n') !== rb.errors.join('\n')) { status = 'errors'; detail = `A: ${ra.errors.join(' | ')}\n B: ${rb.errors.join(' | ')}`; } |
| 233 | else if (ra.diags.join() !== rb.diags.join()) { status = 'diags'; detail = `A: ${ra.diags.join(',')}\n B: ${rb.diags.join(',')}`; } |
| 234 | if (ra.unknown.length || rb.unknown.length) detail += `${detail ? '\n ' : ''}unknown host kinds A: ${ra.unknown.join(',') || '-'} B: ${rb.unknown.join(',') || '-'}`; |
| 235 | } catch (e) { |
| 236 | status = 'crash'; |
| 237 | detail = String(e); |
| 238 | } |
| 239 | report.push({ file, status, detail: detail || undefined }); |
| 240 | console.log(`${status.padEnd(16)} ${file}${detail ? '\n ' + detail : ''}`); |
| 241 | } |
| 242 | const counts = report.reduce<Record<string, number>>((m, r) => ((m[r.status] = (m[r.status] ?? 0) + 1), m), {}); |
| 243 | console.log('\n' + Object.entries(counts).map(([k, v]) => `${k}: ${v}`).join(', ')); |
| 244 | if (jsonOut) fs.writeFileSync(jsonOut, JSON.stringify(report, null, 1)); |
| 245 | process.exit(report.some((r) => r.status !== 'same' && r.status !== 'nondeterministic') ? 1 : 0); |
| 246 | } |
| 247 |