// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests. // // pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--no-serve] // // A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`. // A test declares what it needs on a line near the top: // // @requires plugin:terminal plugin:table-formulas repo:RuneStone_Git/dist electron // The runner skips a test, with the reason, when a requirement is missing. import { spawn } from "node:child_process"; import { createWriteStream, existsSync } from "node:fs"; import { mkdir, readdir, readFile } from "node:fs/promises"; import { createRequire } from "node:module"; import path from "node:path"; import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("../", import.meta.url)); const smokeRoot = path.join(root, "tests", "smoke"); const logRoot = path.join(root, "output", "smoke", "logs"); const args = process.argv.slice(2); const option = (name, fallback) => { const index = args.indexOf(name); if (index < 0) return fallback; const [value] = args.splice(index, 2).slice(1); return value; }; const flag = name => { const index = args.indexOf(name); if (index >= 0) args.splice(index, 1); return index >= 0; }; const list = flag("--list"); const serve = !flag("--no-serve"); const jobs = Math.max(1, Number(option("--jobs", "4"))); const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000; const filters = args; const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" }; const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, ".."); async function findTests(dir) { const result = []; for (const entry of await readdir(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory() && !entry.name.startsWith("_")) result.push(...await findTests(full)); else if (entry.isFile() && entry.name.endsWith(".smoke.mjs")) result.push(full); } return result.sort(); } async function requirements(file) { const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n"); return head.match(/@requires\s+([^\n]+)/)?.[1].trim().split(/\s+/) ?? []; } function missing(requirement) { const [kind, value = ""] = requirement.split(/:(.*)/s); if (kind === "plugin" && value === "terminal") { const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist"); return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`; } if (kind === "plugin") { const entry = path.join(root, "plugin-packages", value, "main.js"); return existsSync(entry) ? null : `plugin-packages/${value} is missing; run pnpm build:plugins`; } if (kind === "repo") { const target = path.join(pluginRepos, value); return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`; } if (kind === "electron") { return existsSync(path.join(root, "browser-runtime", "node_modules", "electron")) ? null : "Electron is missing; run npm ci --prefix browser-runtime"; } return `unknown requirement "${requirement}"`; } function findChrome() { if (env.CHROME_PATH || env.PLAYWRIGHT_MODULE) return; try { const bundled = createRequire(import.meta.url)("playwright").chromium.executablePath(); if (existsSync(bundled)) return; } catch { return; } const candidates = { win32: [ path.join(env.PROGRAMFILES || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"), path.join(env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Microsoft\\Edge\\Application\\msedge.exe"), path.join(env.PROGRAMFILES || "C:\\Program Files", "Microsoft\\Edge\\Application\\msedge.exe"), ], darwin: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium"], linux: ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"], }[process.platform] ?? []; const found = candidates.find(existsSync); if (found) env.CHROME_PATH = found; else console.warn("No Chromium found. Run `pnpm exec playwright install chromium`, or set CHROME_PATH."); } async function reachable(url) { try { await fetch(url, { signal: AbortSignal.timeout(2000) }); return true; } catch { return false; } } async function startServer() { const vite = path.join(root, "node_modules", "vite", "bin", "vite.js"); const server = spawn(process.execPath, [vite, "dev"], { cwd: root, stdio: "ignore", windowsHide: true }); for (let waited = 0; waited < 60000; waited += 500) { if (await reachable(env.SMOKE_URL)) return server; await new Promise(resolve => setTimeout(resolve, 500)); } server.kill(); throw new Error(`The dev server did not start at ${env.SMOKE_URL}.`); } function run(file) { const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""); const log = path.join(logRoot, name.replaceAll("/", "__") + ".log"); const started = Date.now(); return new Promise(resolve => { const out = createWriteStream(log); const child = spawn(process.execPath, [file], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); child.stdout.pipe(out, { end: false }); child.stderr.pipe(out, { end: false }); const timer = setTimeout(() => child.kill(), timeoutMs); child.on("close", code => { clearTimeout(timer); out.end(); const seconds = ((Date.now() - started) / 1000).toFixed(1); const status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail"; resolve({ name, status, detail: `${seconds}s`, log }); }); }); } const tests = (await findTests(smokeRoot)).filter(file => { const rel = path.relative(smokeRoot, file).replace(/\\/g, "/"); return !filters.length || filters.some(filter => rel.includes(filter)); }); if (!tests.length) { console.error(`No smoke tests match: ${filters.join(" ")}`); process.exit(1); } const plan = []; for (const file of tests) { const needs = await requirements(file); const reasons = needs.map(missing).filter(Boolean); plan.push({ file, needs, reasons }); } if (list) { for (const { file, needs, reasons } of plan) { const name = path.relative(smokeRoot, file).replace(/\\/g, "/"); console.log(`${reasons.length ? "skip" : "run "} ${name}${needs.length ? ` [${needs.join(" ")}]` : ""}${reasons.length ? ` (${reasons.join("; ")})` : ""}`); } process.exit(0); } findChrome(); await mkdir(logRoot, { recursive: true }); let server; if (!(await reachable(env.SMOKE_URL))) { if (!serve) { console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`); process.exit(1); } console.log(`Starting the dev server at ${env.SMOKE_URL}...`); server = await startServer(); } const results = []; const queue = plan.filter(item => !item.reasons.length); for (const item of plan.filter(item => item.reasons.length)) { results.push({ name: path.relative(smokeRoot, item.file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""), status: "skip", detail: item.reasons.join("; ") }); } async function worker() { while (queue.length) { const { file } = queue.shift(); const result = await run(file); results.push(result); console.log(`${result.status.padEnd(7)} ${result.name} (${result.detail})`); } } try { await Promise.all(Array.from({ length: Math.min(jobs, queue.length || 1) }, worker)); } finally { server?.kill(); } const count = status => results.filter(result => result.status === status).length; console.log(""); for (const result of results.filter(item => item.status !== "pass").sort((a, b) => a.name.localeCompare(b.name))) { console.log(`${result.status.padEnd(7)} ${result.name}: ${result.status === "skip" ? result.detail : path.relative(root, result.log)}`); } console.log(`\n${count("pass")} passed, ${count("fail") + count("timeout")} failed, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`); process.exitCode = count("fail") + count("timeout") ? 1 : 0;