Files
pipelines/web/test/browser.mjs
T

351 lines
13 KiB
JavaScript

// A zero-dependency Chrome DevTools Protocol driver for verifying the web client
// in a real browser.
//
// It launches the installed Google Chrome in headless mode and talks to it over
// the DevTools WebSocket, using only Node's built-in `fetch` and global
// `WebSocket` (Node 22+). There is deliberately no npm dependency: the UI
// verification a pipeline stage runs must work from a clean checkout with no
// install step and no network.
//
// Usage:
// const browser = await launchChrome(); // { port, close() }
// const page = await browser.openPage(url); // navigate + await load
// await page.fill("#url", "ws://127.0.0.1:8090/connect");
// await page.click("#connectBtn");
// await page.waitForSelector(".row-title");
// await page.screenshot("/path/to/out.png");
// await page.close(); await browser.close();
//
// Chrome path: CHROME_PATH, else the macOS app bundle, else `google-chrome`.
import { spawn } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
].filter(Boolean);
async function resolveChrome() {
for (const candidate of CHROME_CANDIDATES) {
try {
await readFile(candidate);
return candidate;
} catch {
// try the next candidate
}
}
throw new Error(
"no Chrome/Chromium found; set CHROME_PATH to a browser binary to run UI verification",
);
}
/** Poll `check` until it returns a truthy value or the timeout elapses. */
export async function eventually(check, { timeout = 20000, interval = 100, what = "condition" } = {}) {
const deadline = Date.now() + timeout;
let lastError = null;
while (Date.now() < deadline) {
try {
const value = await check();
if (value) return value;
} catch (error) {
lastError = error;
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
throw new Error(`timed out waiting for ${what}${lastError ? `: ${lastError.message}` : ""}`);
}
/** One CDP connection: id-matched commands plus method listeners. */
class Cdp {
constructor(ws) {
this.ws = ws;
this.nextId = 0;
this.pending = new Map();
this.listeners = new Map();
ws.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (message.id != null) {
const entry = this.pending.get(message.id);
this.pending.delete(message.id);
if (!entry) return;
if (message.error) entry.reject(new Error(`${message.error.message}`));
else entry.resolve(message.result ?? {});
return;
}
for (const listener of this.listeners.get(message.method) ?? []) listener(message);
});
}
opened() {
if (this.ws.readyState === 1) return Promise.resolve();
return new Promise((resolve, reject) => {
this.ws.addEventListener("open", () => resolve(), { once: true });
this.ws.addEventListener("error", () => reject(new Error("devtools websocket failed")), {
once: true,
});
});
}
on(method, listener) {
const list = this.listeners.get(method) ?? [];
list.push(listener);
this.listeners.set(method, list);
}
send(method, params = {}, sessionId) {
const id = ++this.nextId;
const frame = { id, method, params };
if (sessionId) frame.sessionId = sessionId;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject });
this.ws.send(JSON.stringify(frame));
});
}
close() {
try {
this.ws.close();
} catch {
// already gone
}
}
}
/**
* Launch headless Chrome with a fresh profile and remote debugging on an
* ephemeral port (read back from the profile's `DevToolsActivePort`).
*/
export async function launchChrome({ width = 1440, height = 900, chromePath } = {}) {
const chrome = chromePath ?? (await resolveChrome());
const profile = await mkdtemp(join(tmpdir(), "pipelines-web-cdp-"));
const child = spawn(
chrome,
[
"--headless=new",
"--disable-gpu",
"--no-first-run",
"--no-default-browser-check",
"--disable-extensions",
"--hide-scrollbars",
"--mute-audio",
`--user-data-dir=${profile}`,
"--remote-debugging-port=0",
`--window-size=${width},${height}`,
"about:blank",
],
{ stdio: ["ignore", "ignore", "pipe"] },
);
let stderr = "";
child.stderr.on("data", (chunk) => {
stderr += chunk.toString();
});
const port = await eventually(
async () => {
if (child.exitCode != null) {
throw new Error(`chrome exited early (${child.exitCode}): ${stderr.trim().slice(-400)}`);
}
const text = await readFile(join(profile, "DevToolsActivePort"), "utf8").catch(() => "");
const first = text.split("\n")[0]?.trim();
return first ? Number(first) : 0;
},
{ what: "chrome devtools port", timeout: 30000 },
);
let cdp = null;
const openCdp = async () => {
if (cdp) return cdp;
const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
const ws = new WebSocket(version.webSocketDebuggerUrl);
cdp = new Cdp(ws);
await cdp.opened();
return cdp;
};
return {
port,
chrome,
async openPage(url, { width: w = width, height: h = height } = {}) {
const conn = await openCdp();
const { targetId } = await conn.send("Target.createTarget", { url: "about:blank" });
const { sessionId } = await conn.send("Target.attachToTarget", { targetId, flatten: true });
const session = (method, params) => conn.send(method, params, sessionId);
await session("Page.enable");
await session("Runtime.enable");
await session("Emulation.setDeviceMetricsOverride", {
width: w,
height: h,
deviceScaleFactor: 1,
mobile: false,
});
const api = {
targetId,
/** Emulate pointer capability only; this is not an OS keyboard test. */
async emulateTouch(enabled = true) {
await session("Emulation.setTouchEmulationEnabled", { enabled, maxTouchPoints: 1 });
},
/** Resize the emulated viewport at the driver's fixed device scale. */
async resize(width, height) {
await session("Emulation.setDeviceMetricsOverride", {
width,
height,
deviceScaleFactor: 1,
mobile: false,
});
},
async evaluate(expression) {
const result = await session("Runtime.evaluate", {
expression,
awaitPromise: true,
returnByValue: true,
});
if (result.exceptionDetails) {
const text =
result.exceptionDetails.exception?.description ??
result.exceptionDetails.text ??
"evaluation failed";
throw new Error(text);
}
return result.result?.value;
},
async goto(nextUrl) {
await session("Page.navigate", { url: nextUrl });
await eventually(
async () => (await api.evaluate("document.readyState")) === "complete",
{ what: `load of ${nextUrl}` },
);
},
/**
* Install a script that runs in every document created from now on, before
* the page's own scripts — the CDP hook a UI check uses to wrap a global
* (for example to record the page's WebSocket) before the app boots.
*/
async addInitScript(source) {
await session("Page.addScriptToEvaluateOnNewDocument", { source });
},
/** Set an input's value and fire input/change so the app sees it. */
async fill(selector, value) {
const ok = await api.evaluate(`(() => {
const el = document.querySelector(${JSON.stringify(selector)});
if (!el) return false;
el.focus();
el.value = ${JSON.stringify(value)};
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
return true;
})()`);
if (!ok) throw new Error(`fill: no element for ${selector}`);
},
async rect(selector) {
return api.evaluate(`(() => {
const el = document.querySelector(${JSON.stringify(selector)});
if (!el) return null;
// CSS smooth scrolling is asynchronous; measuring immediately after
// it can click outside the viewport instead of the target control.
el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
const r = el.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
})()`);
},
/** A real mouse click at the element's centre. */
async click(selector) {
const point = await api.rect(selector);
if (!point) throw new Error(`click: no element for ${selector}`);
const base = { x: point.x, y: point.y, button: "left", clickCount: 1 };
await session("Input.dispatchMouseEvent", { type: "mouseMoved", x: point.x, y: point.y });
await session("Input.dispatchMouseEvent", { type: "mousePressed", ...base });
await session("Input.dispatchMouseEvent", { type: "mouseReleased", ...base });
},
/** Click the first element matching `selector` whose text contains `text`. */
async clickText(selector, text) {
const found = await api.evaluate(`(() => {
const wanted = ${JSON.stringify(text)};
const all = [...document.querySelectorAll(${JSON.stringify(selector)})];
const el = all.find((node) => (node.textContent ?? "").includes(wanted));
if (!el) return false;
el.scrollIntoView({ block: "center", behavior: "instant" });
el.setAttribute("data-test-click", "1");
return true;
})()`);
if (!found) throw new Error(`clickText: no ${selector} containing ${JSON.stringify(text)}`);
await api.click("[data-test-click='1']");
await api.evaluate(
`document.querySelector("[data-test-click='1']")?.removeAttribute("data-test-click")`,
);
},
async waitForSelector(selector, { timeout = 20000 } = {}) {
return eventually(() => api.evaluate(`!!document.querySelector(${JSON.stringify(selector)})`), {
timeout,
what: selector,
});
},
async waitForText(text, { timeout = 20000 } = {}) {
return eventually(
() => api.evaluate(`document.body.innerText.includes(${JSON.stringify(text)})`),
{ timeout, what: `text ${JSON.stringify(text)}` },
);
},
/**
* Dispatch one real key event pair (Input.dispatchKeyEvent), so the page
* sees the same trusted Tab/Escape/Enter a keyboard operator produces.
*/
async pressKey(key, { shift = false } = {}) {
const keys = {
Tab: { code: "Tab", windowsVirtualKeyCode: 9 },
Escape: { code: "Escape", windowsVirtualKeyCode: 27 },
Enter: { code: "Enter", windowsVirtualKeyCode: 13, text: "\r", unmodifiedText: "\r" },
" ": { code: "Space", windowsVirtualKeyCode: 32, text: " ", unmodifiedText: " " },
ArrowDown: { code: "ArrowDown", windowsVirtualKeyCode: 40 },
ArrowUp: { code: "ArrowUp", windowsVirtualKeyCode: 38 },
};
const info = keys[key] ?? { code: key, windowsVirtualKeyCode: 0 };
const base = {
key,
code: info.code,
windowsVirtualKeyCode: info.windowsVirtualKeyCode,
nativeVirtualKeyCode: info.windowsVirtualKeyCode,
modifiers: shift ? 8 : 0,
...(info.text ? { text: info.text, unmodifiedText: info.unmodifiedText } : {}),
};
await session("Input.dispatchKeyEvent", { type: "keyDown", ...base });
await session("Input.dispatchKeyEvent", { type: "keyUp", ...base });
},
async text() {
return api.evaluate("document.body.innerText");
},
async screenshot(path) {
const { data } = await session("Page.captureScreenshot", { format: "png" });
await writeFile(path, Buffer.from(data, "base64"));
return path;
},
async close() {
await conn.send("Target.closeTarget", { targetId }).catch(() => {});
},
};
if (url) await api.goto(url);
return api;
},
async close() {
try {
await fetch(`http://127.0.0.1:${port}/json/close/${""}`).catch(() => {});
} catch {
// ignore
}
cdp?.close();
child.kill("SIGTERM");
await eventually(async () => child.exitCode != null || child.signalCode != null, {
timeout: 5000,
what: "chrome exit",
}).catch(() => {});
await rm(profile, { recursive: true, force: true }).catch(() => {});
},
};
}