// Drives Firefox against a running Booksorter server. Usage: node scripts/browser-check.ts [baseUrl] // Env: SHOTS= to save screenshots, ISBN= to use another already-resolved ISBN. import { firefox } from 'playwright'; import { build } from 'esbuild'; import { mkdirSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; const base = process.argv[2] ?? 'http://localhost:4321'; const shots = process.env.SHOTS; if (shots) mkdirSync(shots, { recursive: true }); const ISBN = process.env.ISBN ?? '9781593278281'; const root = fileURLToPath(new URL('..', import.meta.url)); const failures: string[] = []; const check = (name: string, ok: boolean, detail = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); if (!ok) failures.push(name); }; // EAN-13 module pattern (95 modules) for a 13-digit string. function ean13Modules(code: string): string { const L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']; const R = L.map((p) => [...p].map((b) => (b === '0' ? '1' : '0')).join('')); const G = R.map((p) => [...p].reverse().join('')); const parity = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']; const d = [...code].map(Number); let out = '101'; for (let i = 0; i < 6; i++) out += parity[d[0]][i] === 'L' ? L[d[i + 1]] : G[d[i + 1]]; out += '01010'; for (let i = 7; i < 13; i++) out += R[d[i]]; return out + '101'; } // Bundle scanner.ts (the production module) so the page can call its detector. const bundled = await build({ stdin: { contents: "export { makeDetector } from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' }, bundle: true, format: 'esm', write: false, target: 'es2022', logLevel: 'silent', }); const scannerJs = bundled.outputFiles[0].text.replaceAll('https://fastly.jsdelivr.net/npm/', '/local-only/'); const browser = await firefox.launch({ headless: true, firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true }, }); const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); const page = await ctx.newPage(); const consoleErrors: string[] = []; const badRequests: string[] = []; const foreign: string[] = []; page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); }); page.on('pageerror', (e) => consoleErrors.push(String(e))); page.on('requestfailed', (r) => badRequests.push(`${r.url()} ${r.failure()?.errorText}`)); page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${r.url()} ${r.status()}`); }); page.on('request', (r) => { const u = new URL(r.url()); if (!['localhost', '127.0.0.1'].includes(u.hostname) && !['blob:', 'data:', 'about:'].includes(u.protocol)) foreign.push(r.url()); }); await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs })); const shot = async (name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); }; const tab = (name: RegExp) => page.getByRole('tab', { name }); try { await page.goto(base, { waitUntil: 'networkidle' }); await tab(/^Scan/).waitFor(); check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible()); await shot('scan-1280'); await page.setViewportSize({ width: 380, height: 800 }); await shot('scan-380'); await page.setViewportSize({ width: 1280, height: 900 }); // Typed ISBN. A book already in the catalog would only show "Already in catalog", so remove it first // (it re-resolves from the lookup cache). Run this against a scratch database, not your real one. await page.evaluate(async (isbn) => { const books = await (await fetch('/api/books?filter=all')).json(); for (const b of books.filter((x: any) => x.isbn13 === isbn)) await fetch(`/api/books/${b.id}`, { method: 'DELETE' }); }, ISBN); const box = page.getByLabel('ISBN'); check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement)); await box.fill(ISBN); await box.press('Enter'); await page.locator('.scan .right li.item .chip.ok').first().waitFor({ timeout: 120_000 }); check('typed ISBN reaches Ready', true, (await page.locator('.scan .right li.item').first().innerText()).replace(/\s+/g, ' ')); await shot('scan-after-1280'); // Barcode path, no camera const modules = ean13Modules(ISBN); const decoded = await page.evaluate(async ({ modules, src }) => { const { makeDetector } = await import(/* @vite-ignore */ src); const scale = 4, quiet = 12 * scale, h = 120; const c = document.createElement('canvas'); c.width = modules.length * scale + quiet * 2; c.height = h; const g = c.getContext('2d')!; g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, h); g.fillStyle = '#000'; [...modules].forEach((m, i) => { if (m === '1') g.fillRect(quiet + i * scale, 10, scale, h - 20); }); const found = await makeDetector().detect(c); return found.map((f: { rawValue: string; format: string }) => `${f.format}:${f.rawValue}`); }, { modules, src: '/__check/scanner.js' }); check('wasm barcode decode', decoded.includes(`ean_13:${ISBN}`), JSON.stringify(decoded)); // Camera (Firefox fake stream) await page.getByRole('button', { name: 'Start camera' }).click(); await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 15_000 }); const playing = await page.waitForFunction(() => { const v = document.querySelector('video') as HTMLVideoElement | null; return !!v && !!v.srcObject && v.videoWidth > 0 && !v.paused; }, null, { timeout: 15_000 }).then(() => true, () => false); check('Start camera plays video', playing); check('no camera error message', (await page.locator('.scan .warn[role=alert]').count()) === 0); await page.waitForTimeout(1500); // let the scan loop run on the fake frames await shot('scan-camera-1280'); await page.getByRole('button', { name: 'Stop camera' }).click(); await page.getByRole('button', { name: 'Start camera' }).waitFor(); const stopped = await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject); check('Stop camera releases the stream', stopped); // Print queue await tab(/^Print queue/).click(); await page.getByRole('heading', { name: 'Print queue' }).waitFor(); const rows = await page.locator('.queue section').first().locator('li.item').count(); check('Print queue lists resolved books', rows >= 1, `${rows} rows`); const keys: string[] = await page.evaluate(async () => { const books = await (await fetch('/api/books?filter=queue')).json(); return books.filter((b: any) => b.status === 'resolved' && b.callNumber).map((b: any) => b.sortKey ?? '~'); }); check('queue order matches shelf (sort key) order', JSON.stringify(keys) === JSON.stringify([...keys].sort()) && rows === keys.length); await shot('queue-1280'); const [pdfResp] = await Promise.all([ page.waitForResponse((r) => r.url().includes('/api/print.pdf')), page.getByRole('button', { name: 'Make PDF' }).click(), ]); const pdfBody = await pdfResp.body(); check('Make PDF fetches a PDF', pdfResp.status() === 200 && pdfBody.subarray(0, 4).toString() === '%PDF', `${pdfBody.length} bytes`); check('X-Book-Ids header present', /^\d+(,\d+)*$/.test(pdfResp.headers()['x-book-ids'] ?? '')); await page.getByText('Did the cards print correctly?').waitFor(); await shot('queue-confirm-1280'); await page.getByRole('button', { name: 'Not yet' }).click(); // Catalog await tab(/^Catalog/).click(); await page.waitForTimeout(500); check('Catalog tab renders', (await page.locator('main').innerText()).trim().length > 0); await shot('catalog-1280'); check('no console errors', consoleErrors.length === 0, consoleErrors.join(' | ')); check('no failed requests', badRequests.length === 0, badRequests.join(' | ')); check('no request left localhost', foreign.length === 0, foreign.join(' | ')); } catch (e) { check('script ran to completion', false, String(e)); await shot('failure').catch(() => {}); } await browser.close(); console.log(failures.length ? `\n${failures.length} check(s) failed` : '\nAll checks passed'); process.exit(failures.length ? 1 : 0);