capture.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { spawn } from "node:child_process";
  2. import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
  3. import { homedir, tmpdir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import { pathToFileURL } from "node:url";
  6. if (typeof WebSocket === "undefined" && !process.execArgv.includes("--experimental-websocket")) {
  7. const child = spawn(process.execPath, ["--experimental-websocket", ...process.argv.slice(1)], { stdio: "inherit" });
  8. child.on("exit", (code) => process.exit(code ?? 1));
  9. } else {
  10. await main();
  11. }
  12. function usage() {
  13. console.log(`Capture a figure with headless Chrome.
  14. node capture.mjs <file.html | file.svg | url> [options]
  15. --out <png> output path (default: capture.png in the current directory)
  16. --width <px> viewport width (default 1440; use 390 for a phone)
  17. --height <px> viewport height (default 1000)
  18. --scale <n> device pixel ratio (default 2)
  19. --wait <ms> time to let the page settle before the first shot (default 2500)
  20. --select <css> clip to this element (default: .iso-plate, else the whole page)
  21. --zoom <x,y,w,h> clip a region inside the selected element, in CSS px, for close-up checks
  22. --zoom-scale <n> pixel ratio for --zoom shots (default 4)
  23. --hover <fx,fy> move the mouse to this fraction of the selected element first (e.g. 0.6,0.5)
  24. --key <keys> press keys on the focused figure first, comma separated (e.g. Tab,ArrowRight,7,Escape);
  25. Tab is skipped (the figure is focused for you), a comma is written Comma
  26. --times <ms,...> extra shots at these delays, each measured from the first shot (not from the previous one),
  27. saved as name-<ms>.png; a capture takes 60-200 ms, so delays closer than that run late
  28. --reduced emulate prefers-reduced-motion: reduce
  29. --theme <dark|light> emulate prefers-color-scheme
  30. Prints the clip box, console errors, uncaught exceptions and whether the page scrolls sideways.`);
  31. }
  32. function parse(argv) {
  33. const options = { width: 1440, height: 1000, scale: 2, wait: 2500, zoomScale: 4, times: [] };
  34. const rest = [];
  35. for (let index = 0; index < argv.length; index++) {
  36. const arg = argv[index];
  37. const next = () => argv[++index];
  38. if (arg === "--out") options.out = next();
  39. else if (arg === "--width") options.width = Number(next());
  40. else if (arg === "--height") options.height = Number(next());
  41. else if (arg === "--scale") options.scale = Number(next());
  42. else if (arg === "--wait") options.wait = Number(next());
  43. else if (arg === "--select") options.select = next();
  44. else if (arg === "--zoom") options.zoom = next().split(",").map(Number);
  45. else if (arg === "--zoom-scale") options.zoomScale = Number(next());
  46. else if (arg === "--hover") options.hover = next().split(",").map(Number);
  47. else if (arg === "--key") options.keys = next().split(",");
  48. else if (arg === "--times") options.times = next().split(",").map(Number);
  49. else if (arg === "--reduced") options.reduced = true;
  50. else if (arg === "--theme") options.theme = next();
  51. else if (arg === "--help" || arg === "-h") options.help = true;
  52. else rest.push(arg);
  53. }
  54. options.target = rest[0];
  55. return options;
  56. }
  57. function playwrightShells() {
  58. const found = [];
  59. for (const root of [join(homedir(), ".cache/ms-playwright"), join(homedir(), "Library/Caches/ms-playwright")]) {
  60. if (!existsSync(root)) continue;
  61. for (const dir of readdirSync(root).filter((d) => d.startsWith("chromium_headless_shell-")).sort().reverse()) {
  62. for (const sub of ["chrome-headless-shell-linux64/chrome-headless-shell", "chrome-headless-shell-mac-arm64/chrome-headless-shell", "chrome-headless-shell-mac-x64/chrome-headless-shell"]) {
  63. found.push(join(root, dir, sub));
  64. }
  65. }
  66. }
  67. return found;
  68. }
  69. function chromePath() {
  70. const candidates = [
  71. process.env.CHROME_PATH, ...playwrightShells(),
  72. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
  73. "/Applications/Chromium.app/Contents/MacOS/Chromium",
  74. "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
  75. "/usr/bin/google-chrome",
  76. "/usr/bin/google-chrome-stable",
  77. "/usr/bin/chromium",
  78. "/usr/bin/chromium-browser",
  79. "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  80. ].filter(Boolean);
  81. const playwright = join(homedir(), "Library/Caches/ms-playwright");
  82. if (existsSync(playwright)) {
  83. for (const dir of readdirSync(playwright).sort().reverse()) {
  84. for (const sub of ["chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing", "chrome-mac/Chromium.app/Contents/MacOS/Chromium"]) {
  85. candidates.push(join(playwright, dir, sub));
  86. }
  87. }
  88. }
  89. return candidates.find((path) => existsSync(path));
  90. }
  91. async function main() {
  92. const options = parse(process.argv.slice(2));
  93. if (options.help || !options.target) {
  94. usage();
  95. process.exit(options.help ? 0 : 1);
  96. }
  97. const url = /^https?:|^file:/.test(options.target) ? options.target : pathToFileURL(resolve(options.target)).href;
  98. const out = resolve(options.out ?? "capture.png");
  99. const binary = chromePath();
  100. if (!binary) {
  101. console.error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium binary.");
  102. process.exit(1);
  103. }
  104. const profile = mkdtempSync(join(tmpdir(), "iso-capture-"));
  105. const chrome = spawn(binary, [
  106. "--headless=new",
  107. "--remote-debugging-port=0",
  108. `--user-data-dir=${profile}`,
  109. "--no-first-run",
  110. "--no-default-browser-check",
  111. "--hide-scrollbars",
  112. "--allow-file-access-from-files",
  113. "--enable-unsafe-swiftshader",
  114. "--ignore-gpu-blocklist",
  115. "about:blank",
  116. ]);
  117. const port = await new Promise((done, fail) => {
  118. let text = "";
  119. const timer = setTimeout(() => fail(new Error("Chrome did not start")), 20000);
  120. chrome.stderr.on("data", (chunk) => {
  121. text += chunk;
  122. const match = text.match(/DevTools listening on ws:\/\/[^:]+:(\d+)\//);
  123. if (match) {
  124. clearTimeout(timer);
  125. done(Number(match[1]));
  126. }
  127. });
  128. });
  129. const finish = (code) => {
  130. chrome.kill("SIGKILL");
  131. try {
  132. rmSync(profile, { recursive: true, force: true });
  133. } catch {}
  134. process.exit(code);
  135. };
  136. try {
  137. const target = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
  138. const socket = new WebSocket(target.webSocketDebuggerUrl);
  139. let id = 0;
  140. const pending = new Map();
  141. const problems = [];
  142. socket.onmessage = (message) => {
  143. const data = JSON.parse(message.data);
  144. if (data.id && pending.has(data.id)) {
  145. pending.get(data.id)(data);
  146. pending.delete(data.id);
  147. } else if (data.method === "Runtime.consoleAPICalled" && (data.params.type === "error" || data.params.type === "warning")) {
  148. problems.push(`console.${data.params.type}: ${data.params.args.map((arg) => arg.value ?? arg.description ?? "").join(" ").slice(0, 400)}`);
  149. } else if (data.method === "Runtime.exceptionThrown") {
  150. const detail = data.params.exceptionDetails;
  151. problems.push(`exception: ${detail.exception?.description ?? detail.text}`.slice(0, 600));
  152. }
  153. };
  154. await new Promise((done) => (socket.onopen = done));
  155. const send = (method, params = {}) =>
  156. new Promise((done) => {
  157. const call = ++id;
  158. pending.set(call, done);
  159. socket.send(JSON.stringify({ id: call, method, params }));
  160. });
  161. const evaluate = async (expression) => (await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true })).result?.result?.value;
  162. const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
  163. await send("Runtime.enable");
  164. await send("Page.enable");
  165. const features = [];
  166. if (options.reduced) features.push({ name: "prefers-reduced-motion", value: "reduce" });
  167. if (options.theme) features.push({ name: "prefers-color-scheme", value: options.theme });
  168. if (features.length) await send("Emulation.setEmulatedMedia", { features });
  169. await send("Emulation.setDeviceMetricsOverride", { width: options.width, height: options.height, deviceScaleFactor: options.scale, mobile: options.width < 600 });
  170. await send("Page.navigate", { url });
  171. await sleep(Math.min(options.wait, 1500));
  172. await evaluate(`(async()=>{const h=document.documentElement.scrollHeight;for(let y=0;y<h;y+=400){scrollTo(0,y);await new Promise(r=>setTimeout(r,60))}scrollTo(0,0)})()`);
  173. await sleep(Math.max(0, options.wait - 1500));
  174. const select = options.select ?? ".iso-plate";
  175. const boxOf = async () =>
  176. evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(select)})||document.querySelector("svg")||document.body;el.scrollIntoView({block:"center"});const r=el.getBoundingClientRect();return {x:r.left+scrollX,y:r.top+scrollY,w:r.width,h:r.height,vx:r.left,vy:r.top}})()`);
  177. let box = await boxOf();
  178. if (options.hover) {
  179. await sleep(300);
  180. box = await boxOf();
  181. const x = box.vx + box.w * options.hover[0];
  182. const y = box.vy + box.h * options.hover[1];
  183. await send("Input.dispatchMouseEvent", { type: "mouseMoved", x: box.vx + 2, y: box.vy + 2 });
  184. await sleep(60);
  185. for (let step = 1; step <= 12; step++) {
  186. await send("Input.dispatchMouseEvent", { type: "mouseMoved", x: box.vx + 2 + ((x - box.vx - 2) * step) / 12, y: box.vy + 2 + ((y - box.vy - 2) * step) / 12 });
  187. await sleep(30);
  188. }
  189. await sleep(1200);
  190. }
  191. if (options.keys) {
  192. await evaluate(`(()=>{const f=document.querySelector('[tabindex="0"]');if(f)f.focus()})()`);
  193. const named = { " ": "Space", "-": "Minus", "=": "Equal", ",": "Comma", ".": "Period", "/": "Slash", ";": "Semicolon", "'": "Quote", "[": "BracketLeft", "]": "BracketRight", "\\": "Backslash", "`": "Backquote" };
  194. for (const entry of options.keys) {
  195. if (entry === "Tab") continue;
  196. const key = entry === "Comma" ? "," : entry === "Space" ? " " : entry;
  197. const code = named[key] ?? (/^[0-9]$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key);
  198. await send("Input.dispatchKeyEvent", { type: "keyDown", key, code, text: key.length === 1 ? key : undefined, windowsVirtualKeyCode: key === " " ? 32 : 0 });
  199. await send("Input.dispatchKeyEvent", { type: "keyUp", key, code });
  200. await sleep(250);
  201. }
  202. await sleep(1200);
  203. }
  204. const shoot = async (path, clip, scale) => {
  205. const shot = await send("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, clip: { ...clip, scale } });
  206. writeFileSync(path, Buffer.from(shot.result.data, "base64"));
  207. };
  208. const clipOf = () => {
  209. if (!options.zoom) return { clip: { x: box.x - 6, y: box.y - 6, width: box.w + 12, height: box.h + 12 }, scale: 1 };
  210. const [zx, zy, zw, zh] = options.zoom;
  211. return { clip: { x: box.x + zx, y: box.y + zy, width: zw, height: zh }, scale: options.zoomScale / options.scale };
  212. };
  213. const first = clipOf();
  214. await shoot(out, first.clip, first.scale);
  215. const shotAt = Date.now();
  216. const readouts = [];
  217. for (const delay of [...options.times].sort((a, b) => a - b)) {
  218. await sleep(Math.max(0, shotAt + delay - Date.now()));
  219. const next = clipOf();
  220. await shoot(out.replace(/\.png$/, `-${delay}.png`), next.clip, next.scale);
  221. readouts.push(`+${delay}ms "${await evaluate(`(document.querySelector("[data-readout]")||{}).textContent||""`)}"`);
  222. }
  223. const sideways = await evaluate(`document.documentElement.scrollWidth > innerWidth + 1`);
  224. const readout = await evaluate(`(document.querySelector("[data-readout]")||{}).textContent||""`);
  225. console.log(`saved ${out}`);
  226. console.log(`clip ${Math.round(box.x)},${Math.round(box.y)} ${Math.round(box.w)}x${Math.round(box.h)} · readout "${readout}" · scrolls sideways: ${sideways ? "YES" : "no"}`);
  227. if (readouts.length) console.log(`readout over time: ${readouts.join(" · ")}`);
  228. console.log(problems.length ? problems.join("\n") : "console: clean");
  229. socket.close();
  230. finish(0);
  231. } catch (error) {
  232. console.error(error);
  233. finish(1);
  234. }
  235. }