Explainer videos and product demos made by your AI agent. Free and open source: a local voice (Kokoro), word timing (Whisper) and a canvas renderer turn a script into a narrated MP4.
JavaScript ai-agentsanimationcanvasclaude-codecodexexplainer-videoffmpegjavascriptkokoroproduct-demotext-to-speechvideo-generationwhisper
Capture a live website for product demos (#9)
Vincent Schmalbach946b871630c7
diff --git a/AGENTS.md b/AGENTS.mdindex b8b0bb0..ffe80ac 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -347,6 +347,31 @@ A mouse pointer clicks through the screens and types into the fields, and thecamera zooms in on what the voice talks about. `examples/unspar-demo` is acomplete one.+**Capture the live site first.**++```bash+node bin/explainroo.js capture videos/<name> https://example.com --mobile+```++`capture` opens the page in a fresh browser, without cookies or logins, and+saves what a demo needs in `assets/capture/<hostname>/`:++- `page.png` (the first screen) and `full.png` (the whole page, up to 8000+ pixels tall), at twice the pixel density, so they stay sharp when the+ camera zooms in. `--mobile` adds `mobile.png` and `mobile-full.png`.+- `capture.json` with the colors, fonts, logo candidates and the page's+ wording: headings, navigation, buttons and form labels. Copy the wording+ exactly. The live site is the source of truth for claims and wording.+- Up to three logo files, and the font files that come from Google Fonts, in+ the weights the page uses.++It prints a `brand` and `fonts` block to paste into `video.json`. Check it+against the screenshots. Fonts built into explainroo need no files. For other+fonts, get the files, check the license and copy the license file next to+them. Cookie banners and chat widgets can appear in the screenshots, as they+do for any visitor. Use a screenshot, or a part of one, without them.+Capturing the same site again replaces its folder.+You can also show a real screen recording with `s.clip` in a `browser`frame. Use `s.camera` to zoom in on the detail the voice mentions.@@ -650,6 +675,7 @@ when `ink` or `muted` has too little contrast against `bg`.| `check [project]` | finds layout, timing and pronunciation problems || `render [project]` | the MP4 plus subtitle files, chapters and a cover (`--format gif`, `--draft`, `--from`, `--to`, `--workers`, `--out`) || `verify [project]` | checks the finished file: loudness, black frames, silence, clear voice |+| `capture [project] <url>` | saves screenshots, wording, colors, fonts and logos from a live site (`--mobile`, `--json`) || `image [project] <name> "<prompt>"` | makes an illustration with OpenRouter || `images [project]` | lists the images and what they cost || `voices`, `say "text"` | lists the 28 Kokoro voices, or makes a sample |diff --git a/src/capture.js b/src/capture.jsnew file mode 100644index 0000000..ffe88d8--- /dev/null+++ b/src/capture.js@@ -0,0 +1,315 @@+import fs from 'node:fs';+import path from 'node:path';+import { launch } from './browser.js';+import { ProjectError, findProjectDir } from './project.js';++const BUILT_IN_FONTS = new Set(JSON.parse(fs.readFileSync(new URL('../fonts/fonts.json', import.meta.url), 'utf8')).map((f) => f.family));++export function validateUrl(value) {+ let url;+ try { url = new URL(value); } catch {}+ if (!url || !['http:', 'https:'].includes(url.protocol) || ['.', '..'].includes(url.hostname)) {+ throw new ProjectError('capture needs an http:// or https:// URL.');+ }+ if (url.username || url.password) throw new ProjectError('capture does not log in. Remove the username and password from the URL.');+ return url;+}++export function isGoogleFont(value, hostCheck = (host) => host === 'fonts.gstatic.com') {+ try {+ const url = new URL(value);+ return ['http:', 'https:'].includes(url.protocol) && hostCheck(url.hostname);+ } catch { return false; }+}++export function pickColors(samples, exclude = []) {+ const totals = new Map();+ for (const { color, area = 1 } of samples) {+ if (!/^#[0-9a-f]{6}$/i.test(color) || area <= 0) continue;+ const key = color.toLowerCase();+ const item = totals.get(key) || { color: key, area: 0, count: 0 };+ item.area += area;+ item.count++;+ totals.set(key, item);+ }+ const saturated = (hex) => {+ const rgb = hex.slice(1).match(/../g).map((n) => parseInt(n, 16) / 255);+ const hi = Math.max(...rgb), lo = Math.min(...rgb);+ return hi > 0.15 && lo < 0.9 && hi - lo > 0.12 && (hi - lo) / hi > 0.25;+ };+ const ranked = [...totals.values()].sort((a, b) => b.area * b.count - a.area * a.count || a.color.localeCompare(b.color));+ const sum = [...totals.values()].reduce((n, x) => n + x.area, 0);+ return {+ accent: ranked.find((x) => saturated(x.color))?.color || null,+ other: [...totals.values()].filter((x) => !exclude.includes(x.color)).sort((a, b) => b.area - a.area || a.color.localeCompare(b.color)).slice(0, 6)+ .map((x) => ({ color: x.color, share: Math.round(x.area / sum * 1000) / 1000 })),+ };+}++export function rankLogos(candidates) {+ const score = (c) => c.type === 'svg' ? (c.kind === 'brand' ? 4 : 3) : (c.kind === 'og' ? 1 : 2);+ const seen = new Set();+ return candidates.filter((c) => ['svg', 'png'].includes(c.type))+ .sort((a, b) => score(b) - score(a) || b.area - a.area)+ .filter((c) => {+ const key = c.url || c.svg;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++// This runs in the visited page. Read computed styles so CSS variables and+// inherited colors agree with the screenshots.+function inspectPage({ stylesheets, loadedFonts }) {+ const clean = (v) => (v || '').trim();+ const family = (v) => clean(v.split(',')[0]).replace(/^['"]|['"]$/g, '');+ const style = (el) => getComputedStyle(el);+ const visible = (el) => {+ const r = el.getBoundingClientRect(), c = style(el);+ return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < 8000 && c.display !== 'none' && c.visibility === 'visible' && Number(c.opacity) > 0 && el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true });+ };+ const elements = [...document.querySelectorAll('body *')].filter(visible);+ const select = (q) => [...document.querySelectorAll(q)].filter(visible);+ const labels = (els, attr) => [...new Set(els.map((el) => clean(attr ? el.getAttribute(attr) : el.innerText || el.textContent)).filter(Boolean))].slice(0, 40);+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = 1;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ const hex = (value) => {+ ctx.clearRect(0, 0, 1, 1);+ ctx.fillStyle = value;+ ctx.fillRect(0, 0, 1, 1);+ const rgb = ctx.getImageData(0, 0, 1, 1).data;+ return rgb[3] ? '#' + [...rgb].slice(0, 3).map((n) => n.toString(16).padStart(2, '0')).join('') : null;+ };+ const area = (el) => {+ const r = el.getBoundingClientRect();+ return Math.max(0, Math.min(r.right, innerWidth) - Math.max(0, r.left)) * Math.max(0, Math.min(r.bottom, 8000) - Math.max(0, r.top));+ };+ const buttons = elements.filter((el) => el.matches('button, input[type=submit], input[type=button], [role=button]') ||+ (el.matches('a') && (/btn|button/i.test(el.className) || (hex(style(el).backgroundColor) && parseFloat(style(el).paddingLeft) >= 8))));+ const headings = select('h1, h2, h3, h4, h5, h6');+ const links = select('a');+ const body = document.body;+ const colors = {+ background: hex(style(body).backgroundColor) || hex(style(document.documentElement).backgroundColor) || '#ffffff',+ text: hex(style(body).color),+ heading: headings[0] ? hex(style(headings[0]).color) : null,+ link: links[0] ? hex(style(links[0]).color) : null,+ };+ const samples = elements.flatMap((el) => {+ const c = style(el), a = area(el);+ const r = el.getBoundingClientRect();+ return [{ color: hex(c.backgroundColor), area: a }, { color: hex(c.color), area: el.childNodes.length && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim()) ? a : 0 },+ { color: hex(c.borderTopColor), area: parseFloat(c.borderTopWidth) * r.width }, { color: hex(c.borderBottomColor), area: parseFloat(c.borderBottomWidth) * r.width },+ { color: hex(c.borderLeftColor), area: parseFloat(c.borderLeftWidth) * r.height }, { color: hex(c.borderRightColor), area: parseFloat(c.borderRightWidth) * r.height }];+ });+ samples.push({ color: colors.background, area: innerWidth * Math.min(8000, document.documentElement.scrollHeight) });+ const buttonSamples = buttons.map((el) => ({ color: hex(style(el).backgroundColor), area: area(el) }));+ const fonts = { body: family(style(body).fontFamily), headings: [...new Set(headings.map((el) => family(style(el).fontFamily)))], buttons: [...new Set(buttons.map((el) => family(style(el).fontFamily)))], families: [] };+ const names = [...new Set([fonts.body, ...fonts.headings, ...fonts.buttons])].filter(Boolean);+ const used = [body, ...elements];+ for (const name of names) {+ const uses = used.filter((el) => family(style(el).fontFamily) === name).map((el) => ({ weight: Number(style(el).fontWeight), style: style(el).fontStyle }));+ fonts.families.push({ family: name, uses: [...new Map(uses.map((u) => [JSON.stringify(u), u])).values()], faces: [], sources: [] });+ }+ for (const face of document.fonts) {+ const f = fonts.families.find((f) => f.family === family(face.family));+ if (f) f.faces.push({ weight: face.weight, style: face.style, status: face.status });+ }+ const loaded = new Set([...performance.getEntriesByType('resource').map((r) => r.name), ...loadedFonts]);+ const readRules = (rules, base) => {+ for (const rule of rules) {+ if (rule.type === CSSRule.FONT_FACE_RULE) {+ const f = fonts.families.find((f) => f.family === family(rule.style.getPropertyValue('font-family')));+ if (!f) continue;+ for (const match of rule.style.getPropertyValue('src').matchAll(/url\(\s*['"]?([^'"\s)]+)['"]?\s*\)/g)) {+ const url = new URL(match[1], base).href;+ const weight = rule.style.getPropertyValue('font-weight').replace(/normal/g, '400').replace(/bold/g, '700') || '400';+ const source = { url, weight, style: rule.style.getPropertyValue('font-style') || 'normal', loaded: loaded.has(url) };+ if (!f.sources.some((s) => JSON.stringify(s) === JSON.stringify(source))) f.sources.push(source);+ }+ } else if (rule.styleSheet) {+ try { readRules(rule.styleSheet.cssRules, rule.styleSheet.href || base); } catch {}+ } else if (rule.cssRules) readRules(rule.cssRules, base);+ }+ };+ for (const sheet of document.styleSheets) {+ try { readRules(sheet.cssRules, sheet.href || document.baseURI); } catch {}+ }+ // Cross-origin stylesheets may hide their CSSOM. Their already loaded+ // response bodies still let us match font URLs to families without a fetch.+ for (const { css, url } of stylesheets) {+ try {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(css);+ readRules(sheet.cssRules, url);+ } catch {}+ }+ const siteName = clean(document.querySelector('meta[property="og:site_name"]')?.content) || location.hostname.replace(/^www\./, '').split('.')[0];+ const candidates = [];+ const firstHome = [...document.querySelectorAll('a[href]')].find((el) => {+ try { const u = new URL(el.href); return u.origin === location.origin && u.pathname === '/'; } catch { return false; }+ });+ const type = (url, mime = '') => /svg/i.test(mime) || /\.svg(?:[?#]|$)|^data:image\/svg\+xml/i.test(url) ? 'svg' : /png/i.test(mime) || /\.png(?:[?#]|$)|^data:image\/png/i.test(url) ? 'png' : null;+ for (const el of select('header svg, header img, nav svg, nav img, [role=banner] svg, [role=banner] img, a svg, a img')) {+ if (!el.closest('header, nav, [role=banner]') && !firstHome?.contains(el)) continue;+ const parent = el.closest('a');+ const identity = [el, parent].filter(Boolean).flatMap((n) => ['id', 'class', 'alt', 'aria-label', 'src'].map((a) => n.getAttribute(a) || '')).join(' ').toLowerCase();+ if (!identity.includes('logo') && !(siteName.length > 1 && identity.includes(siteName.toLowerCase()))) continue;+ const c = { kind: 'brand', area: area(el), color: style(el).color };+ if (el.tagName.toLowerCase() === 'svg') {+ const copy = el.cloneNode(true);+ copy.setAttribute('xmlns', 'http://www.w3.org/2000/svg');+ const copies = [copy, ...copy.querySelectorAll('*')];+ [el, ...el.querySelectorAll('*')].forEach((original, i) => {+ const target = copies[i], computed = style(original);+ for (const attr of target.getAttributeNames()) target.setAttribute(attr, target.getAttribute(attr).replace(/currentColor/gi, computed.color));+ for (const prop of ['fill', 'stroke', 'color']) target.style.setProperty(prop, computed[prop].replace(/url\(["']?[^)"']*#([^)'" ]+)["']?\)/g, 'url(#$1)'));+ });+ candidates.push({ ...c, type: 'svg', svg: new XMLSerializer().serializeToString(copy) });+ } else candidates.push({ ...c, type: type(el.currentSrc || el.src), url: el.currentSrc || el.src });+ }+ for (const el of document.querySelectorAll('link[rel~="icon"], link[rel="apple-touch-icon"], meta[property="og:image"]')) {+ const url = el.href || new URL(el.content, document.baseURI).href;+ const sizes = (el.getAttribute('sizes') || '').match(/(\d+)x(\d+)/);+ candidates.push({ kind: el.tagName === 'META' ? 'og' : 'icon', type: type(url, el.type), url, area: sizes ? Number(sizes[1]) * Number(sizes[2]) : 0 });+ }+ return {+ url: location.href, title: document.title, description: document.querySelector('meta[name="description"]')?.content || null,+ themeColor: hex(document.querySelector('meta[name="theme-color"]')?.content || 'transparent'),+ colors, samples, buttonSamples, fonts, candidates,+ text: { h1: labels(select('h1')), h2: labels(select('h2')), navigation: labels(select('nav a, [role=navigation] a')), buttons: [...new Set(buttons.map((el) => clean(el.value || el.innerText || el.getAttribute('aria-label'))).filter(Boolean))].slice(0, 40), labels: labels(select('label')), placeholders: labels(select('input[placeholder], textarea[placeholder]'), 'placeholder') },+ };+}++async function loadPage(page, url) {+ try {+ const response = await page.goto(url, { waitUntil: 'load', timeout: 30000 });+ if (!response || !response.ok()) throw new Error('page returned an error');+ validateUrl(page.url());+ // Background polling may never stop. Give it time to settle, then capture+ // the loaded page; fonts still have to finish within the same limit.+ await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});+ await page.waitForFunction(() => document.fonts.status === 'loaded', { timeout: 10000 });+ } catch {+ throw new ProjectError('the page did not load. Check the URL and try capture again.');+ }+}++async function screenshots(page, dir, prefix = '') {+ await page.screenshot({ path: path.join(dir, prefix ? 'mobile.png' : 'page.png'), timeout: 15000 });+ const height = await page.evaluate(() => Math.min(8000, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, innerHeight)));+ await page.screenshot({ path: path.join(dir, `${prefix}full.png`), fullPage: true, clip: { x: 0, y: 0, width: page.viewportSize().width, height }, timeout: 15000 });+}++async function download(context, url) {+ if (/^data:/i.test(url)) {+ const match = /^data:image\/(svg\+xml|png)(;base64)?,([\s\S]*)$/i.exec(url);+ if (!match) throw new Error('unsupported image');+ return Buffer.from(match[2] ? match[3] : decodeURIComponent(match[3]), match[2] ? 'base64' : 'utf8');+ }+ validateUrl(url);+ const response = await context.request.get(url, { timeout: 15000 });+ if (!response.ok()) throw new Error('file did not load');+ return response.body();+}++export async function capture(project, value, { mobile = false, googleHostCheck } = {}) {+ const url = validateUrl(value);+ const projectDir = findProjectDir(typeof project === 'string' ? project : project?.dir);+ const host = url.hostname.replace(/[:[\]]/g, '_');+ const relative = `assets/capture/${host}`;+ const dest = path.join(projectDir, relative);+ for (const folder of ['assets', 'assets/capture', relative]) {+ const file = path.join(projectDir, folder);+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });+ if (stat && !stat.isDirectory()) throw new ProjectError(`${folder} must be a folder, not a link or file. Move it and try capture again.`);+ }+ const browser = await launch();+ let temp;+ try {+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 });+ const page = await context.newPage();+ const cssResponses = [];+ const loadedFonts = [];+ page.on('response', (response) => {+ if (response.request().resourceType() === 'stylesheet') {+ cssResponses.push(response.text().then((css) => ({ css, url: response.url() })).catch(() => null));+ }+ if (response.request().resourceType() === 'font' && response.ok()) loadedFonts.push(response.url());+ });+ await loadPage(page, url.href);+ const stylesheets = (await Promise.all(cssResponses)).filter(Boolean);+ const data = await page.evaluate(inspectPage, { stylesheets, loadedFonts });+ const { samples, buttonSamples, candidates, ...result } = data;+ result.colors.accent = pickColors(buttonSamples).accent;+ result.colors.other = pickColors(samples, Object.values(result.colors).filter(Boolean)).other;+ result.brand = {};+ for (const [key, val] of Object.entries({ accent: result.colors.accent, background: result.colors.background, ink: result.colors.text, font: result.fonts.body })) {+ if (val) result.brand[key] = val;+ }+ result.notes = [];+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ temp = fs.mkdtempSync(path.join(path.dirname(dest), `.${host}-`));+ await screenshots(page, temp);+ result.logo = { picked: null, candidates: [] };+ const logos = [];+ for (const candidate of candidates) {+ try {+ const bytes = candidate.svg ? Buffer.from(candidate.svg) : await download(context, candidate.url);+ const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));+ const type = png ? 'png' : /<svg[\s>]/i.test(bytes.toString()) ? 'svg' : null;+ if (type) logos.push({ ...candidate, bytes, type, area: png && bytes.length >= 24 ? bytes.readUInt32BE(16) * bytes.readUInt32BE(20) : candidate.area });+ } catch { result.notes.push(`Could not save a logo from ${candidate.url || 'the page'}.`); }+ }+ for (const candidate of rankLogos(logos).slice(0, 3)) {+ const n = result.logo.candidates.length;+ const file = `${relative}/logo${n ? '-' + (n + 1) : ''}.${candidate.type}`;+ fs.writeFileSync(path.join(temp, path.basename(file)), candidate.bytes);+ result.logo.candidates.push({ file, source: candidate.url || 'inline SVG', kind: candidate.kind });+ }+ result.logo.picked = result.logo.candidates[0]?.file || null;+ if (result.logo.picked) result.brand.logo = result.logo.picked;+ const savedFonts = [];+ for (const f of result.fonts.families) {+ if (BUILT_IN_FONTS.has(f.family)) {+ result.notes.push(`${f.family} is built into explainroo. It needs no font files.`);+ continue;+ }+ let saved = false;+ for (const source of f.sources) {+ const range = source.weight.split(/\s+/).map(Number);+ const used = f.uses.some((u) => u.weight >= range[0] && u.weight <= range.at(-1) && u.style === source.style);+ if (!source.loaded || !used || !isGoogleFont(source.url, googleHostCheck)) continue;+ try {+ const bytes = await download(context, source.url);+ const ext = /\.(woff2?|ttf|otf)$/i.exec(new URL(source.url).pathname)?.[0] || '.woff2';+ const name = f.family.replace(/[^a-z0-9-]/gi, '-') || 'font';+ const file = `${relative}/fonts/${name}-${source.weight.replace(/\s+/g, '-')}-${savedFonts.length + 1}${ext}`;+ fs.mkdirSync(path.join(temp, 'fonts'), { recursive: true });+ fs.writeFileSync(path.join(temp, 'fonts', path.basename(file)), bytes);+ savedFonts.push({ family: f.family, src: file, weight: range.length === 1 ? range[0] : source.weight, style: source.style });+ saved = true;+ } catch { result.notes.push(`Could not save ${f.family}. Get the font files and check the license.`); }+ }+ if (!saved) result.notes.push(`${f.family}: get the font files and check the license. Copy the license file next to them.`);+ }+ if (mobile) {+ const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });+ const mobilePage = await phone.newPage();+ await loadPage(mobilePage, url.href);+ await screenshots(mobilePage, temp, 'mobile-');+ }+ result.suggestion = { brand: result.brand, fonts: savedFonts };+ const files = fs.readdirSync(temp).filter((name) => name !== 'fonts').map((name) => `${relative}/${name}`);+ result.files = [...files, ...savedFonts.map((f) => f.src), `${relative}/capture.json`].sort();+ fs.writeFileSync(path.join(temp, 'capture.json'), JSON.stringify(result, null, 2) + '\n');+ fs.rmSync(dest, { recursive: true, force: true });+ fs.renameSync(temp, dest);+ return result;+ } finally {+ await browser.close();+ if (temp) fs.rmSync(temp, { recursive: true, force: true });+ }+}diff --git a/src/cli.js b/src/cli.jsindex 5ca8436..402118f 100644--- a/src/cli.js+++ b/src/cli.js@@ -14,6 +14,7 @@ import { ffmpegVersion } from './ffmpeg.js';import { findChrome } from './browser.js';import { generateImage, imageLog, imageSpend, IMAGE_MODELS } from './images.js';import { elevenVoices, elevenUsage, elevenSpeed } from './elevenlabs.js';+import { capture } from './capture.js';const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;@@ -28,18 +29,21 @@ Make a videostill [project] [t…] PNG stills: "12.5", "scene", "[email protected]" (default: end of every scene)sheet [project] contact sheet of the whole video (--scene id, --every s)check [project] find layout, timing and pronunciation problems (--view-width pixels)- render [project] write MP4, subtitles, chapters and a cover (--format gif for GIF)- (--draft, --from s, --to s, --workers n, --out file)+ render [project] write the MP4 with subtitles, chapters and a cover (--format gif,+ --draft, --from s, --to s, --workers n, --out file)verify [project] check an MP4: loudness, black frames, narration+Product demos+ capture [project] <url> save screenshots, wording, colors, fonts and logo of a live site (--mobile)+Images (optional, needs an OpenRouter API key)image [project] <name> "<what to draw>" save an illustration as assets/<name>.png(--model best|cheap, --aspect 16:9, --ref assets/a.png,assets/b.png, --no-style)images [project] list generated images and what they costReference- voices [project] list Kokoro voices (--elevenlabs lists voices available to your key)- say "text" hear a Kokoro sample (--voice am_michael, --speed 1, --out sample.wav)+ voices [project] list Kokoro voices (--elevenlabs lists the voices of your ElevenLabs key)+ say "text" hear a Kokoro voice (--voice am_michael, --speed 1, --out sample.wav)themes list looksformats list sizes for YouTube, Shorts, TikTok, Reels, Instagram, LinkedInicons <word…> search the 1,800+ built-in icons@@ -63,7 +67,7 @@ function parseArgs(argv) {}return { pos, flags };}-const BOOL = new Set(['json', 'draft', 'force', 'fetch', 'help', 'version', 'quiet', 'open', 'no-style', 'elevenlabs']);+const BOOL = new Set(['json', 'draft', 'force', 'fetch', 'help', 'version', 'quiet', 'open', 'no-style', 'elevenlabs', 'mobile']);function num(v, name) {if (v === undefined) return undefined;@@ -95,6 +99,13 @@ export async function main(argv) {try {switch (cmd) {case 'init': return init(pos[0], flags, print);+ case 'capture': {+ if (pos.length < 1 || pos.length > 2) throw new ProjectError('usage: explainroo capture [project] <url> [--mobile] [--json]');+ const r = await capture(pos.length === 2 ? pos[0] : undefined, pos.at(-1), { mobile: !!flags.mobile });+ const families = r.fonts.families.map((f) => f.family).join(', ') || 'none found';+ print(`saved:\n${r.files.map((f) => ' ' + f).join('\n')}\naccent: ${r.colors.accent || 'none found'}\nfonts: ${families}\nlogo: ${r.logo.picked || 'none found'}\n${r.notes.join('\n')}\nPaste into video.json:\n${JSON.stringify(r.suggestion, null, 2)}\nOpen the screenshots and check them before you use them.`, r);+ return 0;+ }case 'voice': {const project = loadProject(pos[0]);const before = elevenUsage(project).length;diff --git a/test/capture-browser.test.js b/test/capture-browser.test.jsnew file mode 100644index 0000000..1d81163--- /dev/null+++ b/test/capture-browser.test.js@@ -0,0 +1,90 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { fileURLToPath } from 'node:url';+import { findChrome } from '../src/browser.js';+import { capture } from '../src/capture.js';+import { normalizeConfig } from '../src/project.js';+import { captureFixture } from './capture-fixture.js';++let chrome;+try { chrome = findChrome(); } catch {}+const bin = fileURLToPath(new URL('../bin/explainroo.js', import.meta.url));+const run = promisify(execFile);+const dimensions = (file) => {+ const png = fs.readFileSync(file);+ return [png.readUInt32BE(16), png.readUInt32BE(20)];+};++test('capture saves a local site, its loaded fonts and desktop and phone screenshots', { skip: !chrome }, async () => {+ const site = await captureFixture();+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-capture-'));+ try {+ const config = '{"title":"Existing project"}\n';+ fs.writeFileSync(path.join(dir, 'video.json'), config);+ fs.mkdirSync(path.join(dir, 'assets'));+ fs.writeFileSync(path.join(dir, 'assets', 'keep.txt'), 'Keep this file');+ const result = await capture(dir, `${site.url}/redirect`, { mobile: true, googleHostCheck: (host) => host === '127.0.0.1' });+ const root = path.join(dir, 'assets/capture/127.0.0.1');+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'capture.json'))), result);+ assert.equal(result.url, `${site.url}/`);+ assert.equal(result.title, 'Fixture Studio');+ assert.equal(result.description, 'A local page for capture tests.');+ assert.equal(result.themeColor, '#245cff');+ assert.equal(result.colors.accent, '#245cff');+ assert.equal(result.colors.background, '#f8f6f1');+ assert.equal(result.colors.text, '#202020');+ assert.equal(result.colors.heading, '#163469');+ assert.equal(result.colors.link, '#245cff');+ assert.ok(result.colors.other.length <= 6);+ assert.equal(result.fonts.body, 'Fixture Sans');+ assert.deepEqual(result.fonts.headings, ['Fixture Sans']);+ assert.deepEqual(result.fonts.buttons, ['Fixture Sans']);+ assert.equal(result.suggestion.fonts.length, 1);+ assert.equal(result.suggestion.fonts[0].weight, 400);+ assert.equal(site.requests.includes('/unused.woff2'), false);+ assert.deepEqual(fs.readFileSync(path.join(dir, result.suggestion.fonts[0].src)), fs.readFileSync(path.join(site.dir, 'fixture.woff2')));+ assert.deepEqual(result.text.h1, ['Build a clear product demo']);+ assert.deepEqual(result.text.h2, ['Your brand on every screen', 'Capture once, use the files']);+ assert.deepEqual(result.text.navigation, ['Features', 'Plans']);+ assert.deepEqual(result.text.buttons, ['Start a project', 'See examples', 'Create project']);+ assert.deepEqual(result.text.labels, ['Project name']);+ assert.deepEqual(result.text.placeholders, ['My first demo']);+ assert.equal(result.brand.logo, 'assets/capture/127.0.0.1/logo.svg');+ assert.equal(result.logo.picked, result.brand.logo);+ assert.deepEqual(result.logo.candidates.map((c) => path.basename(c.file)), ['logo.svg', 'logo-2.svg', 'logo-3.png']);+ assert.match(fs.readFileSync(path.join(root, 'logo.svg'), 'utf8'), /xmlns="http:\/\/www.w3.org\/2000\/svg"/);+ assert.match(fs.readFileSync(path.join(root, 'logo.svg'), 'utf8'), /fill: rgb\(36, 92, 255\)/);+ assert.doesNotMatch(fs.readFileSync(path.join(root, 'logo.svg'), 'utf8'), /currentColor/i);+ assert.deepEqual(dimensions(path.join(root, 'page.png')), [2880, 1800]);+ assert.deepEqual(dimensions(path.join(root, 'full.png')), [2880, 16000]);+ assert.deepEqual(dimensions(path.join(root, 'mobile.png')), [780, 1688]);+ assert.deepEqual(dimensions(path.join(root, 'mobile-full.png')), [780, 16000]);+ assert.ok(result.files.every((file) => fs.existsSync(path.join(dir, file))));+ assert.deepEqual(normalizeConfig(result.suggestion).brand, result.brand);+ assert.equal(fs.readFileSync(path.join(dir, 'video.json'), 'utf8'), config);+ assert.equal(fs.readFileSync(path.join(dir, 'assets', 'keep.txt'), 'utf8'), 'Keep this file');+ await assert.rejects(capture(dir, `${site.url}/missing`), /page did not load/);+ assert.ok(fs.existsSync(path.join(root, 'mobile.png')));+ fs.writeFileSync(path.join(root, 'stale.txt'), 'old capture');+ const cli = await run(process.execPath, [bin, 'capture', dir, site.url, '--json'], { timeout: 60000 });+ const json = JSON.parse(cli.stdout);+ assert.equal(json.colors.accent, '#245cff');+ assert.equal(json.suggestion.fonts.length, 0);+ assert.match(json.notes.join(' '), /Fixture Sans: get the font files and check the license/);+ assert.equal(fs.existsSync(path.join(root, 'stale.txt')), false);+ assert.equal(fs.existsSync(path.join(root, 'mobile.png')), false);+ const human = await run(process.execPath, [bin, 'capture', '--mobile', site.url], { cwd: dir, timeout: 60000 });+ assert.match(human.stdout, /accent: #245cff/);+ assert.match(human.stdout, /logo: assets\/capture\/127.0.0.1\/logo.svg/);+ assert.match(human.stdout, /Paste into video.json:/);+ assert.ok(fs.existsSync(path.join(root, 'mobile.png')));+ } finally {+ await site.close();+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/capture-fixture.js b/test/capture-fixture.jsnew file mode 100644index 0000000..c8d0bb7--- /dev/null+++ b/test/capture-fixture.js@@ -0,0 +1,46 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import http from 'node:http';+import { fileURLToPath } from 'node:url';++export async function captureFixture() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-capture-site-'));+ fs.copyFileSync(fileURLToPath(new URL('../fonts/Inter-400-latin.woff2', import.meta.url)), path.join(dir, 'fixture.woff2'));+ fs.writeFileSync(path.join(dir, 'icon.svg'), '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" fill="#245cff"/></svg>');+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK3sAAAAASUVORK5CYII=', 'base64');+ for (const name of ['touch.png', 'social.png']) fs.writeFileSync(path.join(dir, name), png);+ const requests = [];+ // A second local origin makes the font stylesheet's CSSOM unreadable.+ const styles = http.createServer((req, res) => {+ requests.push(req.url);+ res.setHeader('Access-Control-Allow-Origin', '*');+ if (req.url === '/font.css') {+ res.setHeader('Content-Type', 'text/css');+ return res.end("@font-face { font-family: 'Fixture Sans'; src: url('fixture.woff2'); font-weight: 400; } @font-face { font-family: 'Fixture Sans'; src: url('unused.woff2'); font-weight: 900; }");+ }+ if (req.url === '/fixture.woff2') {+ res.setHeader('Content-Type', 'font/woff2');+ return res.end(fs.readFileSync(path.join(dir, 'fixture.woff2')));+ }+ res.writeHead(404);+ res.end('Not found');+ });+ await new Promise((resolve) => styles.listen(0, '127.0.0.1', resolve));+ const html = fs.readFileSync(fileURLToPath(new URL('./fixtures/capture.html', import.meta.url)), 'utf8');+ fs.writeFileSync(path.join(dir, 'index.html'), html.replace('__FONT_CSS__', `http://127.0.0.1:${styles.address().port}/font.css`));+ const server = http.createServer((req, res) => {+ requests.push(req.url);+ if (req.url === '/redirect') { res.writeHead(302, { Location: '/' }); return res.end(); }+ const name = req.url === '/' ? 'index.html' : ['/fixture.woff2', '/icon.svg', '/touch.png', '/social.png'].includes(req.url) ? req.url.slice(1) : null;+ if (!name) { res.writeHead(404); return res.end('Not found'); }+ const type = { '.html': 'text/html', '.woff2': 'font/woff2', '.png': 'image/png', '.svg': 'image/svg+xml' }[path.extname(name)];+ res.writeHead(200, { 'Content-Type': type });+ res.end(fs.readFileSync(path.join(dir, name)));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ return { dir, requests, url: `http://127.0.0.1:${server.address().port}`, close: async () => {+ await Promise.all([server, styles].map((s) => new Promise((resolve) => { s.closeAllConnections(); s.close(resolve); })));+ fs.rmSync(dir, { recursive: true, force: true });+ } };+}diff --git a/test/capture.test.js b/test/capture.test.jsnew file mode 100644index 0000000..dc3f38d--- /dev/null+++ b/test/capture.test.js@@ -0,0 +1,62 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { capture, validateUrl, pickColors, rankLogos, isGoogleFont } from '../src/capture.js';++test('capture accepts only HTTP URLs without login credentials', () => {+ assert.equal(validateUrl('https://example.com/demo').hostname, 'example.com');+ assert.equal(validateUrl('http://127.0.0.1:1234/').port, '1234');+ for (const value of ['file:///tmp/page.html', 'data:text/html,hello', 'ftp://example.com', 'example.com', '', undefined, 'http://../']) {+ assert.throws(() => validateUrl(value), /http:\/\/ or https:\/\//);+ }+ assert.throws(() => validateUrl('https://user:[email protected]'), /does not log in/);+});++test('accent counts saturated button backgrounds by area and frequency', () => {+ const samples = [+ { color: '#eeeeee', area: 9000 }, { color: '#070707', area: 9000 }, { color: '#888888', area: 9000 },+ { color: '#245CFF', area: 200 }, { color: '#245cff', area: 200 }, { color: '#00aa22', area: 700 },+ { color: '#fffefa', area: 9000 }, { color: null, area: 20 }, { color: '#aa0000', area: 0 },+ { color: '#ee0000', area: 10 }, { color: '#ee00ee', area: 10 },+ ];+ const colors = pickColors(samples, ['#888888']);+ assert.equal(colors.accent, '#245cff');+ assert.equal(colors.other.some((c) => c.color === '#888888'), false);+ assert.equal(colors.other.length, 6);+ assert.ok(colors.other.every((c) => c.share >= 0 && c.share <= 1));+ assert.deepEqual(pickColors([]), { accent: null, other: [] });+ assert.equal(pickColors([{ color: '#aaaaaa' }]).accent, null);+});++test('logos prefer brand SVGs, SVG icons, large PNGs, then the social image', () => {+ const candidates = [+ { url: 'social.png', type: 'png', kind: 'og', area: 100000 },+ { url: 'small.png', type: 'png', kind: 'icon', area: 256 },+ { url: 'large.png', type: 'png', kind: 'icon', area: 10000 },+ { url: 'icon.svg', type: 'svg', kind: 'icon', area: 64 },+ { svg: '<svg/>', type: 'svg', kind: 'brand', area: 32 },+ { url: 'large.png', type: 'png', kind: 'icon', area: 10000 },+ { url: 'photo.jpg', type: 'jpg', kind: 'og', area: 200000 },+ ];+ assert.deepEqual(rankLogos(candidates).map((c) => c.url || c.svg), ['<svg/>', 'icon.svg', 'large.png', 'small.png', 'social.png']);+});++test('Google font downloads require the exact source host', () => {+ assert.equal(isGoogleFont('https://fonts.gstatic.com/s/inter/v1/font.woff2'), true);+ for (const url of ['https://fonts.googleapis.com/style.css', 'https://fonts.gstatic.com.evil.test/font.woff2', 'https://evil.test/fonts.gstatic.com/a', 'file://fonts.gstatic.com/a', 'bad']) assert.equal(isGoogleFont(url), false);+ assert.equal(isGoogleFont('http://127.0.0.1/font.woff2', (host) => host === '127.0.0.1'), true);+});++test('capture refuses to write through a linked assets folder', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-capture-link-'));+ try {+ fs.mkdirSync(path.join(dir, 'project'));+ fs.mkdirSync(path.join(dir, 'outside'));+ fs.writeFileSync(path.join(dir, 'project', 'video.json'), '{}');+ fs.symlinkSync(path.join(dir, 'outside'), path.join(dir, 'project', 'assets'), 'junction');+ await assert.rejects(capture(path.join(dir, 'project'), 'http://127.0.0.1'), /not a link or file/);+ assert.deepEqual(fs.readdirSync(path.join(dir, 'outside')), []);+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }+});diff --git a/test/fixtures/capture.html b/test/fixtures/capture.htmlnew file mode 100644index 0000000..766aa62--- /dev/null+++ b/test/fixtures/capture.html@@ -0,0 +1,55 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>Fixture Studio</title>+ <meta name="description" content="A local page for capture tests.">+ <meta name="theme-color" content="#245cff">+ <meta property="og:site_name" content="Fixture">+ <meta property="og:image" content="/social.png">+ <link rel="icon" type="image/svg+xml" href="/icon.svg">+ <link rel="apple-touch-icon" href="/touch.png">+ <link rel="stylesheet" href="__FONT_CSS__">+ <style>+ * { box-sizing: border-box; }+ body { margin: 0; background: #f8f6f1; color: #202020; font-family: 'Fixture Sans', sans-serif; font-weight: 400; }+ header { display: flex; align-items: center; justify-content: space-between; padding: 28px 6%; border-bottom: 1px solid #dedcd6; }+ .logo { display: flex; align-items: center; gap: 12px; color: #245cff; text-decoration: none; font-size: 24px; }+ nav { display: flex; gap: 24px; }+ a { color: #245cff; }+ main { padding: 55px 8%; }+ h1, h2 { color: #163469; font-weight: 400; }+ h1 { font-size: 54px; max-width: 680px; margin: 12px 0; }+ h2 { font-size: 32px; }+ p { font-size: 22px; line-height: 1.5; }+ button, .button { font: 400 18px 'Fixture Sans', sans-serif; color: white; background: #245cff; border: none; border-radius: 8px; padding: 16px 24px; display: inline-block; text-decoration: none; }+ form { display: grid; max-width: 460px; gap: 14px; margin: 34px 0; }+ label { font-size: 18px; }+ input { font: inherit; font-size: 18px; padding: 16px; background: white; border: 1px solid #ccc; border-radius: 8px; }+ .hidden { display: none; }+ .footer { margin-top: 40px; height: 8100px; background: #e9eef8; padding: 24px; }+ @media (max-width: 600px) { header { align-items: flex-start; flex-direction: column; gap: 20px; } h1 { font-size: 36px; } main { padding: 32px 6%; } }+ </style>+</head>+<body>+ <header>+ <a class="logo" href="/" aria-label="Fixture home">+ <svg class="logo" aria-label="Fixture logo" width="42" height="42" viewBox="0 0 42 42"><rect x="2" y="2" width="38" height="38" rx="10" fill="currentColor"/><path d="M12 14h19M12 21h15M12 28h10" stroke="white" stroke-width="3"/></svg>+ Fixture Studio+ </a>+ <nav aria-label="Main navigation"><a href="#features">Features</a><a href="#plans">Plans</a><a href="#features">Features</a></nav>+ </header>+ <main>+ <h1>Build a clear product demo</h1>+ <p>Keep your colors, fonts and wording together.</p>+ <button>Start a project</button>+ <a class="button" href="#features">See examples</a>+ <h2 id="features">Your brand on every screen</h2>+ <form><label for="name">Project name</label><input id="name" placeholder="My first demo"><button type="submit">Create project</button></form>+ <button class="hidden">Hidden action</button><input class="hidden" placeholder="Hidden placeholder">+ <h2 id="plans">Capture once, use the files</h2>+ <div class="footer">A long page checks the screenshot height limit.</div>+ </main>+</body>+</html>