interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / docs / design / tools / shoot.mjs

136 lines · 5195 bytes Raw Blame History
1// shoot.mjs -- drives a headless Chrome over its DevTools port, with no packages: loads a page at a size,
2// optionally waits until a page expression is true, prints that expression's value, and saves a screenshot.
3// Used for the boot reference's frame-time receipts and the screen mockups' screenshots. Dev tool only:
4// nothing in AienOS runs it.
5//
6// node docs/design/tools/shoot.mjs URL [--size 1920x1080] [--out shot.png] [--wait EXPR] [--result EXPR]
7// [--timeout-ms 60000] [--chrome PATH] [--gpu]
8//
9// Exit 0 on success, 1 if the page never met --wait, 2 on a usage or launch error.
10
11import { spawn } from "node:child_process";
12import { mkdtempSync, writeFileSync, existsSync, readdirSync } from "node:fs";
13import { tmpdir, homedir } from "node:os";
14import { join } from "node:path";
15
16const args = process.argv.slice(2);
17const opt = (name, dflt) => {
18 const i = args.indexOf(name);
19 return i >= 0 ? args[i + 1] : dflt;
20};
21const url = args[0];
22if (!url || url.startsWith("--")) {
23 console.error("usage: shoot.mjs URL [--size WxH] [--out FILE] [--wait EXPR] [--result EXPR] [--timeout-ms N]");
24 process.exit(2);
25}
26const [width, height] = opt("--size", "1920x1080").split("x").map(Number);
27const out = opt("--out", null);
28const waitExpr = opt("--wait", null);
29const resultExpr = opt("--result", null);
30const timeoutMs = Number(opt("--timeout-ms", "60000"));
31
32function findChrome() {
33 const given = opt("--chrome", null);
34 if (given) return given;
35 const shell = join(homedir(), ".cache/ms-playwright");
36 if (existsSync(shell)) {
37 for (const d of readdirSync(shell).filter((d) => d.startsWith("chromium_headless_shell"))) {
38 for (const sub of readdirSync(join(shell, d))) {
39 const p = join(shell, d, sub, "chrome-headless-shell");
40 if (existsSync(p)) return p;
41 }
42 }
43 }
44 return "google-chrome";
45}
46
47const profile = mkdtempSync(join(tmpdir(), "shoot-"));
48const flags = [
49 "--no-sandbox",
50 "--no-first-run",
51 "--hide-scrollbars",
52 "--autoplay-policy=no-user-gesture-required",
53 `--user-data-dir=${profile}`,
54 "--remote-debugging-port=0",
55 `--window-size=${width},${height}`,
56];
57if (args.includes("--gpu")) flags.push("--enable-gpu", "--use-angle=gl");
58// extra Chrome flags, space separated, e.g. SHOOT_FLAGS="--use-angle=vulkan"
59flags.push(...(process.env.SHOOT_FLAGS || "").split(" ").filter(Boolean));
60const chrome = spawn(findChrome(), [...flags, "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
61
62const port = await new Promise((resolve, reject) => {
63 let buf = "";
64 const timer = setTimeout(() => reject(new Error("chrome did not open its DevTools port")), 20000);
65 chrome.stderr.on("data", (d) => {
66 buf += d;
67 const m = buf.match(/DevTools listening on ws:\/\/[^:]+:(\d+)\//);
68 if (m) {
69 clearTimeout(timer);
70 resolve(Number(m[1]));
71 }
72 });
73 chrome.on("exit", () => reject(new Error("chrome exited before opening its DevTools port")));
74}).catch((e) => {
75 console.error(`shoot: ${e.message}`);
76 process.exit(2);
77});
78
79const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
80const page = targets.find((t) => t.type === "page");
81const ws = new WebSocket(page.webSocketDebuggerUrl);
82await new Promise((r) => ws.addEventListener("open", r, { once: true }));
83let nextId = 1;
84const pending = new Map();
85ws.addEventListener("message", (ev) => {
86 const msg = JSON.parse(ev.data);
87 if (msg.id && pending.has(msg.id)) {
88 pending.get(msg.id)(msg);
89 pending.delete(msg.id);
90 }
91});
92const send = (method, params = {}) =>
93 new Promise((resolve, reject) => {
94 const id = nextId++;
95 pending.set(id, (m) => (m.error ? reject(new Error(`${method}: ${m.error.message}`)) : resolve(m.result)));
96 ws.send(JSON.stringify({ id, method, params }));
97 });
98const evaluate = async (expr) =>
99 (await send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise: true })).result.value;
100
101let code = 0;
102try {
103 await send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: width < 600 });
104 await send("Page.enable");
105 await send("Page.navigate", { url });
106 const start = Date.now();
107 // wait for the document, then for the page's own condition
108 while ((await evaluate("document.readyState")) !== "complete") await new Promise((r) => setTimeout(r, 50));
109 if (waitExpr) {
110 while (!(await evaluate(`Boolean(${waitExpr})`))) {
111 if (Date.now() - start > timeoutMs) {
112 console.error(`shoot: ${waitExpr} still false after ${timeoutMs} ms`);
113 code = 1;
114 break;
115 }
116 await new Promise((r) => setTimeout(r, 100));
117 }
118 } else {
119 await new Promise((r) => setTimeout(r, 400)); // let fonts and the first frame settle
120 }
121 if (resultExpr) {
122 const v = await evaluate(resultExpr);
123 console.log(typeof v === "string" ? v : JSON.stringify(v, null, 2));
124 }
125 if (out) {
126 const shot = await send("Page.captureScreenshot", { format: "png" });
127 writeFileSync(out, Buffer.from(shot.data, "base64"));
128 console.error(`shoot: wrote ${out} (${width}x${height})`);
129 }
130} catch (e) {
131 console.error(`shoot: ${e.message}`);
132 code = 2;
133}
134ws.close();
135chrome.kill();
136process.exit(code);