repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/scripts/phase1-smoke.mjs

Raw
File outline
#!/usr/bin/env node
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { chromium } from "@playwright/test";
import { createUiRuntime } from "../runtime.js";

const args = new Set(process.argv.slice(2));
const noBrowser = args.has("--no-browser");
const outDir = resolve(process.cwd(), ".pi/tmp/ui-phase1-smoke");
const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";
mkdirSync(outDir, { recursive: true });

const runtime = await createUiRuntime({
	sessionLabel: "ui: phase1-smoke",
	address: "127.0.0.1",
	cwd: process.cwd(),
	openBrowser: false,
});

try {
	const status = runtime.status();
	if (!status.url) throw new Error("UI runtime did not expose a URL");
	const url = status.url;
	const parsed = new URL(url);

	const tokenless = await fetch(`${parsed.origin}/api/status`);
	if (tokenless.status !== 401)
		throw new Error(
			`Expected tokenless /api/status 401, got ${tokenless.status}`,
		);

	const shell = await fetch(url);
	if (!shell.ok) throw new Error(`Bare root shell failed: ${shell.status}`);
	const cookie = shell.headers.get("set-cookie") ?? "";
	const authorized = await fetch(`${parsed.origin}/api/status`, {
		headers: { cookie },
	});
	if (!authorized.ok)
		throw new Error(`Authorized /api/status failed: ${authorized.status}`);

	let browserText = "skipped";
	if (!noBrowser) browserText = await verifyBrowser(url);

	const summary = {
		url: redactUrl(url),
		state: status.state,
		tokenlessStatus: tokenless.status,
		authorizedStatus: authorized.status,
		browserText,
	};
	const summaryPath = resolve(outDir, "summary.json");
	writeFileSync(summaryPath, `${JSON.stringify(summary, null, "\t")}\n`);
	console.log(`url: ${summary.url}`);
	console.log(`summary: ${summaryPath}`);
} finally {
	await runtime.stop("phase1 smoke complete");
}

async function verifyBrowser(url) {
	const browser = await chromium.launch({
		headless: true,
		executablePath: existsSync(chromePath) ? chromePath : undefined,
	});
	try {
		const page = await browser.newPage();
		await page.goto(url);
		await page.waitForSelector("#ui-shell");
		await page.waitForSelector("#ui-composer");
		return await page.locator("#ui-progress").innerText();
	} finally {
		await browser.close();
	}
}

function redactUrl(value) {
	const tokenParam = "token" + "=";
	return value.replace(
		new RegExp(`${tokenParam}[A-Za-z0-9_-]+`),
		`${tokenParam}[redacted]`,
	);
}