The best way to control Claude Code, Codex and more from any computer or phone

main
mjs 125 lines 5.25 KB
Raw
1 // Freezes the live app page into a static HTML file that a story can load and animate.
2 // saveBeat(page, dir, name): `page` is anything with Playwright's `evaluate`, such as a
3 // scenario's `browser`. Writes <dir>/beats/<name>.html; fonts and images go to
4 // <dir>/beats/assets, shared by every beat.
5 import * as NodeFS from "node:fs";
6 import * as NodePath from "node:path";
7
8 // Runs in the page. Returns the frozen document and the assets it references.
9 async function freeze(known) {
10 const hash = (s) => {
11 let h1 = 0xdeadbeef;
12 let h2 = 0x41c6ce57;
13 for (let i = 0; i < s.length; i++) {
14 const c = s.charCodeAt(i);
15 h1 = Math.imul(h1 ^ c, 2654435761);
16 h2 = Math.imul(h2 ^ c, 1597334677);
17 }
18 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
19 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
20 return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
21 };
22 const assets = {};
23 const local = (raw, base) => {
24 if (!raw || raw.startsWith("data:") || raw.startsWith("#")) return raw;
25 const url = new URL(raw, base).href;
26 const ext = (new URL(url).pathname.match(/\.[a-z0-9]{1,5}$/i) ?? [""])[0];
27 const name = `assets/${hash(url)}${ext}`;
28 assets[name] = url;
29 return name;
30 };
31 const urlPattern = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g;
32 const rewrite = (css, base) => css.replace(urlPattern, (_, __, u) => `url("${local(u, base)}")`);
33
34 let css = "";
35 for (const sheet of [...document.styleSheets, ...document.adoptedStyleSheets]) {
36 let rules;
37 try {
38 rules = [...sheet.cssRules];
39 } catch {
40 continue;
41 }
42 css += rewrite(rules.map((r) => r.cssText).join("\n"), sheet.href ?? location.href) + "\n";
43 }
44
45 const source = [...document.documentElement.querySelectorAll("*")];
46 const clone = document.documentElement.cloneNode(true);
47 const copies = [...clone.querySelectorAll("*")];
48 source.forEach((el, i) => {
49 const copy = copies[i];
50 if (el.scrollTop || el.scrollLeft)
51 copy.setAttribute("data-kit-scroll", `${el.scrollLeft},${el.scrollTop}`);
52 if (el instanceof HTMLTextAreaElement) copy.textContent = el.value;
53 else if (el instanceof HTMLInputElement) {
54 // Hidden inputs carry ids and local paths nobody sees; keep them out of the beat.
55 if (el.type === "hidden" || el.getAttribute("aria-hidden") === "true") {
56 copy.removeAttribute("value");
57 return;
58 }
59 copy.setAttribute("value", el.value);
60 if (el.checked) copy.setAttribute("checked", "");
61 } else if (el instanceof HTMLImageElement) {
62 copy.removeAttribute("srcset");
63 copy.setAttribute("src", local(el.currentSrc || el.src, location.href));
64 } else if (el instanceof HTMLCanvasElement) {
65 const img = document.createElement("img");
66 for (const a of el.attributes) img.setAttribute(a.name, a.value);
67 try {
68 img.src = el.toDataURL();
69 } catch {}
70 img.style.width = `${el.clientWidth}px`;
71 img.style.height = `${el.clientHeight}px`;
72 copy.replaceWith(img);
73 } else if (el instanceof HTMLIFrameElement) {
74 const box = document.createElement("div");
75 for (const a of el.attributes)
76 if (a.name !== "src" && a.name !== "srcdoc") box.setAttribute(a.name, a.value);
77 box.setAttribute("data-kit-iframe", el.src);
78 copy.replaceWith(box);
79 }
80 const style = copy.getAttribute?.("style");
81 if (style?.includes("url(")) copy.setAttribute("style", rewrite(style, location.href));
82 });
83 for (const el of clone.querySelectorAll("script, noscript, style, link, base")) el.remove();
84
85 const head = clone.querySelector("head");
86 const styleEl = document.createElement("style");
87 styleEl.textContent = css;
88 head.append(styleEl);
89 const viewport = document.createElement("meta");
90 viewport.name = "kit-viewport";
91 viewport.content = `${innerWidth}x${innerHeight}`;
92 head.append(viewport);
93 const restore = document.createElement("script");
94 restore.textContent = `for (const el of document.querySelectorAll("[data-kit-scroll]")) { const [x, y] = el.dataset.kitScroll.split(",").map(Number); el.scrollLeft = x; el.scrollTop = y; }`;
95 clone.querySelector("body").append(restore);
96
97 const fetched = {};
98 for (const [name, url] of Object.entries(assets)) {
99 if (known.includes(name)) continue;
100 try {
101 const buf = new Uint8Array(await (await fetch(url)).arrayBuffer());
102 let bin = "";
103 for (let i = 0; i < buf.length; i += 0x8000)
104 bin += String.fromCharCode(...buf.subarray(i, i + 0x8000));
105 fetched[name] = btoa(bin);
106 } catch {}
107 }
108 return {
109 html: `<!doctype html>\n${clone.outerHTML}`,
110 assets: fetched,
111 viewport: { width: innerWidth, height: innerHeight },
112 };
113 }
114
115 export async function saveBeat(page, dir, name) {
116 const beats = NodePath.join(dir, "beats");
117 NodeFS.mkdirSync(NodePath.join(beats, "assets"), { recursive: true });
118 const known = NodeFS.readdirSync(NodePath.join(beats, "assets")).map((f) => `assets/${f}`);
119 const result = await page.evaluate(freeze, known);
120 for (const [file, base64] of Object.entries(result.assets)) {
121 NodeFS.writeFileSync(NodePath.join(beats, file), Buffer.from(base64, "base64"));
122 }
123 NodeFS.writeFileSync(NodePath.join(beats, `${name}.html`), result.html);
124 return result.viewport;
125 }