Files
vesti/scripts/ui-probe.mjs
T

90 lines
4.6 KiB
JavaScript

// CDP-проба страницы VESTI: геометрия, JS-исключения, скриншот — без логина в прод.
//
// Зачем: проверка авторизованных страниц (candidates/selected/plan) требует cookie, а логин
// через /login сбрасывает сессию пользователя (VESTI_WEB_SESSION перезаписывается). Поэтому
// поднимаем второй экземпляр приложения и заходим в него готовой кукой:
//
// VESTI_WEB_SESSION=probe .venv/bin/uvicorn web.app:app --port 8411 --host 127.0.0.1 &
// node scripts/ui-probe.mjs "http://127.0.0.1:8411/selected" 1440 vesti_session probe /tmp/x.png
//
// Аргументы: <url> [width] [cookieName] [cookieValue] [outPng] [evalExpr]
// Зависимости: только node (>=21, встроенный WebSocket) и chromium-browser в системе.
import { spawn } from "node:child_process";
import { writeFileSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const [url, width = "1440", cookieName = "vesti_session", cookieValue = "probe",
outPng = "/tmp/probe.png", evalExpr = ""] = process.argv.slice(2);
const port = 9333 + Math.floor(Math.random() * 200);
const chrome = spawn("/usr/bin/chromium-browser", [
"--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage",
`--remote-debugging-port=${port}`, `--user-data-dir=${mkdtempSync(join(tmpdir(), "cdp-"))}`,
`--window-size=${width},1000`, "about:blank",
], { stdio: "ignore" });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const wsUrl = await (async () => {
for (let i = 0; i < 60; i++) {
try {
const tabs = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = tabs.find((t) => t.type === "page");
if (page?.webSocketDebuggerUrl) return page.webSocketDebuggerUrl;
} catch {}
await sleep(250);
}
throw new Error("CDP не поднялся");
})();
const ws = new WebSocket(wsUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
let id = 0;
const pending = new Map();
const events = [];
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
else if (msg.method) events.push(msg);
};
const send = (method, params = {}) => new Promise((res) => {
const mid = ++id;
pending.set(mid, res);
ws.send(JSON.stringify({ id: mid, method, params }));
});
await send("Page.enable");
await send("Network.enable");
await send("Runtime.enable");
await send("Emulation.setDeviceMetricsOverride", {
width: Number(width), height: 1000, deviceScaleFactor: 1, mobile: Number(width) < 600,
});
await send("Network.setCookie", { name: cookieName, value: cookieValue, domain: "127.0.0.1", path: "/" });
await send("Page.navigate", { url });
await sleep(2500);
const defaultEval = `(() => {
const box = (sel) => { const e = document.querySelector(sel); if (!e) return null; const r = e.getBoundingClientRect(); return {left: Math.round(r.left), right: Math.round(r.right), top: Math.round(r.top), bottom: Math.round(r.bottom), w: Math.round(r.width), h: Math.round(r.height)}; };
return {
title: document.title, url: location.href,
scrollWidth: document.documentElement.scrollWidth, innerWidth: window.innerWidth,
horizScroll: document.documentElement.scrollWidth > window.innerWidth + 1,
panels: { list: box('#list-panel'), detail: box('#detail-panel'), sources: box('#sources-panel') },
bodyBg: getComputedStyle(document.body).backgroundColor,
extLinks: [...document.querySelectorAll('link[href],script[src]')].map(e => e.href || e.src).filter(u => /^https?:\\/\\//.test(u) && !u.includes('127.0.0.1')),
styleHrefs: [...document.querySelectorAll('link[rel=stylesheet]')].map(l => l.getAttribute('href')),
};
})()`;
const ev = await send("Runtime.evaluate", { expression: evalExpr || defaultEval, returnByValue: true, awaitPromise: true });
const value = ev.result?.result?.value ?? ev.result;
const exceptions = events
.filter((e) => e.method === "Runtime.exceptionThrown")
.map((e) => (e.params.exceptionDetails.exception?.description || e.params.exceptionDetails.text || "").split("\n")[0]);
const shot = await send("Page.captureScreenshot", { format: "png", captureBeyondViewport: true });
if (shot.result?.data) writeFileSync(outPng, Buffer.from(shot.result.data, "base64"));
console.log(JSON.stringify({ ...(typeof value === "object" && value ? value : { value }), exceptions, screenshot: outPng }, null, 2));
ws.close();
chrome.kill();
process.exit(0);