Skip to content

Clone any website into a pixel-accurate Next.js app with AI — Playwright-measured extraction (no eyeballing), spec-gated parallel builder agents, and scored pixel-diff QA at phone/tablet/desktop. Works with Claude Code, Cursor, Copilot + 9 more.

perf: one-shot page recon, precise waits, and located QA mismatches

Mahanaicoach57efd90f0990
diff --git a/.claude/skills/clone-website/SKILL.md b/.claude/skills/clone-website/SKILL.md
index 4f2c512..b12c32a 100644
--- a/.claude/skills/clone-website/SKILL.md
+++ b/.claude/skills/clone-website/SKILL.md
@@ -30,18 +30,17 @@ User-provided instructions override these defaults.
## Tooling
-Ten scripts do the mechanical work — **use them instead of hand-measuring via browser MCP**:
+The scripts do the mechanical work — **use them instead of hand-measuring via browser MCP**:
| Script | Purpose |
|---|---|
+| **`node scripts/extract/page.mjs <url> [--no-site-files]`** | **THE WORKHORSE — one call, 3 page loads total.** Auto-detects sections, then produces `tokens.json` + `css.json` (skip on later pages with `--no-site-files`), `assets.json` + downloads to `public/`, `responsive.json` (all 3 viewports), a full computed-style walk per section (`sections/<name>.json`), and full-page **and** per-section screenshots at phone/iPad/PC. Accepts explicit `--selector "css" --name x` pairs to override detection. Everything is measured from the SAME page state, so numbers, walks and screenshots can never disagree |
| `node scripts/extract/crawl.mjs <url> [--max 25]` | Discover pages (sitemap + nav links) → `docs/research/<host>/sitemap.json` |
-| `node scripts/extract/tokens.mjs <url>` | Colors, fonts, :root CSS vars, shadows, global scroll behaviors → `tokens.json` |
-| `node scripts/extract/assets.mjs <url>` | Enumerate + download all images/videos/SVGs/favicons/fonts → `public/`, `assets.json` |
-| `node scripts/extract/section.mjs <url> --selector "css" [--name x] [--state scroll:600\|click:sel\|hover:sel] [--viewport pc\|ipad\|phone]` | Full computed-style DOM walk. **`--selector`/`--name` repeat — pass every section in one call and they all extract from a single page load.** `--state` captures a second state and diffs them (element styles *and* `::before`/`::after`), waiting for the section's real transition duration |
-| `node scripts/extract/screenshot.mjs <url> [--selector css] [--name x]` | Screenshots at phone/iPad/PC → `docs/design-references/<host>/` |
-| `node scripts/extract/responsive.mjs <url> [--selector css]` | Auto-detects sections and measures each one's real layout (actual column counts, hidden elements, font sizes) at all 3 viewports → `responsive.json` |
+| `node scripts/extract/section.mjs <url> --selector "css" [--name x] --state scroll:600\|click:sel\|hover:sel [--viewport pc\|ipad\|phone]` | **State captures** (page.mjs covers the default state). Captures a second state and diffs them (element styles *and* `::before`/`::after`), waiting for the section's real transition duration. `--selector`/`--name` repeat — one page load for all |
| `node scripts/extract/probe.mjs <url> --selector "css" [--selector "css2"] [--props a,b,c]` | Exact computed values for specific selectors at all 3 viewports, as a markdown table with a **varies** column — paste straight into a spec's Responsive section |
-| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] [--viewport pc] [--threshold 95]` | Scored pixel diff, original vs clone |
+| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
+| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
+| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -73,15 +72,13 @@ Browser MCP (Chrome MCP, Playwright MCP — if available) is for **judgment work
node scripts/manifest.mjs add-page --url <url> --route / # per confirmed page
```
-## Phase 1 — Recon (per site, then per page)
+## Phase 1 — Recon (one page.mjs call per page)
-**Site-wide (once):**
-1. `tokens.mjs` on the start page → read `tokens.json`
-2. `assets.mjs` on every confirmed page (it dedupes downloads across pages)
-3. `screenshot.mjs` full-page on every confirmed page — these are the master references
-4. `responsive.mjs` on every confirmed page → real layout changes per section
-5. **Interaction sweep** (judgment work — browser MCP if available): scroll each page slowly top to bottom. Does the header change? Do elements animate in? Auto-switching tabs? Scroll-snap? Smooth-scroll lib (`tokens.json` flags `.lenis`/Locomotive)? Then click every tab/pill/accordion and note what changes. Then hover. Record findings in `docs/research/<host>/BEHAVIORS.md`.
-6. **Shared chrome detection:** compare screenshots across pages — header/nav/footer that repeat become SHARED components (`SiteHeader`, `SiteFooter`), extracted once from the page where they're most complete.
+1. **First page:** `node scripts/extract/page.mjs <start-url>` — produces tokens, css, assets+downloads, responsive signatures, per-section walks, and every screenshot in one shot (3 page loads).
+2. **Every other confirmed page:** `node scripts/extract/page.mjs <url> --no-site-files` (tokens/css are site-wide; everything else is per-page). Downloads dedupe across pages automatically — files already in `public/` are skipped.
+3. **Review the detected sections** in each run's stdout summary (name, selector, pc height, headline responsive change). Detection is a heuristic: if a "section" is really two, or two are really one, re-run with explicit `--selector "css" --name x` pairs. Section names become spec/component names — rename `section-3` style fallbacks to something meaningful via `--name`.
+4. **Interaction sweep** (judgment work — browser MCP if available): scroll each page slowly top to bottom. Does the header change? Do elements animate in? Auto-switching tabs? Scroll-snap? Smooth-scroll lib (`tokens.json` flags `.lenis`/Locomotive)? Then click every tab/pill/accordion and note what changes. Then hover. `css.json`'s `interactiveStates` lists every :hover/:focus rule the stylesheet defines — use it as the checklist of what to probe. Record findings in `docs/research/<host>/BEHAVIORS.md`.
+5. **Shared chrome detection:** compare screenshots across pages — header/nav/footer that repeat become SHARED components (`SiteHeader`, `SiteFooter`), extracted once from the page where they're most complete.
**Per page — topology:** map every distinct section top to bottom with a working name, its selector, its interaction model (static / click-driven / scroll-driven / hover-driven / time-driven / mixed), and layer notes (sticky? overlay? z-index?). Save `docs/research/<host>/PAGE_TOPOLOGY.md`, then register each section:
```bash
@@ -103,22 +100,14 @@ Work through `manifest.mjs next` until no sections remain. For each section:
### 3a. Extract
-**Batch the default-state walk once per page, not once per section.** Every `--selector`
-shares a single page load, so this is one navigation instead of N:
+**The default state is already extracted** — Phase 1's page.mjs run wrote
+`sections/<name>.json`, `responsive.json`, and all screenshots. Per section, only two
+things remain:
```bash
-# ONE call covering every section on the page — do this before the per-section loop
-node scripts/extract/section.mjs <page-url> \
- --selector "<sel-1>" --name <name-1> \
- --selector "<sel-2>" --name <name-2> \
- --selector "<sel-3>" --name <name-3>
-```
-
-Then per section:
-```bash
-node scripts/extract/screenshot.mjs <page-url> --selector "<sel>" --name <name> # all 3 viewports, in parallel
-node scripts/extract/probe.mjs <page-url> --selector "<sel>" --selector "<sel> h2" # per-viewport table for the Responsive section
-# per discovered behavior — one call per state:
+# 1. Per-viewport probe table for the spec's Responsive section (batch several selectors)
+node scripts/extract/probe.mjs <page-url> --selector "<sel>" --selector "<sel> h2"
+# 2. Per discovered behavior — one call per state (batch selectors sharing a trigger):
node scripts/extract/section.mjs <page-url> --selector "<sel>" --name <name>-hover --state hover:".card"
node scripts/extract/section.mjs <page-url> --selector "<sel>" --name <name>-scrolled --state scroll:600
# per tab/pill state: --state click:".tab-2" etc. EVERY state, not just the default.
@@ -126,7 +115,9 @@ node scripts/extract/section.mjs <page-url> --selector "<sel>" --name <name>-scr
State captures wait for the section's actual transition duration, so a slow fade is
recorded at its end value, not mid-flight — check `settleMs` in the output if a diff
looks wrong. The `diff` array covers `::before`/`::after` too, which is where hover
-overlays usually live.
+overlays usually live. Cross-check discovered behaviors against `css.json`'s
+`interactiveStates` — a :hover rule in the stylesheet with no captured state means
+the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
@@ -196,15 +187,15 @@ Per page: create `src/app/<route>/page.tsx` importing its section components wit
## Phase 5 — Scored QA Loop
-Start the clone: `npm run dev` (background). Then for **every section × every viewport**:
+Start the clone: `npm run dev` (background). Then **one call per section scores all three viewports**:
```bash
-node scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --selector "<sel>" --viewport pc # then ipad, then phone
-node scripts/manifest.mjs set --route <r> --section <name> --score pc=<match>
+node scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --selector "<sel>" --viewport all --name <name>
+node scripts/manifest.mjs set --route <r> --section <name> --score pc=<match> # per viewport
```
- **Pass = ≥95% on all three viewports** → `--stage qa_passed`
-- Below 95% → open the diff image in `docs/research/qa/`, find the discrepancy, check the spec (wrong extraction → re-extract and fix; right spec, wrong build → fix component), re-diff
+- Below 95% → **read the band breakdown first**: it names the y-range where the mismatch lives, so you inspect that band of the diff image in `docs/research/qa/` instead of eyeballing the whole section. Then check the spec (wrong extraction → re-extract and fix; right spec, wrong build → fix component), re-diff
- A large height mismatch reported by diff.mjs = missing content or wrong spacing — fix before pixel-tweaking
- Max 3 fix iterations per section, then record the gap honestly and move on
- **Text-heavy sections at phone width often plateau at 90–95%** when the target's font isn't available on Google Fonts (e.g. Source Sans Pro → Source Sans 3). Different metrics = different wrap points = unavoidable pixel drift. Confirm the layout matches, note the substitution, and accept it.
diff --git a/.gitignore b/.gitignore
index 9d54e84..a47e87f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,7 @@ next-env.d.ts
# Local temp files
temp/
+*.tmp.mjs
# Playwright
.playwright/
diff --git a/canv.tmp.mjs b/canv.tmp.mjs
deleted file mode 100644
index c58d43a..0000000
--- a/canv.tmp.mjs
+++ /dev/null
@@ -1,18 +0,0 @@
-import { chromium } from "playwright";
-const b=await chromium.launch();
-const p=await b.newPage({viewport:{width:1440,height:900}});
-await p.goto("https://uploadthing.com",{waitUntil:"load",timeout:40000});
-await p.waitForTimeout(3000);
-console.log(await p.evaluate(()=>{
- const cs=[...document.querySelectorAll("canvas")];
- return JSON.stringify(cs.map(c=>{
- const r=c.getBoundingClientRect(), st=getComputedStyle(c);
- return {w:c.width,h:c.height,cssW:Math.round(r.width),cssH:Math.round(r.height),
- x:Math.round(r.x),y:Math.round(r.y),cls:c.className,id:c.id,
- pos:st.position,z:st.zIndex,opacity:st.opacity,
- parentCls:(c.parentElement?.className||"").toString().slice(0,90),
- parentTag:c.parentElement?.tagName,
- ancestors:[...(function*(e){let n=e.parentElement;let i=0;while(n&&i++<4){yield n.tagName+"."+(n.className||"").toString().split(" ")[0];n=n.parentElement}})(c)]};
- }),null,1);
-}));
-await b.close();
diff --git a/canv2.tmp.mjs b/canv2.tmp.mjs
deleted file mode 100644
index fc2bd90..0000000
--- a/canv2.tmp.mjs
+++ /dev/null
@@ -1,28 +0,0 @@
-import { chromium } from "playwright";
-import { writeFileSync } from "node:fs";
-const S="/tmp/claude-1000/-home-mahan-GitHub-Custom-Skills/dff31326-4f6e-4f2f-a117-03ae7f26903f/scratchpad";
-const b=await chromium.launch();
-const p=await b.newPage({viewport:{width:1440,height:900}});
-// intercept what gets drawn
-await p.addInitScript(()=>{
- window.__calls=[];
- const C=CanvasRenderingContext2D.prototype;
- for(const m of ["drawImage","fillRect","arc","fillText","beginPath","createLinearGradient","createRadialGradient","putImageData","clearRect","rotate","translate","scale"]){
- const o=C[m];
- C[m]=function(...a){ if(window.__calls.length<600) window.__calls.push(m); return o.apply(this,a); };
- }
- const gc=HTMLCanvasElement.prototype.getContext;
- HTMLCanvasElement.prototype.getContext=function(t,...r){ window.__ctxType=(window.__ctxType||[]).concat(t); return gc.call(this,t,...r); };
-});
-await p.goto("https://uploadthing.com",{waitUntil:"load",timeout:40000});
-await p.waitForTimeout(4000);
-const info=await p.evaluate(()=>{
- const counts={}; for(const c of window.__calls||[]) counts[c]=(counts[c]||0)+1;
- return {ctxTypes:window.__ctxType, callCounts:counts, total:(window.__calls||[]).length};
-});
-console.log(JSON.stringify(info,null,1));
-// screenshot just the canvas
-const c=p.locator("canvas").first();
-await c.screenshot({path:S+"/ut-canvas.png"});
-console.log("canvas shot saved");
-await b.close();
diff --git a/canv3.tmp.mjs b/canv3.tmp.mjs
deleted file mode 100644
index d500161..0000000
--- a/canv3.tmp.mjs
+++ /dev/null
@@ -1,16 +0,0 @@
-import { chromium } from "playwright";
-import { createHash } from "node:crypto";
-const b=await chromium.launch();
-const p=await b.newPage({viewport:{width:1440,height:900}});
-await p.goto("https://uploadthing.com",{waitUntil:"load",timeout:40000});
-await p.waitForTimeout(3500);
-const c=p.locator("canvas").first();
-const hashes=[];
-for(let i=0;i<4;i++){
- const buf=await c.screenshot();
- hashes.push(createHash("md5").update(buf).digest("hex").slice(0,12));
- await p.waitForTimeout(1200);
-}
-console.log("frame hashes:",hashes.join(" "));
-console.log("animated:", new Set(hashes).size>1);
-await b.close();
diff --git a/scripts/diff.mjs b/scripts/diff.mjs
index 5dc3430..3f56508 100644
--- a/scripts/diff.mjs
+++ b/scripts/diff.mjs
@@ -3,12 +3,19 @@
//
// File mode: node scripts/diff.mjs --a original.png --b clone.png [--out diff.png]
// Live mode: node scripts/diff.mjs --original <url> --clone <url> [--selector css]
-// [--clone-selector css] [--viewport pc|ipad|phone] [--name hero]
+// [--clone-selector css] [--viewport pc|ipad|phone|all|pc,phone] [--name hero]
//
// --selector applies to both sides; --clone-selector overrides it for the clone
// when your component's markup uses different hooks than the target's.
+// --viewport takes one name, a comma list, or "all" (= pc,ipad,phone). Default: pc.
//
-// Prints a match % (higher = closer). Exit code 1 if --threshold given and not met.
+// Prints ONE JSON object to stdout: { name, viewports: { pc: {...}, ipad: {...} } }.
+// Single-viewport and file-mode runs use the same shape with one key (file mode
+// reports under "file") — a consistent shape is easier for the calling agent
+// than a flat object that changes layout depending on how it was invoked.
+// Each viewport carries a 10-band breakdown so the caller learns WHERE the
+// mismatch lives, not just how much of it there is.
+// Exit code 1 if --threshold given and ANY requested viewport is below it.
// Live-mode artifacts land in docs/research/qa/.
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { PNG } from "pngjs";
@@ -37,61 +44,119 @@ async function shoot(url, path, viewport, selector) {
return path;
}
-let fileA = args.a;
-let fileB = args.b;
-let outPath = args.out;
+const BAND_COUNT = 10;
+
+// Compare two PNGs cropped to their shared area (full-page heights rarely match
+// exactly). The diff runs once per horizontal band instead of once overall:
+// band-level numbers tell the caller WHICH tenth of the page drifted, and the
+// total is the sum of the bands so both numbers always agree — a separate
+// whole-image pass could disagree slightly at band seams, where pixelmatch's
+// anti-aliasing detection loses its vertical neighbors.
+function compare(pathA, pathB, outPath) {
+ const imgA = PNG.sync.read(readFileSync(pathA));
+ const imgB = PNG.sync.read(readFileSync(pathB));
+ const width = Math.min(imgA.width, imgB.width);
+ const height = Math.min(imgA.height, imgB.height);
+
+ const diffImg = new PNG({ width, height });
+ const bands = [];
+ let mismatched = 0;
+ for (let i = 0; i < BAND_COUNT; i++) {
+ const y0 = Math.floor((height * i) / BAND_COUNT);
+ const y1 = i === BAND_COUNT - 1 ? height : Math.floor((height * (i + 1)) / BAND_COUNT);
+ const bandH = y1 - y0;
+ const label = { band: `${i * 10}-${(i + 1) * 10}%`, yRange: `${y0}-${y1}px` };
+ if (bandH <= 0) {
+ // Image shorter than 10px: report the empty band as perfect instead of
+ // handing pixelmatch a zero-height buffer.
+ bands.push({ ...label, match: 100 });
+ continue;
+ }
+ // bitblt straight out of the source images with a y offset — the shared-area
+ // crop and the band slice are the same copy.
+ const sliceA = new PNG({ width, height: bandH });
+ const sliceB = new PNG({ width, height: bandH });
+ const sliceDiff = new PNG({ width, height: bandH });
+ PNG.bitblt(imgA, sliceA, 0, y0, width, bandH, 0, 0);
+ PNG.bitblt(imgB, sliceB, 0, y0, width, bandH, 0, 0);
+ const bandMismatch = pixelmatch(sliceA.data, sliceB.data, sliceDiff.data, width, bandH, { threshold: 0.1 });
+ // Reassemble the band diffs into one full-size diff image at their offsets,
+ // so the artifact looks identical to a single whole-image pass.
+ PNG.bitblt(sliceDiff, diffImg, 0, 0, width, bandH, 0, y0);
+ mismatched += bandMismatch;
+ bands.push({ ...label, match: Number((100 - (bandMismatch / (width * bandH)) * 100).toFixed(2)) });
+ }
+ const match = 100 - (mismatched / (width * height)) * 100;
+ if (outPath) writeFileSync(outPath, PNG.sync.write(diffImg));
+ return {
+ match: Number(match.toFixed(2)),
+ mismatchedPixels: mismatched,
+ width,
+ height,
+ originalHeight: imgA.height,
+ cloneHeight: imgB.height,
+ diffImage: outPath || null,
+ bands,
+ };
+}
+
+const results = {}; // viewport name -> compare() result
+let name;
if (args.original && args.clone) {
- const vp = args.viewport || "pc";
- const name = args.name || slugify(args.selector || "page");
+ const vpArg = !args.viewport || args.viewport === true ? "pc" : String(args.viewport);
+ const vpNames = vpArg === "all" ? ["pc", "ipad", "phone"] : vpArg.split(",").map((s) => s.trim()).filter(Boolean);
+ const unknown = vpNames.filter((v) => !VIEWPORTS[v]);
+ if (!vpNames.length || unknown.length) {
+ console.error(`Unknown viewport(s): ${unknown.join(", ") || vpArg} — use ${Object.keys(VIEWPORTS).join(", ")}, a comma list, or "all"`);
+ process.exit(1);
+ }
+ name = args.name || slugify(args.selector || "page");
const dir = "docs/research/qa";
mkdirSync(dir, { recursive: true });
- // Both sides shoot concurrently on one browser — they're independent pages.
- [fileA, fileB] = await Promise.all([
- shoot(args.original, `${dir}/${name}-${vp}-original.png`, VIEWPORTS[vp], args.selector),
- shoot(args.clone, `${dir}/${name}-${vp}-clone.png`, VIEWPORTS[vp], args["clone-selector"] || args.selector),
- ]);
+ // Every (side × viewport) shot is an independent page in its own context, so
+ // ALL of them run concurrently on the one shared browser — a 3-viewport run
+ // costs barely more wall time than a 1-viewport run.
+ await Promise.all(
+ vpNames.flatMap((vp) => [
+ shoot(args.original, `${dir}/${name}-${vp}-original.png`, VIEWPORTS[vp], args.selector),
+ shoot(args.clone, `${dir}/${name}-${vp}-clone.png`, VIEWPORTS[vp], args["clone-selector"] || args.selector),
+ ])
+ );
await closeBrowser();
- outPath = outPath || `${dir}/${name}-${vp}-diff.png`;
-}
-if (!fileA || !fileB) {
- console.error("Usage: diff.mjs --a orig.png --b clone.png OR --original <url> --clone <url> [--selector css] [--viewport pc]");
+ for (const vp of vpNames) {
+ // --out keeps its old single-run meaning; multi-viewport runs would clobber
+ // one file with every diff, so they always use the per-viewport path.
+ const outPath = vpNames.length === 1 && args.out ? args.out : `${dir}/${name}-${vp}-diff.png`;
+ results[vp] = compare(`${dir}/${name}-${vp}-original.png`, `${dir}/${name}-${vp}-clone.png`, outPath);
+ }
+} else if (args.a && args.b) {
+ name = args.name || "file";
+ results.file = compare(args.a, args.b, args.out || null);
+} else {
+ console.error("Usage: diff.mjs --a orig.png --b clone.png OR --original <url> --clone <url> [--selector css] [--viewport pc|ipad|phone|all|pc,phone]");
process.exit(1);
}
-const imgA = PNG.sync.read(readFileSync(fileA));
-const imgB = PNG.sync.read(readFileSync(fileB));
-
-// Crop both to the shared area (full-page heights rarely match exactly)
-const width = Math.min(imgA.width, imgB.width);
-const height = Math.min(imgA.height, imgB.height);
-function crop(img) {
- if (img.width === width && img.height === height) return img;
- const out = new PNG({ width, height });
- PNG.bitblt(img, out, 0, 0, width, height, 0, 0);
- return out;
-}
-const a = crop(imgA);
-const b = crop(imgB);
-const diffImg = new PNG({ width, height });
-const mismatched = pixelmatch(a.data, b.data, diffImg.data, width, height, { threshold: 0.1 });
-const match = 100 - (mismatched / (width * height)) * 100;
+console.log(JSON.stringify({ name, viewports: results }, null, 2));
-if (outPath) {
- writeFileSync(outPath, PNG.sync.write(diffImg));
+for (const [vp, r] of Object.entries(results)) {
+ const worst = r.bands.reduce((w, b) => (b.match < w.match ? b : w));
+ const heightNote =
+ r.originalHeight !== r.cloneHeight
+ ? ` · HEIGHT MISMATCH: original ${r.originalHeight}px vs clone ${r.cloneHeight}px (compared top ${r.height}px)`
+ : "";
+ console.error(`[${vp}] Match: ${r.match.toFixed(2)}% · worst band: ${worst.band} (y ${worst.yRange}) at ${worst.match}%${heightNote}`);
}
-const heightNote =
- imgA.height !== imgB.height ? ` · HEIGHT MISMATCH: original ${imgA.height}px vs clone ${imgB.height}px (compared top ${height}px)` : "";
-console.log(
- JSON.stringify(
- { match: Number(match.toFixed(2)), mismatchedPixels: mismatched, width, height, originalHeight: imgA.height, cloneHeight: imgB.height, diffImage: outPath || null },
- null,
- 2
- )
-);
-console.error(`Match: ${match.toFixed(2)}%${heightNote}`);
-if (args.threshold && match < Number(args.threshold)) {
- console.error(`FAIL: below threshold ${args.threshold}%`);
- process.exit(1);
+if (args.threshold) {
+ const t = Number(args.threshold);
+ let failed = false;
+ for (const [vp, r] of Object.entries(results)) {
+ if (r.match < t) {
+ console.error(`FAIL [${vp}]: ${r.match}% below threshold ${t}%`);
+ failed = true;
+ }
+ }
+ if (failed) process.exit(1);
}
diff --git a/scripts/extract/assets.mjs b/scripts/extract/assets.mjs
index 9e16f9d..341a77b 100644
--- a/scripts/extract/assets.mjs
+++ b/scripts/extract/assets.mjs
@@ -1,11 +1,11 @@
#!/usr/bin/env node
// Enumerate and download every asset on a page: <img> (incl. layered/overlay),
// <video>, CSS background images, inline SVGs, favicons/OG images, fonts.
+// Enumeration and downloading live in collectors.mjs — this file is just the CLI.
// Usage: node scripts/extract/assets.mjs <url> [--no-download]
// Output: docs/research/<host>/assets.json + files in public/
-import { createHash } from "node:crypto";
-import { mkdirSync, writeFileSync } from "node:fs";
import { launchPage, gotoAndSettle, autoScroll, hostOf, writeJson, parseArgs } from "../lib.mjs";
+import { collectAssets, downloadAssets } from "./collectors.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
@@ -19,168 +19,25 @@ const { browser, page } = await launchPage();
await gotoAndSettle(page, url);
await autoScroll(page); // trigger lazy loading
-const found = await page.evaluate(() => {
- const cssUrl = (bg) => {
- const m = bg.match(/url\(["']?([^"')]+)["']?\)/);
- return m ? new URL(m[1], location.href).href : null;
- };
- return {
- images: [...document.querySelectorAll("img")].map((img) => ({
- src: img.currentSrc || img.src,
- srcset: img.srcset || null,
- alt: img.alt,
- naturalWidth: img.naturalWidth,
- naturalHeight: img.naturalHeight,
- // layered-composition hints: siblings + positioning
- siblingImgs: img.parentElement ? img.parentElement.querySelectorAll("img").length : 1,
- position: getComputedStyle(img).position,
- zIndex: getComputedStyle(img).zIndex,
- parentClasses: (img.parentElement?.className || "").toString().slice(0, 80),
- })),
- videos: [...document.querySelectorAll("video")].map((v) => ({
- src: v.currentSrc || v.src || v.querySelector("source")?.src || null,
- poster: v.poster || null,
- autoplay: v.autoplay,
- loop: v.loop,
- muted: v.muted,
- playsInline: v.playsInline,
- })),
- backgroundImages: [...document.querySelectorAll("*")]
- .map((el) => {
- const bg = getComputedStyle(el).backgroundImage;
- if (!bg || bg === "none" || !bg.includes("url(")) return null;
- const u = cssUrl(bg);
- return u && !u.startsWith("data:")
- ? { url: u, element: el.tagName.toLowerCase() + "." + (el.className?.toString().split(" ")[0] || "") }
- : null;
- })
- .filter(Boolean),
- inlineSvgs: [...document.querySelectorAll("svg")].map((s) => ({
- outerHTML: s.outerHTML.slice(0, 4000),
- width: s.getAttribute("width") || s.getBoundingClientRect().width,
- height: s.getAttribute("height") || s.getBoundingClientRect().height,
- context: (s.closest("a,button")?.textContent || s.parentElement?.className || "").toString().trim().slice(0, 60),
- })),
- // Rasters referenced from inside inline SVG (<image href>, <pattern><image>).
- // These are invisible to an <img> scan, yet sites use them for full-size
- // screenshots — miss one and a whole section renders empty.
- svgImages: [...document.querySelectorAll("image")]
- .map((im) => {
- const href = im.getAttribute("href") || im.getAttribute("xlink:href");
- if (!href || href.startsWith("data:")) return null;
- const r = im.getBoundingClientRect();
- return {
- url: new URL(href, location.href).href,
- renderedWidth: Math.round(r.width),
- renderedHeight: Math.round(r.height),
- insidePattern: !!im.closest("pattern"),
- };
- })
- .filter(Boolean),
- seo: {
- favicons: [...document.querySelectorAll('link[rel*="icon"]')].map((l) => ({ href: l.href, sizes: l.sizes?.toString() || "" })),
- ogImage: document.querySelector('meta[property="og:image"]')?.content || null,
- manifest: document.querySelector('link[rel="manifest"]')?.href || null,
- title: document.title,
- description: document.querySelector('meta[name="description"]')?.content || null,
- },
- fonts: performance
- .getEntriesByType("resource")
- .filter((r) => /\.(woff2?|ttf|otf)(\?|$)/i.test(r.name))
- .map((r) => r.name),
- };
-});
-await browser.close();
-
-// De-duplicate inline SVGs by content hash
-const svgSeen = new Set();
-found.inlineSvgs = found.inlineSvgs.filter((s) => {
- const h = createHash("md5").update(s.outerHTML).digest("hex");
- if (svgSeen.has(h)) return false;
- svgSeen.add(h);
- return true;
-});
+const found = await collectAssets(page);
+await browser.close(); // downloads go over plain fetch — no browser needed
-// ---- Download ----
-const host = hostOf(url);
-const manifest = [];
-const destFor = (remote, kind) => {
- const u = new URL(remote);
- const base = decodeURIComponent(u.pathname.split("/").pop() || "asset").replace(/[^a-zA-Z0-9.._-]/g, "_");
- const name = base.includes(".") ? base : base + ".bin";
- const dir = kind === "video" ? "public/videos" : kind === "seo" ? "public/seo" : kind === "font" ? "public/fonts" : "public/images";
- return { dir, path: `${dir}/${name}`, name };
-};
-
-async function download(remote, kind) {
- if (!remote || remote.startsWith("data:")) return null;
- const { dir, path } = destFor(remote, kind);
- if (manifest.some((m) => m.local === path && m.remote !== remote)) {
- // filename collision with a different asset — disambiguate with a short hash
- const h = createHash("md5").update(remote).digest("hex").slice(0, 6);
- const parts = path.split(".");
- parts[parts.length - 2] += `-${h}`;
- return downloadTo(remote, kind, dir, parts.join("."));
- }
- return downloadTo(remote, kind, dir, path);
-}
-async function downloadTo(remote, kind, dir, path) {
- if (manifest.some((m) => m.remote === remote)) return manifest.find((m) => m.remote === remote).local;
- try {
- const res = await fetch(remote, { signal: AbortSignal.timeout(30000), headers: { "User-Agent": "Mozilla/5.0" } });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- // extension-less URLs (common for favicons/OG): derive extension from content-type
- if (path.endsWith(".bin")) {
- const ct = res.headers.get("content-type") || "";
- const ext = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg", "image/gif": "gif", "image/x-icon": "ico", "image/vnd.microsoft.icon": "ico", "image/avif": "avif", "video/mp4": "mp4", "video/webm": "webm" }[ct.split(";")[0]];
- if (ext) path = path.replace(/\.bin$/, `.${ext}`);
- }
- mkdirSync(dir, { recursive: true });
- writeFileSync(path, Buffer.from(await res.arrayBuffer()));
- manifest.push({ remote, local: path, kind, ok: true });
- return path;
- } catch (e) {
- manifest.push({ remote, local: null, kind, ok: false, error: String(e.message || e) });
- return null;
- }
-}
+const manifest = doDownload ? await downloadAssets(found, { pool: 8 }) : [];
-if (doDownload) {
- const jobs = [
- ...found.images.map((i) => ({ url: i.src, kind: "image" })),
- ...found.backgroundImages.map((b) => ({ url: b.url, kind: "image" })),
- ...found.svgImages.map((b) => ({ url: b.url, kind: "image" })),
- ...found.videos.flatMap((v) => [v.src && { url: v.src, kind: "video" }, v.poster && { url: v.poster, kind: "image" }].filter(Boolean)),
- ...found.seo.favicons.map((f) => ({ url: f.href, kind: "seo" })),
- ...(found.seo.ogImage ? [{ url: found.seo.ogImage, kind: "seo" }] : []),
- ...found.fonts.map((f) => ({ url: f, kind: "font" })),
- ];
- // batched 4-way parallel downloads
- for (let i = 0; i < jobs.length; i += 4) {
- await Promise.all(jobs.slice(i, i + 4).map((j) => download(j.url, j.kind)));
- }
-}
-
-// Attach local paths back onto the found entries
-const localFor = (remote) => manifest.find((m) => m.remote === remote)?.local || null;
-found.images.forEach((i) => (i.local = localFor(i.src)));
-found.backgroundImages.forEach((b) => (b.local = localFor(b.url)));
-found.svgImages.forEach((b) => (b.local = localFor(b.url)));
-found.videos.forEach((v) => {
- v.local = localFor(v.src);
- v.posterLocal = localFor(v.poster);
-});
-
-writeJson(`docs/research/${host}/assets.json`, {
+writeJson(`docs/research/${hostOf(url)}/assets.json`, {
url,
generatedAt: new Date().toISOString(),
...found,
downloads: manifest,
});
+
const okCount = manifest.filter((m) => m.ok).length;
const failCount = manifest.filter((m) => !m.ok).length;
+const cachedCount = manifest.filter((m) => m.cached).length;
console.log(
`Images: ${found.images.length} · BG images: ${found.backgroundImages.length} · SVG rasters: ${found.svgImages.length} · Videos: ${found.videos.length} · SVGs: ${found.inlineSvgs.length} · Fonts: ${found.fonts.length}` +
- (doDownload ? ` · Downloaded: ${okCount} ok, ${failCount} failed` : " · (download skipped)")
+ (doDownload
+ ? ` · Downloaded: ${okCount} ok${cachedCount ? ` (${cachedCount} already on disk)` : ""}, ${failCount} failed`
+ : " · (download skipped)")
);
if (failCount > 0) console.log("Failed downloads listed in assets.json — retry or fetch manually.");
diff --git a/scripts/extract/collectors.mjs b/scripts/extract/collectors.mjs
new file mode 100644
index 0000000..fa5dec5
--- /dev/null
+++ b/scripts/extract/collectors.mjs
@@ -0,0 +1,795 @@
+// Shared extraction collectors. Every in-page measurement payload lives here
+// exactly once, so the thin CLI scripts (tokens/css/assets/responsive/section)
+// and the one-shot page.mjs can never drift apart. Each collector takes a live
+// Playwright page that has already been gotoAndSettle'd + autoScroll'ed.
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
+
+// ---------------------------------------------------------------------------
+// Design tokens (colors, fonts, css vars, keyframes, global behaviors)
+// ---------------------------------------------------------------------------
+export async function collectTokens(page) {
+ return page.evaluate(() => {
+ const els = [...document.querySelectorAll("body *")].slice(0, 3000);
+ const count = (map, key) => key && map.set(key, (map.get(key) || 0) + 1);
+ const colors = new Map();
+ const bgs = new Map();
+ const families = new Map();
+ const radii = new Map();
+ const shadows = new Map();
+ const fontSizes = new Map();
+
+ for (const el of els) {
+ const cs = getComputedStyle(el);
+ count(colors, cs.color);
+ if (cs.backgroundColor !== "rgba(0, 0, 0, 0)") count(bgs, cs.backgroundColor);
+ count(families, cs.fontFamily);
+ if (cs.borderRadius !== "0px") count(radii, cs.borderRadius);
+ if (cs.boxShadow !== "none") count(shadows, cs.boxShadow);
+ if (el.textContent?.trim()) count(fontSizes, `${cs.fontSize}/${cs.fontWeight}/${cs.lineHeight}`);
+ }
+ const top = (map, n = 20) =>
+ [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([value, uses]) => ({ value, uses }));
+
+ // Typography of key elements
+ const typo = {};
+ for (const sel of ["h1", "h2", "h3", "h4", "p", "a", "button", "body"]) {
+ const el = document.querySelector(sel);
+ if (!el) continue;
+ const cs = getComputedStyle(el);
+ typo[sel] = {
+ fontFamily: cs.fontFamily,
+ fontSize: cs.fontSize,
+ fontWeight: cs.fontWeight,
+ lineHeight: cs.lineHeight,
+ letterSpacing: cs.letterSpacing,
+ color: cs.color,
+ textTransform: cs.textTransform,
+ };
+ }
+
+ // :root custom properties + @keyframes bodies (same-origin stylesheets only).
+ // Capturing keyframes matters: computed styles tell you `animation: slide-up-fade 1s`
+ // but not what slide-up-fade DOES. Without the rule body a builder can only guess.
+ const cssVars = {};
+ const keyframes = {};
+ const walkRules = (rules) => {
+ for (const rule of rules) {
+ if (rule.type === 7 || rule.constructor?.name === "CSSKeyframesRule") {
+ const steps = {};
+ for (const kf of rule.cssRules) steps[kf.keyText] = kf.style.cssText;
+ keyframes[rule.name] = steps;
+ continue;
+ }
+ if (rule.cssRules) {
+ try {
+ walkRules(rule.cssRules);
+ } catch { /* ignore */ }
+ continue;
+ }
+ if (rule.selectorText === ":root" || rule.selectorText === "html") {
+ for (const prop of rule.style) {
+ if (prop.startsWith("--")) cssVars[prop] = rule.style.getPropertyValue(prop).trim();
+ }
+ }
+ }
+ };
+ for (const sheet of document.styleSheets) {
+ try {
+ walkRules(sheet.cssRules);
+ } catch {
+ continue; // cross-origin sheet
+ }
+ }
+
+ // Which animations are actually used on the page, and on how many elements
+ const animationsInUse = {};
+ for (const el of els) {
+ const cs = getComputedStyle(el);
+ if (cs.animationName && cs.animationName !== "none") {
+ const key = `${cs.animationName} | ${cs.animationDuration} | ${cs.animationTimingFunction} | ${cs.animationIterationCount} | delay ${cs.animationDelay}`;
+ animationsInUse[key] = (animationsInUse[key] || 0) + 1;
+ }
+ }
+
+ const fontLinks = [...document.querySelectorAll('link[rel="stylesheet"], link[rel="preload"][as="font"]')]
+ .map((l) => l.href)
+ .filter((h) => /fonts\.|font|\.woff/i.test(h));
+
+ const htmlCs = getComputedStyle(document.documentElement);
+ const bodyCs = getComputedStyle(document.body);
+ const globalBehaviors = {
+ smoothScrollLib: document.querySelector(".lenis, [data-lenis], .locomotive-scroll, [data-scroll-container]")
+ ? "detected (Lenis or Locomotive — inspect manually)"
+ : null,
+ scrollBehavior: htmlCs.scrollBehavior,
+ scrollSnapType: htmlCs.scrollSnapType !== "none" ? htmlCs.scrollSnapType : bodyCs.scrollSnapType !== "none" ? bodyCs.scrollSnapType : null,
+ bodyBackground: bodyCs.backgroundColor,
+ hasFixedHeader: !!document.querySelector("header, nav") &&
+ ["fixed", "sticky"].includes(getComputedStyle(document.querySelector("header, nav")).position),
+ };
+
+ return {
+ colors: top(colors),
+ backgrounds: top(bgs),
+ fontFamilies: top(families, 10),
+ typography: typo,
+ fontSizeCombos: top(fontSizes, 25),
+ borderRadii: top(radii, 10),
+ boxShadows: top(shadows, 10),
+ cssVariables: cssVars,
+ keyframes,
+ animationsInUse,
+ fontLinks,
+ globalBehaviors,
+ };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Stylesheet rules (hover/focus states, breakpoints, keyframe names)
+// ---------------------------------------------------------------------------
+
+// Light brace-matching parser: CSS is regular enough at this level, and this
+// avoids taking a dependency just to find hover rules.
+export function splitRules(css) {
+ const out = [];
+ let depth = 0, buf = "", atRule = null, atBuf = "";
+ for (let i = 0; i < css.length; i++) {
+ const ch = css[i];
+ if (ch === "{") {
+ depth++;
+ if (depth === 1) {
+ const head = buf.trim();
+ buf = "";
+ if (head.startsWith("@media") || head.startsWith("@supports") || head.startsWith("@layer") || head.startsWith("@container")) {
+ atRule = head;
+ atBuf = "";
+ continue;
+ }
+ out.push({ selector: head, body: "", _open: true });
+ continue;
+ }
+ } else if (ch === "}") {
+ depth--;
+ if (depth === 0) {
+ if (atRule) {
+ for (const inner of splitRules(atBuf)) out.push({ ...inner, media: atRule });
+ atRule = null;
+ atBuf = "";
+ } else {
+ const last = out[out.length - 1];
+ if (last?._open) {
+ last.body = buf.trim();
+ delete last._open;
+ }
+ buf = "";
+ }
+ continue;
+ }
+ }
+ if (atRule && depth >= 1) atBuf += ch;
+ else buf += ch;
+ }
+ return out.filter((r) => r.selector && !r.selector.startsWith("@"));
+}
+
+const STATE_RE = /:(hover|focus|focus-visible|focus-within|active|checked|disabled|target|open)\b/;
+
+// Collect every stylesheet's text (fetching cross-origin ones directly), parse
+// out interactive-state rules, real breakpoints, and keyframe names.
+export async function collectCss(page, { selector = null } = {}) {
+ const collected = await page.evaluate(() => {
+ const sheets = [];
+ for (const sheet of document.styleSheets) {
+ let rules = null;
+ try {
+ rules = sheet.cssRules;
+ } catch {
+ sheets.push({ href: sheet.href, blocked: true, text: null });
+ continue;
+ }
+ const text = [...rules].map((r) => r.cssText).join("\n");
+ sheets.push({ href: sheet.href || "(inline <style>)", blocked: false, text });
+ }
+ return sheets;
+ });
+
+ // Fetch anything the browser refused to expose — all in parallel.
+ await Promise.all(
+ collected
+ .filter((s) => s.blocked && s.href)
+ .map(async (s) => {
+ try {
+ const res = await fetch(s.href, { signal: AbortSignal.timeout(20000), headers: { "User-Agent": "Mozilla/5.0" } });
+ if (res.ok) {
+ s.text = await res.text();
+ s.blocked = false;
+ s.fetched = true;
+ }
+ } catch {
+ /* leave blocked — reported in the summary */
+ }
+ })
+ );
+
+ const allCss = collected.filter((s) => s.text).map((s) => s.text).join("\n");
+ const rules = splitRules(allCss);
+
+ const interactive = rules
+ .filter((r) => STATE_RE.test(r.selector))
+ .map((r) => ({ selector: r.selector.trim(), declarations: r.body, media: r.media || null }));
+
+ const byState = {};
+ for (const r of interactive) {
+ const m = r.selector.match(STATE_RE);
+ const k = m ? m[1] : "other";
+ (byState[k] ||= []).push(r);
+ }
+
+ const breakpoints = [...new Set(
+ (allCss.match(/@media[^{]+/g) || [])
+ .flatMap((m) => m.match(/\(\s*(min|max)-width\s*:\s*[^)]+\)/g) || [])
+ .map((s) => s.replace(/\s+/g, " ").trim())
+ )].sort();
+
+ const keyframeNames = [...new Set((allCss.match(/@keyframes\s+([\w-]+)/g) || []).map((s) => s.replace(/@keyframes\s+/, "")))];
+
+ // Optional: exact matched rules for one element, via CDP — same data as the
+ // DevTools Styles panel, including :hover rules.
+ let matched = null;
+ if (selector) {
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send("DOM.enable");
+ await cdp.send("CSS.enable");
+ const { root } = await cdp.send("DOM.getDocument", { depth: -1 });
+ const { nodeId } = await cdp.send("DOM.querySelector", { nodeId: root.nodeId, selector });
+ if (!nodeId) {
+ console.error(`Element not found: ${selector}`);
+ } else {
+ const styles = await cdp.send("CSS.getMatchedStylesForNode", { nodeId });
+ matched = {
+ selector,
+ matchedRules: (styles.matchedCSSRules || []).map((m) => ({
+ selector: m.rule.selectorList?.text,
+ origin: m.rule.origin,
+ media: m.rule.media?.map((x) => x.text) || null,
+ declarations: (m.rule.style?.cssProperties || [])
+ .filter((p) => !p.disabled && p.value)
+ .map((p) => `${p.name}: ${p.value}`),
+ })),
+ pseudoRules: (styles.pseudoElements || []).map((p) => ({
+ pseudoType: p.pseudoType,
+ rules: p.matches?.map((m) => ({
+ selector: m.rule.selectorList?.text,
+ declarations: (m.rule.style?.cssProperties || []).filter((x) => !x.disabled && x.value).map((x) => `${x.name}: ${x.value}`),
+ })),
+ })),
+ inherited: (styles.inherited || []).length,
+ };
+ }
+ }
+
+ return {
+ stylesheets: collected.map((s) => ({ href: s.href, blocked: s.blocked, fetched: !!s.fetched, bytes: s.text?.length || 0 })),
+ totalRules: rules.length,
+ breakpoints,
+ keyframeNames,
+ interactiveStates: byState,
+ interactiveCount: interactive.length,
+ blockedCount: collected.filter((s) => s.blocked).length,
+ matched,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Assets (enumerate on the page, then download in a worker pool)
+// ---------------------------------------------------------------------------
+export async function collectAssets(page) {
+ const found = await page.evaluate(() => {
+ const cssUrl = (bg) => {
+ const m = bg.match(/url\(["']?([^"')]+)["']?\)/);
+ return m ? new URL(m[1], location.href).href : null;
+ };
+ return {
+ images: [...document.querySelectorAll("img")].map((img) => ({
+ src: img.currentSrc || img.src,
+ srcset: img.srcset || null,
+ alt: img.alt,
+ naturalWidth: img.naturalWidth,
+ naturalHeight: img.naturalHeight,
+ // layered-composition hints: siblings + positioning
+ siblingImgs: img.parentElement ? img.parentElement.querySelectorAll("img").length : 1,
+ position: getComputedStyle(img).position,
+ zIndex: getComputedStyle(img).zIndex,
+ parentClasses: (img.parentElement?.className || "").toString().slice(0, 80),
+ })),
+ videos: [...document.querySelectorAll("video")].map((v) => ({
+ src: v.currentSrc || v.src || v.querySelector("source")?.src || null,
+ poster: v.poster || null,
+ autoplay: v.autoplay,
+ loop: v.loop,
+ muted: v.muted,
+ playsInline: v.playsInline,
+ })),
+ backgroundImages: [...document.querySelectorAll("*")]
+ .map((el) => {
+ const bg = getComputedStyle(el).backgroundImage;
+ if (!bg || bg === "none" || !bg.includes("url(")) return null;
+ const u = cssUrl(bg);
+ return u && !u.startsWith("data:")
+ ? { url: u, element: el.tagName.toLowerCase() + "." + (el.className?.toString().split(" ")[0] || "") }
+ : null;
+ })
+ .filter(Boolean),
+ inlineSvgs: [...document.querySelectorAll("svg")].map((s) => ({
+ outerHTML: s.outerHTML.slice(0, 4000),
+ width: s.getAttribute("width") || s.getBoundingClientRect().width,
+ height: s.getAttribute("height") || s.getBoundingClientRect().height,
+ context: (s.closest("a,button")?.textContent || s.parentElement?.className || "").toString().trim().slice(0, 60),
+ })),
+ // Rasters referenced from inside inline SVG (<image href>, <pattern><image>).
+ // These are invisible to an <img> scan, yet sites use them for full-size
+ // screenshots — miss one and a whole section renders empty.
+ svgImages: [...document.querySelectorAll("image")]
+ .map((im) => {
+ const href = im.getAttribute("href") || im.getAttribute("xlink:href");
+ if (!href || href.startsWith("data:")) return null;
+ const r = im.getBoundingClientRect();
+ return {
+ url: new URL(href, location.href).href,
+ renderedWidth: Math.round(r.width),
+ renderedHeight: Math.round(r.height),
+ insidePattern: !!im.closest("pattern"),
+ };
+ })
+ .filter(Boolean),
+ seo: {
+ favicons: [...document.querySelectorAll('link[rel*="icon"]')].map((l) => ({ href: l.href, sizes: l.sizes?.toString() || "" })),
+ ogImage: document.querySelector('meta[property="og:image"]')?.content || null,
+ manifest: document.querySelector('link[rel="manifest"]')?.href || null,
+ title: document.title,
+ description: document.querySelector('meta[name="description"]')?.content || null,
+ },
+ fonts: performance
+ .getEntriesByType("resource")
+ .filter((r) => /\.(woff2?|ttf|otf)(\?|$)/i.test(r.name))
+ .map((r) => r.name),
+ };
+ });
+
+ // De-duplicate inline SVGs by content hash
+ const svgSeen = new Set();
+ found.inlineSvgs = found.inlineSvgs.filter((s) => {
+ const h = createHash("md5").update(s.outerHTML).digest("hex");
+ if (svgSeen.has(h)) return false;
+ svgSeen.add(h);
+ return true;
+ });
+ return found;
+}
+
+// Download every asset `found` references into public/, with a concurrency pool
+// (not batch barriers — one slow file no longer stalls three fast ones) and a
+// disk short-circuit: a file that already exists locally is not re-fetched, so
+// multi-page runs and resumed runs only pay for what's new.
+export async function downloadAssets(found, { pool = 8, skipExisting = true } = {}) {
+ const manifest = [];
+ const byRemote = new Map(); // remote url -> manifest entry (dedupe)
+ const usedPaths = new Map(); // local path -> remote url (collision detect)
+
+ const destFor = (remote, kind) => {
+ const u = new URL(remote);
+ const base = decodeURIComponent(u.pathname.split("/").pop() || "asset").replace(/[^a-zA-Z0-9.._-]/g, "_");
+ const name = base.includes(".") ? base : base + ".bin";
+ const dir = kind === "video" ? "public/videos" : kind === "seo" ? "public/seo" : kind === "font" ? "public/fonts" : "public/images";
+ return { dir, path: `${dir}/${name}` };
+ };
+
+ async function fetchOne(remote, kind) {
+ let { dir, path } = destFor(remote, kind);
+ if (usedPaths.has(path) && usedPaths.get(path) !== remote) {
+ // filename collision with a different asset — disambiguate with a short hash
+ const h = createHash("md5").update(remote).digest("hex").slice(0, 6);
+ const parts = path.split(".");
+ parts[parts.length - 2] += `-${h}`;
+ path = parts.join(".");
+ }
+ usedPaths.set(path, remote);
+ if (skipExisting && !path.endsWith(".bin") && existsSync(path) && statSync(path).size > 0) {
+ manifest.push({ remote, local: path, kind, ok: true, cached: true });
+ return;
+ }
+ try {
+ const res = await fetch(remote, { signal: AbortSignal.timeout(30000), headers: { "User-Agent": "Mozilla/5.0" } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ // extension-less URLs (common for favicons/OG): derive extension from content-type
+ if (path.endsWith(".bin")) {
+ const ct = res.headers.get("content-type") || "";
+ const ext = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/svg+xml": "svg", "image/gif": "gif", "image/x-icon": "ico", "image/vnd.microsoft.icon": "ico", "image/avif": "avif", "video/mp4": "mp4", "video/webm": "webm" }[ct.split(";")[0]];
+ if (ext) path = path.replace(/\.bin$/, `.${ext}`);
+ if (skipExisting && existsSync(path) && statSync(path).size > 0) {
+ manifest.push({ remote, local: path, kind, ok: true, cached: true });
+ return;
+ }
+ }
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path, Buffer.from(await res.arrayBuffer()));
+ manifest.push({ remote, local: path, kind, ok: true });
+ } catch (e) {
+ manifest.push({ remote, local: null, kind, ok: false, error: String(e.message || e) });
+ }
+ }
+
+ const jobs = [
+ ...found.images.map((i) => ({ url: i.src, kind: "image" })),
+ ...found.backgroundImages.map((b) => ({ url: b.url, kind: "image" })),
+ ...found.svgImages.map((b) => ({ url: b.url, kind: "image" })),
+ ...found.videos.flatMap((v) => [v.src && { url: v.src, kind: "video" }, v.poster && { url: v.poster, kind: "image" }].filter(Boolean)),
+ ...found.seo.favicons.map((f) => ({ url: f.href, kind: "seo" })),
+ ...(found.seo.ogImage ? [{ url: found.seo.ogImage, kind: "seo" }] : []),
+ ...found.fonts.map((f) => ({ url: f, kind: "font" })),
+ ].filter((j) => j.url && !j.url.startsWith("data:"));
+
+ // Dedupe by remote URL, then drain a shared queue with `pool` workers.
+ const queue = [];
+ for (const j of jobs) {
+ if (byRemote.has(j.url)) continue;
+ byRemote.set(j.url, true);
+ queue.push(j);
+ }
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: Math.min(pool, queue.length) }, async () => {
+ while (next < queue.length) {
+ const j = queue[next++];
+ await fetchOne(j.url, j.kind);
+ }
+ })
+ );
+
+ // Attach local paths back onto the found entries
+ const localFor = (remote) => manifest.find((m) => m.remote === remote)?.local || null;
+ found.images.forEach((i) => (i.local = localFor(i.src)));
+ found.backgroundImages.forEach((b) => (b.local = localFor(b.url)));
+ found.svgImages.forEach((b) => (b.local = localFor(b.url)));
+ found.videos.forEach((v) => {
+ v.local = localFor(v.src);
+ v.posterLocal = localFor(v.poster);
+ });
+ return manifest;
+}
+
+// ---------------------------------------------------------------------------
+// Section detection + responsive signatures (batched: one evaluate per page)
+// ---------------------------------------------------------------------------
+
+// Auto-detect the page's top-level sections. Semantic elements are leaves;
+// generic wrapper divs get expanded through; repeated collections stay whole.
+export async function detectSections(page) {
+ return page.evaluate(() => {
+ const LEAF = new Set(["SECTION", "HEADER", "FOOTER", "NAV", "ASIDE", "ARTICLE", "MAIN"]);
+ const MIN_H = 40; // site headers are often ~44px on phones
+ const found = [];
+ // Produce a selector that provably resolves back to this exact element.
+ function selectorFor(el) {
+ const tag = el.tagName.toLowerCase();
+ const ok = (s) => {
+ try {
+ return document.querySelector(s) === el ? s : null;
+ } catch {
+ return null;
+ }
+ };
+ if (el.id) {
+ const s = ok(tag + "#" + CSS.escape(el.id));
+ if (s) return s;
+ }
+ const classes = (el.className?.toString() || "").split(/\s+/).filter(Boolean).map((c) => CSS.escape(c));
+ for (const n of [1, 2, 3]) {
+ if (classes.length < n) break;
+ const s = ok(tag + "." + classes.slice(0, n).join("."));
+ if (s) return s;
+ }
+ // Guaranteed fallback: absolute nth-child path from <body>
+ const parts = [];
+ let cur = el;
+ while (cur && cur !== document.body && cur.parentElement) {
+ parts.unshift(":nth-child(" + ([...cur.parentElement.children].indexOf(cur) + 1) + ")");
+ cur = cur.parentElement;
+ }
+ return "body > " + parts.join(" > ");
+ }
+ // A real section is roughly viewport-scale. Anything much taller is a
+ // container holding several sections, so keep descending through it.
+ const MAX_SECTION_H = Math.max(1400, window.innerHeight * 1.6);
+ function walk(el, depth) {
+ if (depth > 7 || found.length > 25) return;
+ for (const child of el.children) {
+ if (["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "svg", "SVG"].includes(child.tagName)) continue;
+ const r = child.getBoundingClientRect();
+ if (r.height < MIN_H) continue;
+ const bigKids = [...child.children].filter((k) => k.getBoundingClientRect().height >= MIN_H);
+ // A repeated collection (a card grid, a tile row) is ONE section — it
+ // becomes one component fed by a data array, never N sections. Requires
+ // same tag AND similar heights: three <div>s of 852/2161/974px is a page
+ // scaffold, not a grid, and must still be descended into.
+ const kidHeights = bigKids.map((k) => k.getBoundingClientRect().height);
+ const minKid = Math.min(...kidHeights);
+ const maxKid = Math.max(...kidHeights);
+ const isCollection =
+ bigKids.length >= 3 &&
+ new Set(bigKids.map((k) => k.tagName)).size === 1 &&
+ maxKid - minKid <= maxKid * 0.25 && // siblings are roughly equal
+ r.height <= MAX_SECTION_H;
+ // The rule: a section is the first element small enough to BE a section.
+ if (!isCollection && bigKids.length >= 1) {
+ if (r.height > MAX_SECTION_H) {
+ walk(child, depth + 1);
+ continue;
+ }
+ // A pure wrapper adds nothing of its own — unwrap it even at section
+ // scale (common in React output: div > div > main > …).
+ if (!LEAF.has(child.tagName) && !child.id && bigKids.length === 1 && bigKids[0].getBoundingClientRect().height >= r.height * 0.92) {
+ walk(child, depth + 1);
+ continue;
+ }
+ // A semantic element wrapping only other semantic sections.
+ if (LEAF.has(child.tagName) && bigKids.length > 1 && bigKids.every((k) => LEAF.has(k.tagName))) {
+ walk(child, depth + 1);
+ continue;
+ }
+ }
+ const sel = selectorFor(child);
+ if (!found.some((f) => f.selector === sel) && document.querySelector(sel) === child) {
+ found.push({ selector: sel, label: sel });
+ }
+ }
+ }
+ walk(document.body, 0);
+ // Site chrome is always worth its own spec even when nested inside a wrapper
+ for (const tag of ["header", "footer"]) {
+ const el = document.querySelector(tag);
+ if (!el || el.getBoundingClientRect().height < MIN_H) continue;
+ const sel = selectorFor(el);
+ if (!found.some((f) => f.selector === sel)) found.unshift({ selector: sel, label: sel });
+ }
+ return found;
+ });
+}
+
+// Layout signatures for MANY selectors in ONE evaluate round-trip.
+export async function measureSections(page, selectors) {
+ return page.evaluate((sels) => {
+ const signature = (selector) => {
+ const el = document.querySelector(selector);
+ if (!el) return { error: "not found" };
+ const cs = getComputedStyle(el);
+ const rect = el.getBoundingClientRect();
+ const kids = [...el.children];
+ const visibleKids = kids.filter((k) => {
+ const kcs = getComputedStyle(k);
+ return kcs.display !== "none" && kcs.visibility !== "hidden";
+ });
+ // Find the container with the most visible children — that's the "grid" of
+ // the section regardless of technique (grid, flex-wrap, floats, width %).
+ const candidates = [el, ...el.querySelectorAll("*")].slice(0, 300);
+ let gridEl = el, maxKids = 0;
+ for (const c of candidates) {
+ const vis = [...c.children].filter((k) => {
+ const r = k.getBoundingClientRect();
+ return r.width > 40 && r.height > 40 && getComputedStyle(k).display !== "none";
+ });
+ if (vis.length > maxKids) { maxKids = vis.length; gridEl = c; }
+ }
+ // Real column count = children sharing the first row (same top, ±10px)
+ const gkids = [...gridEl.children].filter((k) => {
+ const r = k.getBoundingClientRect();
+ return r.width > 40 && r.height > 40 && getComputedStyle(k).display !== "none";
+ });
+ let realColumns = null;
+ if (gkids.length >= 2) {
+ const firstTop = gkids[0].getBoundingClientRect().top;
+ realColumns = gkids.filter((k) => Math.abs(k.getBoundingClientRect().top - firstTop) < 10).length;
+ }
+ const gcs = getComputedStyle(gridEl);
+ const h = el.querySelector("h1,h2,h3");
+ return {
+ width: Math.round(rect.width),
+ height: Math.round(rect.height),
+ display: cs.display,
+ flexDirection: cs.flexDirection,
+ innerLayout: {
+ display: gcs.display,
+ flexDirection: gcs.flexDirection,
+ flexWrap: gcs.flexWrap,
+ gridColumns: gcs.gridTemplateColumns === "none" ? null : gcs.gridTemplateColumns.split(" ").length,
+ realColumns,
+ itemCount: gkids.length,
+ gap: gcs.gap,
+ },
+ childCount: kids.length,
+ visibleChildCount: visibleKids.length,
+ hiddenChildren: kids.length - visibleKids.length,
+ headingFontSize: h ? getComputedStyle(h).fontSize : null,
+ paddingX: cs.paddingLeft + " / " + cs.paddingRight,
+ fontSize: cs.fontSize,
+ };
+ };
+ const out = {};
+ for (const sel of sels) out[sel] = signature(sel);
+ return out;
+ }, selectors);
+}
+
+// Human-readable phone/ipad/pc change summary for one selector.
+export function summarizeResponsive(results, sel) {
+ const p = results.phone?.[sel] || {};
+ const t = results.ipad?.[sel] || {};
+ const d = results.pc?.[sel] || {};
+ const changes = [];
+ const cmp = (label, a, b, aName, bName) => {
+ if (a != null && b != null && a !== b) changes.push(`${label}: ${b} (${bName}) → ${a} (${aName})`);
+ };
+ cmp("columns", p.innerLayout?.realColumns, d.innerLayout?.realColumns, "phone", "pc");
+ cmp("grid-template columns", p.innerLayout?.gridColumns, d.innerLayout?.gridColumns, "phone", "pc");
+ cmp("flex direction", p.innerLayout?.flexDirection, d.innerLayout?.flexDirection, "phone", "pc");
+ cmp("heading size", p.headingFontSize, d.headingFontSize, "phone", "pc");
+ cmp("visible children", p.visibleChildCount, d.visibleChildCount, "phone", "pc");
+ cmp("hidden children", p.hiddenChildren, d.hiddenChildren, "phone", "pc");
+ cmp("padding-x", p.paddingX, d.paddingX, "phone", "pc");
+ const ipadLike =
+ JSON.stringify(t.innerLayout) === JSON.stringify(d.innerLayout) ? "ipad matches pc layout"
+ : JSON.stringify(t.innerLayout) === JSON.stringify(p.innerLayout) ? "ipad matches phone layout"
+ : "ipad has its own intermediate layout";
+ return { changes: changes.length ? changes : ["no layout change across viewports"], ipadBehavior: ipadLike };
+}
+
+// ---------------------------------------------------------------------------
+// Deep section walk (batched: one evaluate for many selectors)
+// ---------------------------------------------------------------------------
+
+// Full computed-style DOM walk for MANY selectors in ONE evaluate. Rects carry
+// both viewport coords (x/y) and absolute page coords (pageX/pageY) so geometry
+// stays comparable across sections captured at different scroll positions.
+export async function walkSections(page, selectors, { depth = 5 } = {}) {
+ return page.evaluate(
+ ({ selectors, maxDepth }) => {
+ const PROPS = [
+ "fontSize","fontWeight","fontFamily","lineHeight","letterSpacing","color","textAlign",
+ "textTransform","textDecoration","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
+ "paddingTop","paddingRight","paddingBottom","paddingLeft",
+ "marginTop","marginRight","marginBottom","marginLeft",
+ "width","height","maxWidth","minWidth","maxHeight","minHeight",
+ "display","flexDirection","flexWrap","justifyContent","alignItems","gap","rowGap","columnGap",
+ "gridTemplateColumns","gridTemplateRows","gridAutoFlow",
+ "borderRadius","borderTopWidth","borderBottomWidth","borderLeftWidth","borderRightWidth","borderColor","borderStyle",
+ "boxShadow","overflow","overflowX","overflowY",
+ "position","top","right","bottom","left","zIndex","inset",
+ "opacity","transform","transition","animation","cursor","pointerEvents","visibility",
+ "objectFit","objectPosition","mixBlendMode","filter","backdropFilter",
+ "whiteSpace","textOverflow","aspectRatio","order","flexGrow","flexShrink","flexBasis",
+ ];
+ const SKIP = new Set(["none","normal","auto","0px","rgba(0, 0, 0, 0)","visible","static","initial",""]);
+ function styles(element) {
+ const cs = getComputedStyle(element);
+ const out = {};
+ for (const p of PROPS) {
+ const v = cs[p];
+ if (v !== undefined && !SKIP.has(v)) out[p] = v;
+ }
+ return out;
+ }
+ function directText(element) {
+ return [...element.childNodes]
+ .filter((n) => n.nodeType === 3)
+ .map((n) => n.textContent.trim())
+ .filter(Boolean)
+ .join(" ")
+ .slice(0, 500) || null;
+ }
+ // ::before / ::after carry real visuals (underline bars, icon glyphs,
+ // overlays) that getComputedStyle on the element itself never reveals.
+ const PSEUDO_PROPS = [
+ "content","width","height","backgroundColor","backgroundImage","backgroundSize","borderRadius",
+ "position","top","right","bottom","left","transform","opacity","display",
+ "borderBottomWidth","borderTopWidth","borderLeftWidth","borderRightWidth","borderColor","borderStyle",
+ "margin","padding","zIndex","boxShadow","transition","mixBlendMode","filter",
+ ];
+ const PSEUDO_TEXT_PROPS = ["fontFamily","fontSize","fontWeight","color","lineHeight","letterSpacing","textAlign"];
+ function pseudos(element) {
+ const out = {};
+ for (const pe of ["::before", "::after"]) {
+ const cs = getComputedStyle(element, pe);
+ if (!cs.content || cs.content === "none") continue;
+ const hasText = cs.content !== '""' && cs.content !== "''" && !cs.content.startsWith("url(");
+ const st = { content: cs.content };
+ for (const p of [...PSEUDO_PROPS, ...(hasText ? PSEUDO_TEXT_PROPS : [])]) {
+ const v = cs[p];
+ if (v !== undefined && !SKIP.has(v)) st[p] = v;
+ }
+ // A pseudo with no box and no text renders nothing — skip it
+ if (Object.keys(st).length > 1) out[pe] = st;
+ }
+ return Object.keys(out).length ? out : undefined;
+ }
+ const MAX_KIDS = 40;
+ function walk(element, d) {
+ if (d > maxDepth) return { truncated: true, tag: element.tagName.toLowerCase() };
+ const kids = [...element.children];
+ const rect = element.getBoundingClientRect();
+ return {
+ tag: element.tagName.toLowerCase(),
+ classes: (element.className?.toString() || "").split(" ").filter(Boolean).slice(0, 6).join(" ") || null,
+ text: directText(element),
+ href: element.tagName === "A" ? element.getAttribute("href") : undefined,
+ ariaLabel: element.getAttribute("aria-label") || undefined,
+ img: element.tagName === "IMG"
+ ? { src: element.currentSrc || element.src, alt: element.alt, w: element.naturalWidth, h: element.naturalHeight }
+ : undefined,
+ isSvg: element.tagName.toLowerCase() === "svg" || undefined,
+ rect: {
+ x: Math.round(rect.x),
+ y: Math.round(rect.y),
+ pageX: Math.round(rect.x + window.scrollX),
+ pageY: Math.round(rect.y + window.scrollY),
+ w: Math.round(rect.width),
+ h: Math.round(rect.height),
+ },
+ styles: styles(element),
+ pseudo: pseudos(element),
+ childCount: kids.length,
+ truncatedChildren: kids.length > MAX_KIDS ? kids.length - MAX_KIDS : undefined,
+ children: kids.slice(0, MAX_KIDS).map((c) => walk(c, d + 1)),
+ };
+ }
+ const out = {};
+ for (const selector of selectors) {
+ const el = document.querySelector(selector);
+ out[selector] = el ? walk(el, 0) : { error: "Element not found: " + selector };
+ }
+ return out;
+ },
+ { selectors, maxDepth: depth }
+ );
+}
+
+// Style deltas between two captures of the same subtree, element by element.
+// Both real styles and pseudo-element styles count: a hover effect built from a
+// ::before overlay changes nothing on the element itself.
+export function diffNode(a, b, path, out) {
+ if (!a || !b || a.error || b.error) return;
+ const keys = new Set([...Object.keys(a.styles || {}), ...Object.keys(b.styles || {})]);
+ for (const k of keys) {
+ if ((a.styles?.[k] || null) !== (b.styles?.[k] || null)) {
+ out.push({ path, prop: k, before: a.styles?.[k] ?? "(unset)", after: b.styles?.[k] ?? "(unset)" });
+ }
+ }
+ for (const pe of ["::before", "::after"]) {
+ const pa = a.pseudo?.[pe] || {};
+ const pb = b.pseudo?.[pe] || {};
+ const pkeys = new Set([...Object.keys(pa), ...Object.keys(pb)]);
+ for (const k of pkeys) {
+ if ((pa[k] || null) !== (pb[k] || null)) {
+ out.push({ path: path + pe, prop: k, before: pa[k] ?? "(unset)", after: pb[k] ?? "(unset)" });
+ }
+ }
+ }
+ (a.children || []).forEach((c, i) => diffNode(c, b.children?.[i], `${path} > ${c.tag}[${i}]`, out));
+}
+
+// Short, readable section name from an auto-detected selector. Real ids and
+// semantic tags make good names; Tailwind utility soup does not — `.flex` or an
+// escaped `bg-\[\#150002\]` (whose \# would false-match a naive id regex) must
+// fall through to section-N rather than become the section's identity.
+const UTILITY_CLASS = /^(flex|grid|block|inline|relative|absolute|sticky|fixed|hidden|container|group|peer|isolate|w-|h-|max-|min-|size-|bg-|text-|font-|p[trblxyse]?-|m[trblxyse]?-|space-|gap-|items-|justify-|content-|self-|place-|overflow|rounded|border|ring|shadow|opacity-|z-|inset-|top-|left-|right-|bottom-|col-|row-|order-|grow|shrink|basis-|aspect-|object-|translate|scale|rotate|transition|duration-|ease-|delay-|animate-|cursor-|select-|pointer-|sr-only|not-sr|leading-|tracking-|whitespace-|break-|truncate|align-|list-|divide-|from-|via-|to-|backdrop-|blur|mix-blend|will-change|origin-|columns-|(sm|md|lg|xl|2xl|hover|focus|active|dark|group-hover)[:\\])/;
+export function nameFromSelector(sel, index) {
+ const id = sel.match(/(?<!\\)#([a-zA-Z][\w-]*)/);
+ if (id) return id[1].toLowerCase();
+ const tag = sel.match(/^([a-z]+)(?:[.#[:]|$)/)?.[1];
+ if (tag && ["header", "footer", "nav", "main", "aside", "article", "form"].includes(tag)) return tag;
+ const classes = [...sel.matchAll(/(?<!\\)\.([a-zA-Z][\w-]{2,})/g)].map((m) => m[1]);
+ const meaningful = classes.find((c) => !UTILITY_CLASS.test(c));
+ if (meaningful) return meaningful.toLowerCase().slice(0, 24);
+ return `section-${index + 1}`;
+}
diff --git a/scripts/extract/crawl.mjs b/scripts/extract/crawl.mjs
index b1ab731..dc036ac 100644
--- a/scripts/extract/crawl.mjs
+++ b/scripts/extract/crawl.mjs
@@ -13,7 +13,7 @@ if (!startUrl) {
const MAX = Number(args.max ?? 25);
const origin = new URL(startUrl).origin;
-// 1. Try sitemap.xml (no browser needed)
+// 1. Try sitemap.xml (no browser needed) — runs concurrently with the page load below
// Same-site check that tolerates www./non-www mismatches (very common)
const sameSite = (a, b) => {
try {
@@ -23,57 +23,66 @@ const sameSite = (a, b) => {
}
};
-const fromSitemap = new Set();
-try {
- const res = await fetch(`${origin}/sitemap.xml`, { signal: AbortSignal.timeout(10000) });
- if (res.ok) {
- const xml = await res.text();
- let locs = [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => m[1].trim());
- // sitemap index → fetch child sitemaps (first 5)
+const fetchLocs = async (u) => {
+ const res = await fetch(u, { signal: AbortSignal.timeout(10000) });
+ if (!res.ok) return [];
+ return [...(await res.text()).matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => m[1].trim());
+};
+
+const collectSitemap = async () => {
+ const fromSitemap = new Set();
+ try {
+ const locs = await fetchLocs(`${origin}/sitemap.xml`);
+ // sitemap index → fetch child sitemaps (first 5) in parallel
const children = locs.filter((u) => u.endsWith(".xml")).slice(0, 5);
- for (const child of children) {
- try {
- const r = await fetch(child, { signal: AbortSignal.timeout(10000) });
- if (r.ok) locs.push(...[...(await r.text()).matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => m[1].trim()));
- } catch { /* skip broken child sitemap */ }
- }
+ const childLocs = await Promise.all(
+ children.map((child) => fetchLocs(child).catch(() => [] /* skip broken child sitemap */))
+ );
+ locs.push(...childLocs.flat());
for (const u of locs) {
if (sameSite(u, origin) && !u.endsWith(".xml")) fromSitemap.add(u);
}
+ } catch {
+ // no sitemap — fine, nav links below are the primary source
}
-} catch {
- // no sitemap — fine, nav links below are the primary source
-}
+ return fromSitemap;
+};
// 2. Collect same-origin links from the rendered start page
-const { browser, page } = await launchPage();
-await gotoAndSettle(page, startUrl);
-const links = await page.evaluate(() => {
- const inNav = (el) => !!el.closest("header, nav, footer");
- const host = location.hostname.replace(/^www\./, "");
- const seen = new Map();
- for (const a of document.querySelectorAll("a[href]")) {
- const href = a.href.split("#")[0].split("?")[0];
- let linkHost;
- try {
- linkHost = new URL(href).hostname.replace(/^www\./, "");
- } catch {
- continue;
+const collectLinks = async () => {
+ const { browser, page } = await launchPage();
+ await gotoAndSettle(page, startUrl);
+ const links = await page.evaluate(() => {
+ const inNav = (el) => !!el.closest("header, nav, footer");
+ const host = location.hostname.replace(/^www\./, "");
+ const seen = new Map();
+ for (const a of document.querySelectorAll("a[href]")) {
+ const href = a.href.split("#")[0].split("?")[0];
+ let linkHost;
+ try {
+ linkHost = new URL(href).hostname.replace(/^www\./, "");
+ } catch {
+ continue;
+ }
+ if (linkHost !== host) continue;
+ if (/\.(pdf|zip|jpg|jpeg|png|webp|svg|mp4|xml|ico)$/i.test(href)) continue;
+ const prev = seen.get(href);
+ const entry = {
+ url: href,
+ text: (a.textContent || "").trim().slice(0, 60),
+ source: inNav(a) ? "nav" : "body",
+ };
+ // nav placement wins over body placement
+ if (!prev || (prev.source === "body" && entry.source === "nav")) seen.set(href, entry);
}
- if (linkHost !== host) continue;
- if (/\.(pdf|zip|jpg|jpeg|png|webp|svg|mp4|xml|ico)$/i.test(href)) continue;
- const prev = seen.get(href);
- const entry = {
- url: href,
- text: (a.textContent || "").trim().slice(0, 60),
- source: inNav(a) ? "nav" : "body",
- };
- // nav placement wins over body placement
- if (!prev || (prev.source === "body" && entry.source === "nav")) seen.set(href, entry);
- }
- return [...seen.values()];
-});
-await browser.close();
+ return [...seen.values()];
+ });
+ await browser.close();
+ return links;
+};
+
+// Sitemap fetches and the browser page load are independent — overlap them.
+const [fromSitemap, links] = await Promise.all([collectSitemap(), collectLinks()]);
// 3. Merge: start page first, then nav links, then sitemap-only, then body links
const merged = new Map();
diff --git a/scripts/extract/css.mjs b/scripts/extract/css.mjs
index 88a7326..ffdd960 100644
--- a/scripts/extract/css.mjs
+++ b/scripts/extract/css.mjs
@@ -4,11 +4,7 @@
// Computed styles only tell you how an element looks right now. The stylesheet
// tells you every state it can be in: :hover, :focus, :active, media queries,
// keyframes. Reading the rules catches interactions you'd never think to probe.
-//
-// Sources handled:
-// - inline <style> blocks
-// - same-origin stylesheets (via cssRules)
-// - cross-origin stylesheets (cssRules throws → fetched directly by URL)
+// All the parsing lives in collectors.mjs — this file is just the CLI.
//
// Usage:
// node scripts/extract/css.mjs <url> # whole-page rule dump
@@ -18,6 +14,7 @@
// Styles panel, incl. :hover)
// Output: docs/research/<host>/css.json (+ a summary to stdout)
import { launchPage, gotoAndSettle, autoScroll, hostOf, writeJson, parseArgs } from "../lib.mjs";
+import { collectCss } from "./collectors.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
@@ -30,167 +27,23 @@ const { browser, page } = await launchPage();
await gotoAndSettle(page, url);
await autoScroll(page);
-// ── 1. Collect stylesheet text from inside the page ───────────────────
-const collected = await page.evaluate(() => {
- const sheets = [];
- for (const sheet of document.styleSheets) {
- let rules = null;
- try {
- rules = sheet.cssRules;
- } catch {
- // cross-origin: record the href so we can fetch it outside the page
- sheets.push({ href: sheet.href, blocked: true, text: null });
- continue;
- }
- const text = [...rules].map((r) => r.cssText).join("\n");
- sheets.push({ href: sheet.href || "(inline <style>)", blocked: false, text });
- }
- return sheets;
-});
-
-// ── 2. Fetch anything the browser refused to expose ───────────────────
-for (const s of collected) {
- if (!s.blocked || !s.href) continue;
- try {
- const res = await fetch(s.href, { signal: AbortSignal.timeout(20000), headers: { "User-Agent": "Mozilla/5.0" } });
- if (res.ok) {
- s.text = await res.text();
- s.blocked = false;
- s.fetched = true;
- }
- } catch {
- /* leave blocked — reported in the summary */
- }
-}
-
-const allCss = collected.filter((s) => s.text).map((s) => s.text).join("\n");
-
-// ── 3. Parse out the parts that matter for cloning ────────────────────
-// A light brace-matching parser: CSS is regular enough at this level, and this
-// avoids taking a dependency just to find hover rules.
-function splitRules(css) {
- const out = [];
- let depth = 0, buf = "", atRule = null, atBuf = "";
- for (let i = 0; i < css.length; i++) {
- const ch = css[i];
- if (ch === "{") {
- depth++;
- if (depth === 1) {
- const head = buf.trim();
- buf = "";
- if (head.startsWith("@media") || head.startsWith("@supports") || head.startsWith("@layer") || head.startsWith("@container")) {
- atRule = head;
- atBuf = "";
- continue;
- }
- out.push({ selector: head, body: "", _open: true });
- continue;
- }
- } else if (ch === "}") {
- depth--;
- if (depth === 0) {
- if (atRule) {
- // recurse into the group, tagging each inner rule with its condition
- for (const inner of splitRules(atBuf)) out.push({ ...inner, media: atRule });
- atRule = null;
- atBuf = "";
- } else {
- const last = out[out.length - 1];
- if (last?._open) {
- last.body = buf.trim();
- delete last._open;
- }
- buf = "";
- }
- continue;
- }
- }
- if (atRule && depth >= 1) atBuf += ch;
- else buf += ch;
- }
- return out.filter((r) => r.selector && !r.selector.startsWith("@"));
-}
-
-const rules = splitRules(allCss);
-
-const STATE_RE = /:(hover|focus|focus-visible|focus-within|active|checked|disabled|target|open)\b/;
-const interactive = rules
- .filter((r) => STATE_RE.test(r.selector))
- .map((r) => ({ selector: r.selector.trim(), declarations: r.body, media: r.media || null }));
-
-const byState = {};
-for (const r of interactive) {
- const m = r.selector.match(STATE_RE);
- const k = m ? m[1] : "other";
- (byState[k] ||= []).push(r);
-}
-
-// Real breakpoint values, straight from the source
-const breakpoints = [...new Set(
- (allCss.match(/@media[^{]+/g) || [])
- .flatMap((m) => m.match(/\(\s*(min|max)-width\s*:\s*[^)]+\)/g) || [])
- .map((s) => s.replace(/\s+/g, " ").trim())
-)].sort();
-
-const keyframeNames = [...new Set((allCss.match(/@keyframes\s+([\w-]+)/g) || []).map((s) => s.replace(/@keyframes\s+/, "")))];
-
-const host = hostOf(url);
-
-// ── 4. Optional: exact matched rules for one element, via CDP ─────────
-let matched = null;
-if (args.selector) {
- const cdp = await page.context().newCDPSession(page);
- await cdp.send("DOM.enable");
- await cdp.send("CSS.enable");
- const { root } = await cdp.send("DOM.getDocument", { depth: -1 });
- const { nodeId } = await cdp.send("DOM.querySelector", { nodeId: root.nodeId, selector: args.selector });
- if (!nodeId) {
- console.error(`Element not found: ${args.selector}`);
- } else {
- const styles = await cdp.send("CSS.getMatchedStylesForNode", { nodeId });
- matched = {
- selector: args.selector,
- // every rule that applies, in cascade order — same list DevTools shows
- matchedRules: (styles.matchedCSSRules || []).map((m) => ({
- selector: m.rule.selectorList?.text,
- origin: m.rule.origin,
- media: m.rule.media?.map((x) => x.text) || null,
- declarations: (m.rule.style?.cssProperties || [])
- .filter((p) => !p.disabled && p.value)
- .map((p) => `${p.name}: ${p.value}`),
- })),
- // :hover / :focus / etc. rules Chrome knows about for this element
- pseudoRules: (styles.pseudoElements || []).map((p) => ({
- pseudoType: p.pseudoType,
- rules: p.matches?.map((m) => ({
- selector: m.rule.selectorList?.text,
- declarations: (m.rule.style?.cssProperties || []).filter((x) => !x.disabled && x.value).map((x) => `${x.name}: ${x.value}`),
- })),
- })),
- inherited: (styles.inherited || []).length,
- };
- }
-}
-
+const css = await collectCss(page, { selector: args.selector || null });
await browser.close();
-writeJson(`docs/research/${host}/css.json`, {
+// The counts drive the stdout summary only — they're derivable from the JSON,
+// so persisting them would just be two more fields to keep in sync.
+const { interactiveCount, blockedCount, ...persisted } = css;
+writeJson(`docs/research/${hostOf(url)}/css.json`, {
url,
generatedAt: new Date().toISOString(),
- stylesheets: collected.map((s) => ({ href: s.href, blocked: s.blocked, fetched: !!s.fetched, bytes: s.text?.length || 0 })),
- totalRules: rules.length,
- breakpoints,
- keyframeNames,
- interactiveStates: byState,
- matched,
+ ...persisted,
});
-const blocked = collected.filter((s) => s.blocked);
console.log(
- `Stylesheets: ${collected.length} (${blocked.length} unreadable) · rules: ${rules.length} · interactive-state rules: ${interactive.length}`
+ `Stylesheets: ${css.stylesheets.length} (${blockedCount} unreadable) · rules: ${css.totalRules} · interactive-state rules: ${interactiveCount}`
);
-console.log(`States found: ${Object.entries(byState).map(([k, v]) => `${k}=${v.length}`).join(" · ") || "none"}`);
-console.log(`Breakpoints: ${breakpoints.join(", ") || "none"}`);
-if (keyframeNames.length) console.log(`@keyframes: ${keyframeNames.join(", ")}`);
-if (blocked.length) console.log(`NOTE: ${blocked.length} stylesheet(s) could not be read or fetched — hover rules from those are missing.`);
-if (matched) console.log(`Matched rules for "${args.selector}": ${matched.matchedRules.length}`);
+console.log(`States found: ${Object.entries(css.interactiveStates).map(([k, v]) => `${k}=${v.length}`).join(" · ") || "none"}`);
+console.log(`Breakpoints: ${css.breakpoints.join(", ") || "none"}`);
+if (css.keyframeNames.length) console.log(`@keyframes: ${css.keyframeNames.join(", ")}`);
+if (blockedCount) console.log(`NOTE: ${blockedCount} stylesheet(s) could not be read or fetched — hover rules from those are missing.`);
+if (css.matched) console.log(`Matched rules for "${args.selector}": ${css.matched.matchedRules.length}`);
diff --git a/scripts/extract/page.mjs b/scripts/extract/page.mjs
new file mode 100644
index 0000000..2a3c0ba
--- /dev/null
+++ b/scripts/extract/page.mjs
@@ -0,0 +1,208 @@
+#!/usr/bin/env node
+// ONE-SHOT page recon: everything Phase 1 + the default-state part of Phase 3a
+// need, from THREE page loads total (one per viewport, all concurrent).
+//
+// From those three live pages this produces:
+// docs/research/<host>/tokens.json design tokens (pc)
+// docs/research/<host>/css.json real CSS rules/states (pc)
+// docs/research/<host>/assets.json asset inventory + downloads to public/
+// docs/research/<host>/responsive.json per-section signatures @ all 3 viewports
+// docs/research/<host>/sections/<name>.json full computed-style walk per section (pc)
+// docs/design-references/<host>/page-{pc,ipad,phone}.png full-page shots
+// docs/design-references/<host>/<name>-{pc,ipad,phone}.png per-section shots
+//
+// Replaces running tokens.mjs + css.mjs + assets.mjs + responsive.mjs +
+// screenshot.mjs + a batched section.mjs one after another (~15 page loads).
+// Every measurement also comes from the SAME page state, so numbers, walks and
+// screenshots can never disagree about what the page looked like.
+//
+// Usage:
+// node scripts/extract/page.mjs <url>
+// [--selector "css" --name x ...] explicit sections (skips auto-detect)
+// [--depth 5] [--no-download] [--no-shots] [--no-section-shots]
+// [--no-site-files] skip tokens.json/css.json (they're
+// site-wide — only the first page needs them)
+import { mkdirSync } from "node:fs";
+import {
+ VIEWPORTS,
+ openPage,
+ closeBrowser,
+ gotoAndSettle,
+ autoScroll,
+ freezePage,
+ hostOf,
+ writeJson,
+ parseArgs,
+ toList,
+} from "../lib.mjs";
+import {
+ collectTokens,
+ collectCss,
+ collectAssets,
+ downloadAssets,
+ detectSections,
+ measureSections,
+ summarizeResponsive,
+ walkSections,
+ nameFromSelector,
+} from "./collectors.mjs";
+
+const t0 = Date.now();
+const args = parseArgs(process.argv.slice(2));
+const url = args._[0];
+if (!url) {
+ console.error('Usage: node scripts/extract/page.mjs <url> [--selector "css" --name x ...] [--depth 5] [--no-download] [--no-shots] [--no-site-files]');
+ process.exit(1);
+}
+const host = hostOf(url);
+const depth = Number(args.depth ?? 5);
+const explicit = toList(args.selector);
+const explicitNames = toList(args.name);
+const doDownload = !args["no-download"];
+const doShots = !args["no-shots"];
+const doSectionShots = doShots && !args["no-section-shots"];
+const doSiteFiles = !args["no-site-files"]; // tokens.json + css.json are site-wide — skip on later pages
+const shotDir = `docs/design-references/${host}`;
+const pageSlug = new URL(url).pathname.replace(/\/+$/, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "") || "page";
+
+// ── 1. Load all three viewports concurrently (the only page loads) ──────────
+const loaded = Object.fromEntries(
+ await Promise.all(
+ ["pc", "ipad", "phone"].map(async (vp) => {
+ const { page, close } = await openPage(VIEWPORTS[vp]);
+ await gotoAndSettle(page, url);
+ await autoScroll(page, { force: true }); // full-page shots need lazy content everywhere
+ return [vp, { page, close }];
+ })
+ )
+);
+const pc = loaded.pc.page;
+console.error(` ✓ loaded @ pc/ipad/phone in ${((Date.now() - t0) / 1000).toFixed(1)}s`);
+
+// ── 2. Sections: explicit or auto-detected on the desktop layout ────────────
+let sections;
+if (explicit.length) {
+ sections = explicit.map((selector, i) => ({ selector, name: explicitNames[i] || nameFromSelector(selector, i) }));
+} else {
+ const detected = await detectSections(pc);
+ const used = new Set();
+ sections = detected.map((s, i) => {
+ let name = nameFromSelector(s.selector, i);
+ while (used.has(name)) name += "-2";
+ used.add(name);
+ return { selector: s.selector, name };
+ });
+}
+
+// ── 3. Measure everything (order matters: measure BEFORE freeze/screenshots) ─
+const selectors = sections.map((s) => s.selector);
+const [signatures, walks, tokens, css, assetsFound] = await Promise.all([
+ // signatures at all three viewports — one evaluate per page
+ (async () => {
+ const out = {};
+ await Promise.all(
+ Object.entries(loaded).map(async ([vp, { page }]) => {
+ out[vp] = await measureSections(page, selectors);
+ })
+ );
+ return out;
+ })(),
+ walkSections(pc, selectors, { depth }),
+ doSiteFiles ? collectTokens(pc) : null,
+ doSiteFiles ? collectCss(pc) : null,
+ collectAssets(pc),
+]);
+
+// ── 4. Write research files ─────────────────────────────────────────────────
+const meta = { url, generatedAt: new Date().toISOString() };
+if (tokens) writeJson(`docs/research/${host}/tokens.json`, { ...meta, ...tokens });
+if (css) {
+ const { interactiveCount, blockedCount, ...cssOut } = css;
+ writeJson(`docs/research/${host}/css.json`, { ...meta, ...cssOut });
+}
+writeJson(`docs/research/${host}/responsive.json`, {
+ ...meta,
+ viewports: { phone: 390, ipad: 768, pc: 1440 },
+ sections: sections.map((s) => ({
+ selector: s.selector,
+ name: s.name,
+ phone: signatures.phone[s.selector],
+ ipad: signatures.ipad[s.selector],
+ pc: signatures.pc[s.selector],
+ summary: summarizeResponsive(signatures, s.selector),
+ })),
+});
+for (const s of sections) {
+ writeJson(`docs/research/${host}/sections/${s.name}.json`, {
+ ...meta,
+ viewport: "pc",
+ selector: s.selector,
+ tree: walks[s.selector],
+ });
+}
+
+// ── 5. Downloads + screenshots overlap (network vs browser work) ────────────
+const jobs = [];
+
+if (doDownload) {
+ jobs.push(
+ downloadAssets(assetsFound, { pool: 8 }).then((manifest) => {
+ writeJson(`docs/research/${host}/assets.json`, { ...meta, ...assetsFound, downloads: manifest });
+ const ok = manifest.filter((m) => m.ok).length;
+ const cached = manifest.filter((m) => m.cached).length;
+ const fail = manifest.filter((m) => !m.ok).length;
+ console.error(` ✓ assets: ${ok} ok (${cached} already on disk), ${fail} failed`);
+ })
+ );
+} else {
+ writeJson(`docs/research/${host}/assets.json`, { ...meta, ...assetsFound, downloads: [] });
+}
+
+if (doShots) {
+ mkdirSync(shotDir, { recursive: true });
+ jobs.push(
+ ...Object.entries(loaded).map(async ([vp, { page }]) => {
+ await freezePage(page); // deterministic pixels — safe now, measuring is done
+ await page.screenshot({ path: `${shotDir}/${pageSlug}-${vp}.png`, fullPage: true });
+ if (doSectionShots) {
+ for (const s of sections) {
+ const loc = page.locator(s.selector).first();
+ try {
+ await loc.scrollIntoViewIfNeeded({ timeout: 3000 });
+ await loc.screenshot({ path: `${shotDir}/${s.name}-${vp}.png`, timeout: 5000 });
+ } catch {
+ console.error(` ! section shot failed: ${s.name} @ ${vp}`);
+ }
+ }
+ }
+ console.error(` ✓ screenshots @ ${vp}`);
+ })
+ );
+}
+
+await Promise.all(jobs);
+await Promise.all(Object.values(loaded).map((l) => l.close()));
+await closeBrowser();
+
+// ── 6. Summary the foreman can read at a glance ─────────────────────────────
+console.log(
+ JSON.stringify(
+ {
+ url,
+ seconds: Number(((Date.now() - t0) / 1000).toFixed(1)),
+ sections: sections.map((s) => ({
+ name: s.name,
+ selector: s.selector,
+ pcHeight: signatures.pc[s.selector]?.height ?? null,
+ responsive: summarizeResponsive(signatures, s.selector).changes[0],
+ })),
+ siteFiles: doSiteFiles ? ["tokens.json", "css.json"] : [],
+ files: {
+ research: `docs/research/${host}/`,
+ screenshots: doShots ? shotDir : null,
+ },
+ },
+ null,
+ 2
+ )
+);
diff --git a/scripts/extract/responsive.mjs b/scripts/extract/responsive.mjs
index 92b8542..b23fcc1 100644
--- a/scripts/extract/responsive.mjs
+++ b/scripts/extract/responsive.mjs
@@ -2,12 +2,13 @@
// Responsive check: load the page at phone (390) / iPad (768) / PC (1440) and
// record each section's layout signature at every width, plus a human-readable
// summary of what changes. Spec files fill their Responsive section from this —
-// never from guessing.
+// never from guessing. Detection/measurement live in collectors.mjs.
//
// Usage: node scripts/extract/responsive.mjs <url> [--selector "css"]
// (no --selector = auto-detect top-level sections: header, main children, footer)
// Output: docs/research/<host>/responsive.json
import { VIEWPORTS, openPage, closeBrowser, gotoAndSettle, autoScroll, hostOf, writeJson, parseArgs } from "../lib.mjs";
+import { detectSections, measureSections, summarizeResponsive } from "./collectors.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
@@ -16,164 +17,6 @@ if (!url) {
process.exit(1);
}
-// Layout signature of a section at the current viewport — runs in the page.
-const SIGNATURE = `(function (selector) {
- const el = document.querySelector(selector);
- if (!el) return { error: "not found" };
- const cs = getComputedStyle(el);
- const rect = el.getBoundingClientRect();
- const kids = [...el.children];
- const visibleKids = kids.filter((k) => {
- const kcs = getComputedStyle(k);
- return kcs.display !== "none" && kcs.visibility !== "hidden";
- });
- // Find the container with the most visible children — that's the "grid" of the
- // section regardless of technique (grid, flex-wrap, floats, width %).
- const candidates = [el, ...el.querySelectorAll("*")].slice(0, 300);
- let gridEl = el, maxKids = 0;
- for (const c of candidates) {
- const vis = [...c.children].filter((k) => {
- const r = k.getBoundingClientRect();
- return r.width > 40 && r.height > 40 && getComputedStyle(k).display !== "none";
- });
- if (vis.length > maxKids) { maxKids = vis.length; gridEl = c; }
- }
- // Real column count = children sharing the first row (same top, ±10px)
- const gkids = [...gridEl.children].filter((k) => {
- const r = k.getBoundingClientRect();
- return r.width > 40 && r.height > 40 && getComputedStyle(k).display !== "none";
- });
- let realColumns = null;
- if (gkids.length >= 2) {
- const firstTop = gkids[0].getBoundingClientRect().top;
- realColumns = gkids.filter((k) => Math.abs(k.getBoundingClientRect().top - firstTop) < 10).length;
- }
- const gcs = getComputedStyle(gridEl);
- const h = el.querySelector("h1,h2,h3");
- return {
- width: Math.round(rect.width),
- height: Math.round(rect.height),
- display: cs.display,
- flexDirection: cs.flexDirection,
- innerLayout: {
- display: gcs.display,
- flexDirection: gcs.flexDirection,
- flexWrap: gcs.flexWrap,
- gridColumns: gcs.gridTemplateColumns === "none" ? null : gcs.gridTemplateColumns.split(" ").length,
- realColumns,
- itemCount: gkids.length,
- gap: gcs.gap,
- },
- childCount: kids.length,
- visibleChildCount: visibleKids.length,
- hiddenChildren: kids.length - visibleKids.length,
- headingFontSize: h ? getComputedStyle(h).fontSize : null,
- paddingX: cs.paddingLeft + " / " + cs.paddingRight,
- fontSize: cs.fontSize,
- };
-})`;
-
-// Auto-detect the page's top-level sections — runs in the page.
-// Walk the page top-down collecting real sections. Semantic elements
-// (section/header/footer/nav/main/aside/article) are leaves; generic wrapper
-// divs (body > #wrapper > #main > section...) get expanded through.
-const DETECT = `(function () {
- const LEAF = new Set(["SECTION", "HEADER", "FOOTER", "NAV", "ASIDE", "ARTICLE", "MAIN"]);
- const MIN_H = 40; // site headers are often ~44px on phones
- const found = [];
- // Produce a selector that provably resolves back to this exact element.
- // Class-based selectors are preferred (readable in specs), but Tailwind
- // classes are rarely unique, so there's a guaranteed positional fallback.
- function selectorFor(el) {
- const tag = el.tagName.toLowerCase();
- const ok = (s) => {
- try {
- return document.querySelector(s) === el ? s : null;
- } catch {
- return null;
- }
- };
- if (el.id) {
- const s = ok(tag + "#" + CSS.escape(el.id));
- if (s) return s;
- }
- const classes = (el.className?.toString() || "").split(/\s+/).filter(Boolean).map((c) => CSS.escape(c));
- for (const n of [1, 2, 3]) {
- if (classes.length < n) break;
- const s = ok(tag + "." + classes.slice(0, n).join("."));
- if (s) return s;
- }
- // Guaranteed fallback: absolute nth-child path from <body>
- const parts = [];
- let cur = el;
- while (cur && cur !== document.body && cur.parentElement) {
- parts.unshift(":nth-child(" + ([...cur.parentElement.children].indexOf(cur) + 1) + ")");
- cur = cur.parentElement;
- }
- return "body > " + parts.join(" > ");
- }
- // A real section is roughly viewport-scale. Anything much taller is a
- // container holding several sections, so keep descending through it.
- const MAX_SECTION_H = Math.max(1400, window.innerHeight * 1.6);
- function walk(el, depth) {
- if (depth > 7 || found.length > 25) return;
- for (const child of el.children) {
- if (["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "svg", "SVG"].includes(child.tagName)) continue;
- const r = child.getBoundingClientRect();
- if (r.height < MIN_H) continue;
- const bigKids = [...child.children].filter((k) => k.getBoundingClientRect().height >= MIN_H);
- // A repeated collection (a card grid, a tile row) is ONE section — it
- // becomes one component fed by a data array, never N sections. Requires
- // same tag AND similar heights: three <div>s of 852/2161/974px is a page
- // scaffold, not a grid, and must still be descended into.
- const kidHeights = bigKids.map((k) => k.getBoundingClientRect().height);
- const minKid = Math.min(...kidHeights);
- const maxKid = Math.max(...kidHeights);
- const isCollection =
- bigKids.length >= 3 &&
- new Set(bigKids.map((k) => k.tagName)).size === 1 &&
- maxKid - minKid <= maxKid * 0.25 && // siblings are roughly equal
- r.height <= MAX_SECTION_H;
- // The rule: a section is the first element small enough to BE a section.
- // Anything taller is a container to descend through. Without this, sites
- // with no semantic tags recurse all the way down to individual paragraphs.
- if (!isCollection && bigKids.length >= 1) {
- if (r.height > MAX_SECTION_H) {
- walk(child, depth + 1);
- continue;
- }
- // A pure wrapper adds nothing of its own — unwrap it even at section
- // scale (common in React output: div > div > main > …).
- if (!LEAF.has(child.tagName) && !child.id && bigKids.length === 1 && bigKids[0].getBoundingClientRect().height >= r.height * 0.92) {
- walk(child, depth + 1);
- continue;
- }
- // A semantic element wrapping only other semantic sections.
- if (LEAF.has(child.tagName) && bigKids.length > 1 && bigKids.every((k) => LEAF.has(k.tagName))) {
- walk(child, depth + 1);
- continue;
- }
- }
- const sel = selectorFor(child);
- if (!found.some((f) => f.selector === sel) && document.querySelector(sel) === child) {
- found.push({ selector: sel, label: sel });
- }
- }
- }
- walk(document.body, 0);
- // Site chrome is always worth its own spec even when nested inside a wrapper
- for (const tag of ["header", "footer"]) {
- const el = document.querySelector(tag);
- if (!el || el.getBoundingClientRect().height < MIN_H) continue;
- const sel = selectorFor(el);
- if (!found.some((f) => f.selector === sel)) found.unshift({ selector: sel, label: sel });
- }
- return found;
-})`;
-
-const results = {};
-let sections = null;
-
// Detect sections at PC first — desktop is the canonical layout. At phone width
// everything stacks and grows tall, which makes containers and sections
// indistinguishable by height.
@@ -192,47 +35,22 @@ const loaded = await Promise.all(
);
const pcPage = (loaded.find((l) => l.vpName === "pc") || loaded[0]).page;
-sections = args.selector
+const sections = args.selector
? [{ selector: args.selector, label: args.selector }]
- : await pcPage.evaluate(`(${DETECT})()`);
+ : await detectSections(pcPage);
+const selectors = sections.map((s) => s.selector);
+// One evaluate per viewport measures ALL sections — not one round-trip each.
+const results = {};
await Promise.all(
loaded.map(async ({ vpName, page, close }) => {
- const measured = {};
- for (const s of sections) {
- measured[s.selector] = await page.evaluate(`(${SIGNATURE})(${JSON.stringify(s.selector)})`);
- }
- results[vpName] = measured;
+ results[vpName] = await measureSections(page, selectors);
await close();
console.error(` ✓ measured ${sections.length} sections @ ${vpName} (${VIEWPORTS[vpName].width}px)`);
})
);
await closeBrowser();
-// Build human-readable change summaries per section
-const summarize = (sel) => {
- const p = results.phone[sel] || {};
- const t = results.ipad[sel] || {};
- const d = results.pc[sel] || {};
- const changes = [];
- const cmp = (label, a, b, aName, bName) => {
- if (a != null && b != null && a !== b) changes.push(`${label}: ${b} (${bName}) → ${a} (${aName})`);
- };
- cmp("columns", p.innerLayout?.realColumns, d.innerLayout?.realColumns, "phone", "pc");
- cmp("grid-template columns", p.innerLayout?.gridColumns, d.innerLayout?.gridColumns, "phone", "pc");
- cmp("flex direction", p.innerLayout?.flexDirection, d.innerLayout?.flexDirection, "phone", "pc");
- cmp("heading size", p.headingFontSize, d.headingFontSize, "phone", "pc");
- cmp("visible children", p.visibleChildCount, d.visibleChildCount, "phone", "pc");
- cmp("hidden children", p.hiddenChildren, d.hiddenChildren, "phone", "pc");
- cmp("padding-x", p.paddingX, d.paddingX, "phone", "pc");
- // does tablet match desktop or phone?
- const ipadLike =
- JSON.stringify(t.innerLayout) === JSON.stringify(d.innerLayout) ? "ipad matches pc layout"
- : JSON.stringify(t.innerLayout) === JSON.stringify(p.innerLayout) ? "ipad matches phone layout"
- : "ipad has its own intermediate layout";
- return { changes: changes.length ? changes : ["no layout change across viewports"], ipadBehavior: ipadLike };
-};
-
const out = {
url,
generatedAt: new Date().toISOString(),
@@ -242,7 +60,7 @@ const out = {
phone: results.phone[s.selector],
ipad: results.ipad[s.selector],
pc: results.pc[s.selector],
- summary: summarize(s.selector),
+ summary: summarizeResponsive(results, s.selector),
})),
};
writeJson(`docs/research/${hostOf(url)}/responsive.json`, out);
diff --git a/scripts/extract/screenshot.mjs b/scripts/extract/screenshot.mjs
index 8187bb3..731cf10 100644
--- a/scripts/extract/screenshot.mjs
+++ b/scripts/extract/screenshot.mjs
@@ -1,9 +1,12 @@
#!/usr/bin/env node
-// Screenshot a page (or one section) at phone/iPad/PC viewports.
-// All viewports render concurrently on one browser.
+// Screenshot a page (or one or more sections) at phone/iPad/PC viewports.
+// All viewports render concurrently on one browser, and each viewport loads
+// the page ONCE — every requested section is shot from that single load.
// Usage:
-// node scripts/extract/screenshot.mjs <url> [--name hero] [--selector "css"]
+// node scripts/extract/screenshot.mjs <url> [--selector "css" [--name hero]]...
// [--viewports phone,ipad,pc] [--no-freeze] [--out-dir docs/design-references]
+// --selector/--name are repeatable and pair up in order; a missing --name
+// defaults to slugify(selector). No --selector = full-page shot per viewport.
// Output: <out-dir>/<host>/<name>-<viewport>.png
import { mkdirSync } from "node:fs";
import {
@@ -16,16 +19,20 @@ import {
hostOf,
slugify,
parseArgs,
+ toList,
} from "../lib.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
if (!url) {
- console.error("Usage: node scripts/extract/screenshot.mjs <url> [--selector css] [--name x] [--viewports phone,ipad,pc]");
+ console.error("Usage: node scripts/extract/screenshot.mjs <url> [--selector css --name x]... [--viewports phone,ipad,pc]");
process.exit(1);
}
const wanted = String(args.viewports || "phone,ipad,pc").split(",").filter((v) => VIEWPORTS[v]);
-const name = args.name || (args.selector ? slugify(args.selector) : "page");
+const selectors = toList(args.selector);
+const names = toList(args.name);
+// (selector, name) pairs in argv order — unnamed selectors fall back to their slug.
+const shots = selectors.map((selector, i) => ({ selector, name: names[i] || slugify(selector) }));
const outDir = `${args["out-dir"] || "docs/design-references"}/${hostOf(url)}`;
mkdirSync(outDir, { recursive: true });
@@ -33,17 +40,28 @@ await forEachViewport(wanted, async (page, vp) => {
await gotoAndSettle(page, url);
// A full-page shot must include lazy content, so force the scroll pass here
// even when the page shows no lazy-loading signals.
- await autoScroll(page, { force: !args.selector });
+ await autoScroll(page, { force: shots.length === 0 });
if (!args["no-freeze"]) await freezePage(page);
- const path = `${outDir}/${name}-${vp}.png`;
- if (args.selector) {
- const loc = page.locator(args.selector).first();
- await loc.scrollIntoViewIfNeeded();
- await loc.screenshot({ path });
- } else {
+ if (shots.length === 0) {
+ const path = `${outDir}/${names[0] || "page"}-${vp}.png`;
await page.screenshot({ path, fullPage: true });
+ console.log(` ✓ ${path}`);
+ return;
+ }
+ for (const { selector, name } of shots) {
+ const path = `${outDir}/${name}-${vp}.png`;
+ try {
+ const loc = page.locator(selector).first();
+ // Short timeouts: a bad selector should cost 3s and a warning, not
+ // Playwright's default 30s before the rest of the sections get shot.
+ await loc.scrollIntoViewIfNeeded({ timeout: 3000 });
+ await loc.screenshot({ path, timeout: 5000 });
+ console.log(` ✓ ${path}`);
+ } catch (err) {
+ // One bad selector must not kill the other sections' shots.
+ console.warn(` ⚠ ${vp}: selector "${selector}" failed — ${String(err.message || err).split("\n")[0]}`);
+ }
}
- console.log(` ✓ ${path}`);
});
await closeBrowser();
diff --git a/scripts/extract/section.mjs b/scripts/extract/section.mjs
index fe60dac..1371112 100644
--- a/scripts/extract/section.mjs
+++ b/scripts/extract/section.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Deep-extract one or more sections: full computed-style DOM walk + verbatim
// text + assets. Optionally capture a second state (scroll/click/hover) and
-// diff the two.
+// diff the two. The walker and differ live in collectors.mjs.
//
// Usage:
// node scripts/extract/section.mjs <url> --selector "header" [--name header]
@@ -28,6 +28,7 @@ import {
parseArgs,
toList,
} from "../lib.mjs";
+import { walkSections, diffNode } from "./collectors.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
@@ -46,134 +47,21 @@ const { page, close } = await openPage(viewport);
await gotoAndSettle(page, url);
await autoScroll(page);
-// The walker runs in the page. Captures every relevant computed property per element.
-const WALKER = `(function (selector, maxDepth) {
- const el = document.querySelector(selector);
- if (!el) return { error: "Element not found: " + selector };
- const PROPS = [
- "fontSize","fontWeight","fontFamily","lineHeight","letterSpacing","color","textAlign",
- "textTransform","textDecoration","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
- "paddingTop","paddingRight","paddingBottom","paddingLeft",
- "marginTop","marginRight","marginBottom","marginLeft",
- "width","height","maxWidth","minWidth","maxHeight","minHeight",
- "display","flexDirection","flexWrap","justifyContent","alignItems","gap","rowGap","columnGap",
- "gridTemplateColumns","gridTemplateRows","gridAutoFlow",
- "borderRadius","borderTopWidth","borderBottomWidth","borderLeftWidth","borderRightWidth","borderColor","borderStyle",
- "boxShadow","overflow","overflowX","overflowY",
- "position","top","right","bottom","left","zIndex","inset",
- "opacity","transform","transition","animation","cursor","pointerEvents","visibility",
- "objectFit","objectPosition","mixBlendMode","filter","backdropFilter",
- "whiteSpace","textOverflow","aspectRatio","order","flexGrow","flexShrink","flexBasis",
- ];
- const SKIP = new Set(["none","normal","auto","0px","rgba(0, 0, 0, 0)","visible","static","initial",""]);
- function styles(element) {
- const cs = getComputedStyle(element);
- const out = {};
- for (const p of PROPS) {
- const v = cs[p];
- if (v !== undefined && !SKIP.has(v)) out[p] = v;
- }
- return out;
- }
- function directText(element) {
- return [...element.childNodes]
- .filter((n) => n.nodeType === 3)
- .map((n) => n.textContent.trim())
- .filter(Boolean)
- .join(" ")
- .slice(0, 500) || null;
- }
- // ::before / ::after carry real visuals (underline bars, icon glyphs, overlays)
- // that getComputedStyle on the element itself never reveals. Miss these and the
- // clone silently loses decorations.
- const PSEUDO_PROPS = [
- "content","width","height","backgroundColor","backgroundImage","backgroundSize","borderRadius",
- "position","top","right","bottom","left","transform","opacity","display",
- "borderBottomWidth","borderTopWidth","borderLeftWidth","borderRightWidth","borderColor","borderStyle",
- "margin","padding","zIndex","boxShadow","transition","mixBlendMode","filter",
- ];
- // Typography only matters when the pseudo actually renders text (icon fonts, glyphs)
- const PSEUDO_TEXT_PROPS = ["fontFamily","fontSize","fontWeight","color","lineHeight","letterSpacing","textAlign"];
- function pseudos(element) {
- const out = {};
- for (const pe of ["::before", "::after"]) {
- const cs = getComputedStyle(element, pe);
- if (!cs.content || cs.content === "none") continue;
- const hasText = cs.content !== '""' && cs.content !== "''" && !cs.content.startsWith("url(");
- const styles = { content: cs.content };
- for (const p of [...PSEUDO_PROPS, ...(hasText ? PSEUDO_TEXT_PROPS : [])]) {
- const v = cs[p];
- if (v !== undefined && !SKIP.has(v)) styles[p] = v;
- }
- // A pseudo with no box and no text renders nothing — skip it
- if (Object.keys(styles).length > 1) out[pe] = styles;
- }
- return Object.keys(out).length ? out : undefined;
- }
- function walk(element, d) {
- if (d > maxDepth) return { truncated: true, tag: element.tagName.toLowerCase() };
- const kids = [...element.children];
- const rect = element.getBoundingClientRect();
- return {
- tag: element.tagName.toLowerCase(),
- classes: (element.className?.toString() || "").split(" ").filter(Boolean).slice(0, 6).join(" ") || null,
- text: directText(element),
- href: element.tagName === "A" ? element.getAttribute("href") : undefined,
- ariaLabel: element.getAttribute("aria-label") || undefined,
- img: element.tagName === "IMG"
- ? { src: element.currentSrc || element.src, alt: element.alt, w: element.naturalWidth, h: element.naturalHeight }
- : undefined,
- isSvg: element.tagName.toLowerCase() === "svg" || undefined,
- rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
- styles: styles(element),
- pseudo: pseudos(element),
- childCount: kids.length,
- children: kids.slice(0, 25).map((c) => walk(c, d + 1)),
- };
- }
- return walk(el, 0);
-})`;
+const meta = { url, viewport: args.viewport || "pc", generatedAt: new Date().toISOString() };
-async function capture(selector) {
+// Bring every target into view first (in-view rendering settles), then walk
+// them ALL in one evaluate — N sections cost one round-trip, not N.
+for (const { selector } of targets) {
await page.locator(selector).first().scrollIntoViewIfNeeded().catch(() => {});
- return page.evaluate(`(${WALKER})(${JSON.stringify(selector)}, ${depth})`);
}
-
-// Style deltas between two captures of the same subtree, element by element.
-// Both real styles and pseudo-element styles count: a hover effect built from a
-// ::before overlay changes nothing on the element itself.
-function diffNode(a, b, path, out) {
- if (!a || !b || a.error || b.error) return;
- const keys = new Set([...Object.keys(a.styles || {}), ...Object.keys(b.styles || {})]);
- for (const k of keys) {
- if ((a.styles?.[k] || null) !== (b.styles?.[k] || null)) {
- out.push({ path, prop: k, before: a.styles?.[k] ?? "(unset)", after: b.styles?.[k] ?? "(unset)" });
- }
- }
- for (const pe of ["::before", "::after"]) {
- const pa = a.pseudo?.[pe] || {};
- const pb = b.pseudo?.[pe] || {};
- const pkeys = new Set([...Object.keys(pa), ...Object.keys(pb)]);
- for (const k of pkeys) {
- if ((pa[k] || null) !== (pb[k] || null)) {
- out.push({ path: path + pe, prop: k, before: pa[k] ?? "(unset)", after: pb[k] ?? "(unset)" });
- }
- }
- }
- (a.children || []).forEach((c, i) => diffNode(c, b.children?.[i], `${path} > ${c.tag}[${i}]`, out));
-}
-
-const meta = { url, viewport: args.viewport || "pc", generatedAt: new Date().toISOString() };
-const stateA = {};
+const stateA = await walkSections(page, selectors, { depth });
for (const { selector } of targets) {
- const tree = await capture(selector);
- if (tree.error) {
- console.error(tree.error);
+ if (stateA[selector].error) {
+ console.error(stateA[selector].error);
await close();
await closeBrowser();
process.exit(1);
}
- stateA[selector] = tree;
}
if (args.state) {
@@ -184,22 +72,23 @@ if (args.state) {
else if (kind === "click") await page.locator(target).first().click({ timeout: 5000 }).catch((e) => console.error("click failed:", e.message));
else if (kind === "hover") await page.locator(target).first().hover({ timeout: 5000 }).catch((e) => console.error("hover failed:", e.message));
- // Wait exactly as long as this section's slowest transition, not a flat guess.
- // A 2.5s overlay fade used to get captured mid-flight and recorded as final.
+ // Wait exactly as long as the slowest transition among the targets, not a
+ // flat guess. A 2.5s overlay fade used to get captured mid-flight and
+ // recorded as final.
const settle = Math.max(...(await Promise.all(targets.map((t) => transitionMs(page, t.selector)))));
await page.waitForTimeout(settle);
+ const stateB = await walkSections(page, selectors, { depth });
for (const { selector, name } of targets) {
- const stateB = await capture(selector);
const diff = [];
- diffNode(stateA[selector], stateB, stateA[selector].tag, diff);
+ diffNode(stateA[selector], stateB[selector], stateA[selector].tag, diff);
writeJson(`docs/research/${hostOf(url)}/sections/${name}.json`, {
...meta,
selector,
trigger: args.state,
settleMs: settle,
stateA: stateA[selector],
- stateB,
+ stateB: stateB[selector],
diff,
});
console.log(`${name}: ${diff.length} properties changed after "${args.state}" (waited ${settle}ms)`);
diff --git a/scripts/extract/tokens.mjs b/scripts/extract/tokens.mjs
index 1a9fec0..1fbca2f 100644
--- a/scripts/extract/tokens.mjs
+++ b/scripts/extract/tokens.mjs
@@ -3,7 +3,9 @@
// radii/shadows, and global scroll behaviors (Lenis, scroll-snap, etc).
// Usage: node scripts/extract/tokens.mjs <url>
// Output: docs/research/<host>/tokens.json
+// (page.mjs produces the same file as part of its one-shot recon.)
import { launchPage, gotoAndSettle, autoScroll, hostOf, writeJson, parseArgs } from "../lib.mjs";
+import { collectTokens } from "./collectors.mjs";
const args = parseArgs(process.argv.slice(2));
const url = args._[0];
@@ -15,126 +17,7 @@ if (!url) {
const { browser, page } = await launchPage();
await gotoAndSettle(page, url);
await autoScroll(page);
-
-const tokens = await page.evaluate(() => {
- const els = [...document.querySelectorAll("body *")].slice(0, 3000);
- const count = (map, key) => key && map.set(key, (map.get(key) || 0) + 1);
- const colors = new Map();
- const bgs = new Map();
- const families = new Map();
- const radii = new Map();
- const shadows = new Map();
- const fontSizes = new Map();
-
- for (const el of els) {
- const cs = getComputedStyle(el);
- count(colors, cs.color);
- if (cs.backgroundColor !== "rgba(0, 0, 0, 0)") count(bgs, cs.backgroundColor);
- count(families, cs.fontFamily);
- if (cs.borderRadius !== "0px") count(radii, cs.borderRadius);
- if (cs.boxShadow !== "none") count(shadows, cs.boxShadow);
- if (el.textContent?.trim()) count(fontSizes, `${cs.fontSize}/${cs.fontWeight}/${cs.lineHeight}`);
- }
- const top = (map, n = 20) =>
- [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([value, uses]) => ({ value, uses }));
-
- // Typography of key elements
- const typo = {};
- for (const sel of ["h1", "h2", "h3", "h4", "p", "a", "button", "body"]) {
- const el = document.querySelector(sel);
- if (!el) continue;
- const cs = getComputedStyle(el);
- typo[sel] = {
- fontFamily: cs.fontFamily,
- fontSize: cs.fontSize,
- fontWeight: cs.fontWeight,
- lineHeight: cs.lineHeight,
- letterSpacing: cs.letterSpacing,
- color: cs.color,
- textTransform: cs.textTransform,
- };
- }
-
- // :root custom properties + @keyframes bodies (same-origin stylesheets only).
- // Capturing keyframes matters: computed styles tell you `animation: slide-up-fade 1s`
- // but not what slide-up-fade DOES. Without the rule body a builder can only guess.
- const cssVars = {};
- const keyframes = {};
- const walkRules = (rules) => {
- for (const rule of rules) {
- // CSSKeyframesRule
- if (rule.type === 7 || rule.constructor?.name === "CSSKeyframesRule") {
- const steps = {};
- for (const kf of rule.cssRules) steps[kf.keyText] = kf.style.cssText;
- keyframes[rule.name] = steps;
- continue;
- }
- // nested groups: @media, @supports, @layer
- if (rule.cssRules) {
- try {
- walkRules(rule.cssRules);
- } catch { /* ignore */ }
- continue;
- }
- if (rule.selectorText === ":root" || rule.selectorText === "html") {
- for (const prop of rule.style) {
- if (prop.startsWith("--")) cssVars[prop] = rule.style.getPropertyValue(prop).trim();
- }
- }
- }
- };
- for (const sheet of document.styleSheets) {
- try {
- walkRules(sheet.cssRules);
- } catch {
- continue; // cross-origin sheet
- }
- }
-
- // Which animations are actually used on the page, and on how many elements
- const animationsInUse = {};
- for (const el of els) {
- const cs = getComputedStyle(el);
- if (cs.animationName && cs.animationName !== "none") {
- const key = `${cs.animationName} | ${cs.animationDuration} | ${cs.animationTimingFunction} | ${cs.animationIterationCount} | delay ${cs.animationDelay}`;
- animationsInUse[key] = (animationsInUse[key] || 0) + 1;
- }
- }
-
- // Font sources
- const fontLinks = [...document.querySelectorAll('link[rel="stylesheet"], link[rel="preload"][as="font"]')]
- .map((l) => l.href)
- .filter((h) => /fonts\.|font|\.woff/i.test(h));
-
- // Global scroll behavior detection
- const htmlCs = getComputedStyle(document.documentElement);
- const bodyCs = getComputedStyle(document.body);
- const globalBehaviors = {
- smoothScrollLib: document.querySelector(".lenis, [data-lenis], .locomotive-scroll, [data-scroll-container]")
- ? "detected (Lenis or Locomotive — inspect manually)"
- : null,
- scrollBehavior: htmlCs.scrollBehavior,
- scrollSnapType: htmlCs.scrollSnapType !== "none" ? htmlCs.scrollSnapType : bodyCs.scrollSnapType !== "none" ? bodyCs.scrollSnapType : null,
- bodyBackground: bodyCs.backgroundColor,
- hasFixedHeader: !!document.querySelector("header, nav") &&
- ["fixed", "sticky"].includes(getComputedStyle(document.querySelector("header, nav")).position),
- };
-
- return {
- colors: top(colors),
- backgrounds: top(bgs),
- fontFamilies: top(families, 10),
- typography: typo,
- fontSizeCombos: top(fontSizes, 25),
- borderRadii: top(radii, 10),
- boxShadows: top(shadows, 10),
- cssVariables: cssVars,
- keyframes,
- animationsInUse,
- fontLinks,
- globalBehaviors,
- };
-});
+const tokens = await collectTokens(page);
await browser.close();
writeJson(`docs/research/${hostOf(url)}/tokens.json`, { url, generatedAt: new Date().toISOString(), ...tokens });
diff --git a/scripts/lib.mjs b/scripts/lib.mjs
index a328e71..7c64760 100644
--- a/scripts/lib.mjs
+++ b/scripts/lib.mjs
@@ -55,8 +55,57 @@ const CONTEXT_OPTS = {
userAgent:
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
deviceScaleFactor: 1,
+ // Service workers serve stale shells and bypass request interception — both
+ // poison extraction determinism and the response cache below.
+ serviceWorkers: "block",
};
+// ---------------------------------------------------------------------------
+// In-process response cache
+//
+// Every context has an isolated HTTP cache, so a 3-viewport run downloads every
+// image, font and script three times — and page.mjs loads the same page many
+// more. Cache static subresources once per process and replay them. GET-only,
+// static resource types only (documents and XHR always hit the network).
+// ---------------------------------------------------------------------------
+const CACHEABLE = new Set(["image", "font", "stylesheet", "script"]);
+const MAX_ENTRY = 4 * 1024 * 1024; // 4 MB per resource
+const MAX_TOTAL = 256 * 1024 * 1024; // 256 MB overall
+const _cache = new Map(); // url -> { body: Buffer, contentType: string }
+let _cacheBytes = 0;
+
+async function enableResponseCache(context) {
+ await context.route("**/*", async (route) => {
+ const req = route.request();
+ if (req.method() !== "GET" || !CACHEABLE.has(req.resourceType())) {
+ return route.fallback();
+ }
+ const url = req.url();
+ const hit = _cache.get(url);
+ if (hit) {
+ return route.fulfill({ status: 200, contentType: hit.contentType, body: hit.body });
+ }
+ let res;
+ try {
+ res = await route.fetch();
+ } catch {
+ return route.fallback(); // fetch aborted (navigation) — let the browser handle it
+ }
+ if (res.status() === 200) {
+ try {
+ const body = await res.body();
+ if (body.length <= MAX_ENTRY && _cacheBytes + body.length <= MAX_TOTAL) {
+ _cache.set(url, { body, contentType: res.headers()["content-type"] || "" });
+ _cacheBytes += body.length;
+ }
+ } catch {
+ /* body unavailable — just pass the response through */
+ }
+ }
+ return route.fulfill({ response: res });
+ });
+}
+
export function getBrowser() {
if (!_browserPromise) _browserPromise = chromium.launch({ headless: true });
return _browserPromise;
@@ -89,10 +138,12 @@ async function instrumentLazySignals(context) {
}
// Open a page on the shared browser. `close()` disposes only this context.
-export async function openPage(viewport = VIEWPORTS.pc) {
+// `cache: false` opts out of response caching (e.g. when probing live-changing pages).
+export async function openPage(viewport = VIEWPORTS.pc, { cache = true } = {}) {
const browser = await getBrowser();
const context = await browser.newContext({ viewport, ...CONTEXT_OPTS });
await instrumentLazySignals(context);
+ if (cache) await enableResponseCache(context);
const page = await context.newPage();
return { page, context, close: () => context.close() };
}
@@ -164,12 +215,38 @@ export async function settleLayout(page, { timeout = 3000, quietMs = 150 } = {})
.catch(() => {});
}
+// Wait until every <img> currently in the DOM has finished loading (or errored).
+// This is the signal networkidle was standing in for on image-heavy pages, and
+// unlike networkidle it can't be held hostage by analytics beacons.
+async function imagesSettled(page, { timeout = 4000 } = {}) {
+ await page
+ .evaluate(
+ (timeout) =>
+ Promise.race([
+ Promise.all(
+ [...document.images]
+ .filter((img) => !img.complete)
+ .map((img) => new Promise((r) => {
+ img.addEventListener("load", r, { once: true });
+ img.addEventListener("error", r, { once: true });
+ }))
+ ),
+ new Promise((r) => setTimeout(r, timeout)),
+ ]),
+ timeout
+ )
+ .catch(() => {});
+}
+
export async function gotoAndSettle(page, url) {
await page.goto(url, { waitUntil: "load", timeout: 60000 });
- // Network quiet + fonts ready + stable height are the three things the old
- // blanket 1500ms was guessing at. On a fast page this returns almost instantly.
- await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
+ // Four precise signals instead of one long networkidle gamble. Sites with
+ // analytics/websocket chatter never reach networkidle and used to pay the
+ // full 15s on EVERY load — the cap is now 4s and the other three signals
+ // (fonts ready, images decoded, stable height) carry the real guarantee.
+ await page.waitForLoadState("networkidle", { timeout: 4000 }).catch(() => {});
await page.evaluate(() => document.fonts?.ready).catch(() => {});
+ await imagesSettled(page);
await settleLayout(page);
}
@@ -237,12 +314,25 @@ export async function transitionMs(page, selector, { min = 150, max = 4000 } = {
return Math.min(max, Math.max(min, Math.round(ms)));
}
-// Kill animations/transitions/videos so screenshots are deterministic (for QA diffs).
+// Park animations/transitions/videos so screenshots are deterministic (for QA diffs).
+// Animations jump to their END state, not `animation: none`: killing them outright
+// reverts `fill-mode: forwards` entry animations to their pre-animation frame, so
+// scroll-revealed content screenshots at opacity 0 and QA penalizes a clone that
+// is actually correct. A near-zero duration with iteration-count 1 lands every
+// animation (including infinite spinners) on its final keyframe deterministically.
export async function freezePage(page) {
await page.addStyleTag({
content:
- "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",
+ "*,*::before,*::after{" +
+ "animation-delay:-0.0001s!important;animation-duration:0.0001s!important;" +
+ "animation-iteration-count:1!important;" +
+ "transition-delay:0s!important;transition-duration:0s!important;" +
+ "caret-color:transparent!important;scroll-behavior:auto!important}",
});
+ // Two frames so the jumped-to-end animation states actually paint.
+ await page
+ .evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))))
+ .catch(() => {});
// Park videos on a frame that actually has content. Seeking to 0 lands on the
// first encoded frame, which for a screen recording is often blank — that
// renders as an empty box and costs the section real diff points.
diff --git a/vid.tmp.mjs b/vid.tmp.mjs
deleted file mode 100644
index da560ce..0000000
--- a/vid.tmp.mjs
+++ /dev/null
@@ -1,18 +0,0 @@
-import { chromium } from "playwright";
-const S="/tmp/claude-1000/-home-mahan-GitHub-Custom-Skills/dff31326-4f6e-4f2f-a117-03ae7f26903f/scratchpad/vid";
-const b=await chromium.launch();
-const ctx=await b.newContext({viewport:{width:700,height:700},recordVideo:{dir:S,size:{width:700,height:700}}});
-const p=await ctx.newPage();
-await p.goto("https://uploadthing.com",{waitUntil:"load",timeout:40000});
-await p.waitForTimeout(3000);
-// isolate: pin the canvas to fill the viewport, hide everything else
-await p.evaluate(()=>{
- const c=document.querySelector("canvas");
- document.body.style.cssText="margin:0;padding:0;overflow:hidden;background:#0a0004";
- document.documentElement.style.background="#0a0004";
- for(const el of document.body.querySelectorAll("*")) if(!el.contains(c)&&el!==c) el.style.visibility="hidden";
- c.style.cssText="position:fixed;top:0;left:0;width:700px;height:700px;visibility:visible;z-index:99999";
-});
-await p.waitForTimeout(5000); // record 5s of motion
-await ctx.close(); await b.close();
-console.log("recorded");