~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/socialweb-computer-watch

The socialweb.computer market's live topology from Jetstreams and relays, deduplicated; capture and replay

0
0
main
82 lines · 5.5 KB Raw History
// The page in headless Chrome over CDP: console errors, live sources, dedup counts, topology, a capture replay.
//   node test/page.mjs <url> [--wait 40] [--capture file.ndjson] [--filter text] [--shot out.png]
// Exits 1 on any console error or exception. CHROME: the Chrome binary.
import { spawn } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

const args = process.argv.slice(2);
const flag = (n, d) => (args.includes(n) ? args.splice(args.indexOf(n), 2)[1] : d);
const wait = Number(flag("--wait", 40));
const capture = flag("--capture");
const filter = flag("--filter");
const shot = flag("--shot");
const url = args[0] ?? "http://127.0.0.1:8799/";
const chrome = process.env.CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
const proc = spawn(chrome, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${mkdtempSync(join(tmpdir(), "swc-watch-"))}`, "--window-size=1600,1000", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
const wsUrl = await new Promise((ok) => proc.stderr.on("data", (d) => /ws:\/\/\S+/.test(d) && ok(String(d).match(/ws:\/\/\S+/)[0])));
const browser = new WebSocket(wsUrl);
await new Promise((ok) => (browser.onopen = ok));
let id = 0;
const pending = new Map();
const errors = [];
const send = (method, params = {}, sessionId) => new Promise((ok, no) => {
	const i = ++id;
	pending.set(i, { ok, no });
	browser.send(JSON.stringify({ id: i, method, params, sessionId }));
});
browser.onmessage = ({ data }) => {
	const m = JSON.parse(data);
	if (m.id) return m.error ? pending.get(m.id).no(new Error(m.error.message)) : pending.get(m.id).ok(m.result);
	if (m.method === "Runtime.exceptionThrown") errors.push(`exception: ${m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text}`);
	if (m.method === "Runtime.consoleAPICalled" && m.params.type === "error") errors.push(`console.error: ${m.params.args.map((a) => a.value ?? a.description).join(" ")}`);
	if (m.method === "Log.entryAdded" && m.params.entry.level === "error") errors.push(`log: ${m.params.entry.text} ${m.params.entry.url ?? ""}`);
	if (m.method === "Target.attachedToTarget" && m.params.targetInfo.type === "worker") {
		const s = m.params.sessionId;
		send("Runtime.enable", {}, s).catch(() => {});
		send("Runtime.runIfWaitingForDebugger", {}, s).catch(() => {});
	}
};
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
const { sessionId: s } = await send("Target.attachToTarget", { targetId, flatten: true });
for (const d of ["Runtime", "Log", "Page", "DOM"]) await send(`${d}.enable`, {}, s);
await send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, s);
await send("Page.navigate", { url }, s);
const evaluate = async (expression) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, s)).result.value;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const state = () => evaluate(`({ totals: document.getElementById("totals").textContent, sources: [...document.querySelectorAll("#stats tr")].map((tr) => [tr.querySelector(".dot")?.dataset.state, ...[...tr.cells].map((c) => c.textContent)].join(" ")), nodes: [...document.querySelectorAll("g.node")].map((g) => g.dataset.type + ":" + (g.dataset.role || g.dataset.status) + ":" + g.querySelector("text.label").textContent), links: document.querySelectorAll("g.link").length, log: document.querySelectorAll("#log li").length })`);
for (let t = 0; t < wait; t += 10) {
	await sleep(10_000);
	const st = await state();
	console.log(`t=${t + 10}s ${st.totals} | links ${st.links} | log ${st.log}`);
}
if (filter) {
	await evaluate(`(() => { const f = document.getElementById("filter"); f.value = ${JSON.stringify(filter)}; f.dispatchEvent(new Event("input")); })()`);
	await sleep(3000);
}
const live = await state();
console.log(JSON.stringify({ sources: live.sources, nodes: live.nodes.length, sample: live.nodes.slice(0, 40) }, null, 1));
if (capture) {
	const { root } = await send("DOM.getDocument", {}, s);
	const { nodeId } = await send("DOM.querySelector", { nodeId: root.nodeId, selector: "#file" }, s);
	await send("DOM.setFileInputFiles", { nodeId, files: [resolve(capture)] }, s);
	await sleep(5000);
	const r = await state();
	const info = await evaluate(`document.getElementById("replay-info").textContent + " | " + document.getElementById("clock").textContent`);
	console.log(JSON.stringify({ replay: info, totals: r.totals, sources: r.sources, nodes: r.nodes.length, links: r.links }, null, 1));
	await evaluate(`(() => { document.getElementById("speed").value = "600"; document.getElementById("play").click(); })()`);
	await sleep(4000);
	console.log("after play:", await evaluate(`document.getElementById("clock").textContent + " | " + document.getElementById("totals").textContent`));
	await evaluate(`(() => { const s = document.getElementById("scrub"); s.value = String(Math.round(s.max / 2)); s.dispatchEvent(new Event("input")); })()`);
	await sleep(2000);
	console.log("scrub to half:", await evaluate(`document.getElementById("clock").textContent + " | " + document.getElementById("totals").textContent`));
}
if (shot) {
	await evaluate(`document.getElementById("fit").click()`);
	await sleep(1500);
	writeFileSync(shot, Buffer.from((await send("Page.captureScreenshot", { format: "png" }, s)).data, "base64"));
}
console.log(errors.length ? `ERRORS (${errors.length}):\n${errors.join("\n")}` : "console errors: 0");
proc.kill();
process.exit(errors.length ? 1 : 0);