Something went wrong. Try again.
Automations and webhooks for the AT Protocol airglow.run
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226// Screenshots of the UI without the app's database, PDS or a sign-in: each// state of an `app/previews/<name>.preview.tsx` file is rendered on the// server, as a page would, with the app's styles and fonts, then shot in// headless Chromium. Islands are not hydrated: the shots show the server// markup, which is what a page shows before its scripts run.//// pnpm preview:ui every preview, light and dark// pnpm preview:ui header --theme dark one preview, one theme// pnpm preview:ui header --state menu-two-accounts// pnpm preview:ui --list previews and their states// pnpm preview:ui header --serve print the pages' URLs instead, to open in a browser//// The PNGs go to `.ui-preview/<name>/<state>.<theme>.png` (gitignored).// Chromium comes from `pnpm exec playwright install --only-shell chromium`.import { mkdirSync, readdirSync, rmSync } from "node:fs";import { createServer as createHttpServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { join, relative, resolve } from "node:path";import { parseArgs } from "node:util";import { chromium, type Browser } from "playwright";import { createServer } from "vite";import type { Preview } from "../../app/previews/preview.ts";import { UI_PREVIEW_MODE } from "./mode.ts";import type { Theme } from "./render.tsx";
const ROOT = resolve(import.meta.dirname, "../..");const PREVIEWS = "app/previews";const SUFFIX = ".preview.tsx";const DEFAULT_VIEWPORT = { width: 1024, height: 640 };
const OUT = ".ui-preview";
const USAGE = `usage: pnpm preview:ui [name ...] [--state <name>] [--theme light|dark|both] [--list] [--serve]`;
function fail(message: string): never { console.error(message); process.exit(2);}
const { values, positionals } = parseArgs({ options: { state: { type: "string" }, theme: { type: "string", default: "both" }, list: { type: "boolean" }, serve: { type: "boolean" }, help: { type: "boolean", short: "h" }, }, allowPositionals: true,});if (values.help) { console.log(USAGE); process.exit(0);}const themes: Theme[] = values.theme === "both" ? ["light", "dark"] : values.theme === "light" || values.theme === "dark" ? [values.theme] : fail(`--theme must be light, dark or both\n${USAGE}`);
const available = readdirSync(join(ROOT, PREVIEWS)) .filter((f) => f.endsWith(SUFFIX)) .map((f) => f.slice(0, -SUFFIX.length)) .sort();const names = positionals.length ? positionals.map((p) => { const name = p.replace(/^.*\//, "").replace(SUFFIX, ""); if (!available.includes(name)) fail(`no preview "${p}": ${PREVIEWS}/ has ${available.join(", ") || "none"}`); return name; }) : available;if (!names.length) fail(`no previews in ${PREVIEWS}/`);
// The app's own Vite config in its ui-preview mode: its aliases, SSR externals,// vanilla-extract and devCss (which serves the styles a render loaded), without// what serves the app itself. Loading it also loads `.env`, when there is one.const vite = await createServer({ configFile: join(ROOT, "vite.config.ts"), mode: UI_PREVIEW_MODE, root: ROOT, appType: "custom", logLevel: "warn", server: { middlewareMode: true, hmr: false, ws: false },});
// lib/config.ts throws at import without its settings. The previews render// components, so the tests' placeholders are enough; a real .env wins. The// database is an unreachable one, so a render that queries fails loudly instead// of reading the tests' local database.process.env.DATABASE_URL ??= "postgres://preview:preview@127.0.0.1:1/preview";const testEnv = (vite.config as { test?: { env?: Record<string, string> } }).test?.env ?? {};for (const [key, value] of Object.entries(testEnv)) process.env[key] ??= value;
async function loadPreview(name: string): Promise<Preview> { const mod = (await vite.ssrLoadModule(`/${PREVIEWS}/${name}${SUFFIX}`)) as { default?: Preview }; if (!mod.default?.states?.length) throw new Error(`${PREVIEWS}/${name}${SUFFIX} has no default export with states`); return mod.default;}
const PAGE = /^\/__preview\/([^/]+)\/([^/]+)$/;const http: Server = createHttpServer((req, res) => { const url = new URL(req.url ?? "/", "http://127.0.0.1"); const match = PAGE.exec(url.pathname); if (!match) { vite.middlewares(req, res, () => { res.statusCode = 404; res.end(); }); return; } const [, name, state] = match as unknown as [string, string, string]; const theme: Theme = url.searchParams.get("theme") === "dark" ? "dark" : "light"; (async () => { const { renderState } = (await vite.ssrLoadModule( "/scripts/ui-preview/render.tsx", )) as typeof import("./render.tsx"); const html = await renderState(await loadPreview(name), state, theme); res.setHeader("content-type", "text/html; charset=utf-8"); res.end(html); })().catch((err: unknown) => { if (err instanceof Error) vite.ssrFixStacktrace(err); res.statusCode = 500; res.setHeader("content-type", "text/plain; charset=utf-8"); res.end(err instanceof Error ? (err.stack ?? err.message) : String(err)); });});await new Promise<void>((done) => http.listen(0, "127.0.0.1", done));const origin = `http://127.0.0.1:${(http.address() as AddressInfo).port}`;
/** The first lines of a stack: enough to find the error without the runner's frames. */const short = (text = "") => text.split("\n").slice(0, 8).join("\n");
async function close(browser?: Browser) { await browser?.close(); http.close(); await vite.close();}
const previews = new Map<string, Preview>();for (const name of names) { try { previews.set(name, await loadPreview(name)); } catch (err) { vite.ssrFixStacktrace(err as Error); console.error(`${name}: ${short((err as Error).stack ?? String(err))}`); process.exitCode = 1; }}const states = (p: Preview) => values.state ? p.states.filter((s) => s.name === values.state) : p.states;if (values.state && ![...previews.values()].some((p) => states(p).length)) fail(`no state "${values.state}" in ${names.join(", ")}`);
if (values.list || values.serve) { for (const [name, p] of previews) { console.log(`${name}: ${p.title}`); for (const s of states(p)) { const where = values.serve ? themes.map((t) => `${origin}/__preview/${name}/${s.name}?theme=${t}`).join(" ") : ""; console.log(` ${s.name}${s.note ? `: ${s.note}` : ""}${where ? `\n ${where}` : ""}`); } } if (values.list) await close(); else console.log("\nServing until Ctrl-C. The pages show the state before its act() runs.");} else { let browser: Browser; try { browser = await chromium.launch(); } catch (err) { await close(); const message = String(err); fail( message.includes("Executable doesn't exist") ? "Chromium is not installed for this Playwright: run `pnpm exec playwright install --only-shell chromium`." : /missing dependencies|error while loading shared libraries/.test(message) ? "Chromium's system libraries are missing: run `pnpm exec playwright install-deps chromium` as root" + " (in an automated session, its image has to provide them).\n" + short(message) : message, ); } const outDir = join(ROOT, OUT); for (const [name, p] of previews) { mkdirSync(join(outDir, name), { recursive: true }); for (const s of states(p)) { for (const theme of themes) { const file = join(outDir, name, `${s.name}.${theme}.png`); // A shot that fails must not leave the last run's PNG to be read as this one. rmSync(file, { force: true }); const context = await browser.newContext({ viewport: s.viewport ?? DEFAULT_VIEWPORT, deviceScaleFactor: 2, colorScheme: theme, reducedMotion: "reduce", }); const page = await context.newPage(); const problems: string[] = []; page.on("pageerror", (e) => problems.push(`page error: ${e.message}`)); page.on("requestfailed", (r) => problems.push(`failed request: ${r.url()}`)); page.on("response", (r) => { if (r.status() >= 400 && r.request().resourceType() !== "document") problems.push(`${r.status()} for ${r.url()}`); }); try { const res = await page.goto(`${origin}/__preview/${name}/${s.name}?theme=${theme}`); if (!res?.ok()) throw new Error(`render failed (${res?.status()}):\n${short(await res?.text())}`); await page.evaluate(() => document.fonts.ready); await s.act?.(page); await page.screenshot({ path: file, animations: "disabled" }); console.log(`${relative(process.cwd(), file)}${s.note ? ` ${s.note}` : ""}`); } catch (err) { console.error(`${name}/${s.name} (${theme}): ${(err as Error).message ?? err}`); process.exitCode = 1; } for (const problem of problems) console.error(` ${name}/${s.name} (${theme}): ${problem}`); await context.close(); } } } await close(browser);}