import { spawn } from 'node:child_process'; import { readdir, stat, access } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; export async function latestReport(directory) { const reports = []; try { const legacy = await stat(path.join(directory, 'index.html')); reports.push({ candidate: directory, modified: legacy.mtimeMs }); } catch { /* Older runners wrote index.html directly in this directory. */ } for (const entry of await readdir(directory, { withFileTypes: true })) { if (!entry.isDirectory()) continue; const candidate = path.join(directory, entry.name); try { const info = await stat(path.join(candidate, 'index.html')); reports.push({ candidate, modified: info.mtimeMs }); } catch { /* Incomplete runs have no report to open. */ } } reports.sort((a, b) => b.modified - a.modified); if (!reports.length) throw new Error('No completed HTML report found'); return reports[0].candidate; } if ( process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) ) { const [mode, ...args] = process.argv.slice(2); const env = { ...process.env }; const cli = fileURLToPath( new URL('../node_modules/@playwright/test/cli.js', import.meta.url), ); let command = ['test', ...args]; if (mode === 'headless') env.PW_HEADLESS = '1'; else if (mode === 'extended') env.PW_EXTENDED_LAYOUT = '1'; else if (mode === 'dist') { env.PW_TARGET = 'local-dist'; env.PW_BASE_URL = 'http://127.0.0.1:4176/'; const root = env.PW_DIST_DIR || fileURLToPath(new URL('../dist/', import.meta.url)); await access(path.join(root, 'index.html')); } else if (mode === 'report') { const explicitDirectory = args[0] && !args[0].startsWith('-'); const directory = explicitDirectory ? args[0] : await latestReport( fileURLToPath(new URL('../playwright-report/', import.meta.url)), ); command = [ 'show-report', directory, ...(explicitDirectory ? args.slice(1) : args), ]; } else throw new Error('Expected headless, extended, dist or report'); const child = spawn(process.execPath, [cli, ...command], { cwd: fileURLToPath(new URL('../', import.meta.url)), stdio: 'inherit', env, }); child.on('error', (error) => { console.error(error); process.exitCode = 1; }); child.on('exit', (code) => { process.exitCode = code ?? 1; }); }