Rework scan screen, make lookups non-blocking, fix review findings
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
468cafc6db
commit
b5defb4e4f
46 files changed
+1957
-406
No files matched your search
+386
-117
@@ -1,155 +1,424 @@
|
||||
// Drives Firefox against a running Booksorter server. Usage: node scripts/browser-check.ts [baseUrl]
|
||||
// Env: SHOTS=<dir> to save screenshots, ISBN=<isbn13> to use another already-resolved ISBN.
|
||||
import { firefox } from 'playwright';
|
||||
// Drives Chromium (the browser the app is used in) and Firefox against a running Booksorter server.
|
||||
// Usage: node scripts/browser-check.ts [baseUrl] (point the server at a scratch database)
|
||||
// npx playwright install chromium firefox # once
|
||||
// PORT=4323 BOOKSORTER_DB=/tmp/scratch.db npm start # in another terminal
|
||||
// Env: SHOTS=<dir> saves 1280px dark-mode screenshots; ISBN=<isbn13> uses another already-resolved book.
|
||||
// The camera is Chromium's fake camera playing a .y4m video of an EAN-13 barcode that this script renders.
|
||||
// It adds, removes and re-adds the test book, and invents a few books in the page (never on the server) to
|
||||
// hold the "looking up" and "needs attention" states still.
|
||||
import { chromium, firefox } from 'playwright';
|
||||
import type { Browser, BrowserContext, Page } from 'playwright';
|
||||
import { build } from 'esbuild';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { mkdirSync, mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { makeBarcodeY4m } from './browser-media.ts';
|
||||
|
||||
const base = process.argv[2] ?? 'http://localhost:4321';
|
||||
if (new URL(base).port === '4321' && !process.env.ALLOW_4321) { console.error('Refusing to run against port 4321 (the real database). Use a scratch server.'); process.exit(2); }
|
||||
const shots = process.env.SHOTS;
|
||||
if (shots) mkdirSync(shots, { recursive: true });
|
||||
const ISBN = process.env.ISBN ?? '9781593278281';
|
||||
const ISBN2 = '9780201835953'; // used only for invented books, never looked up
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const work = mkdtempSync(join(tmpdir(), 'booksorter-check-'));
|
||||
|
||||
const failures: string[] = [];
|
||||
const check = (name: string, ok: boolean, detail = '') => {
|
||||
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`);
|
||||
if (!ok) failures.push(name);
|
||||
};
|
||||
const norm = (s: string) => s.replace(/\s+/g, ' ').trim();
|
||||
|
||||
// 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';
|
||||
const consoleErrors: string[] = [];
|
||||
const badRequests: string[] = [];
|
||||
const foreign: string[] = [];
|
||||
function watch(page: Page, label: string) {
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(`${label}: ${m.text()}`); });
|
||||
page.on('pageerror', (e) => consoleErrors.push(`${label}: ${e}`));
|
||||
page.on('requestfailed', (r) => badRequests.push(`${label}: ${r.url()} ${r.failure()?.errorText}`));
|
||||
page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${label}: ${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());
|
||||
});
|
||||
}
|
||||
const shot = async (page: Page, name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); };
|
||||
const section = async (name: string, fn: () => Promise<void>) => {
|
||||
console.log(`\n# ${name}`);
|
||||
try { await fn(); } catch (e) { check(`${name}: ran to completion`, false, String(e).split('\n')[0]); }
|
||||
};
|
||||
|
||||
const api = <T = any>(page: Page, path: string, init?: { method?: string; body?: unknown }): Promise<T> =>
|
||||
page.evaluate(async ({ path, init }) => {
|
||||
const r = await fetch(path, { method: init?.method ?? 'GET', headers: init?.body ? { 'Content-Type': 'application/json' } : undefined, body: init?.body ? JSON.stringify(init.body) : undefined });
|
||||
const t = await r.text();
|
||||
return t ? JSON.parse(t) : null;
|
||||
}, { path, init });
|
||||
|
||||
const removeBook = (page: Page, isbn: string) => 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 fakeBook = (id: number, over: Record<string, unknown>) => ({
|
||||
id, isbn13: null, lccn: null, title: `Book ${id}`, subtitle: null, authors: ['A. Writer'], publisher: null, year: null, subjects: [],
|
||||
callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, status: 'pending', attentionReason: null,
|
||||
manualOverride: false, inQueue: true, printedAt: null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...over,
|
||||
});
|
||||
|
||||
/** Answer POST /api/scan for one ISBN with an invented book instead of asking the server. */
|
||||
async function inventScan(page: Page, isbn: string, book: Record<string, unknown>) {
|
||||
await page.route('**/api/scan', async (route) => {
|
||||
const sent = route.request().postDataJSON();
|
||||
if (sent?.isbn === isbn) await route.fulfill({ json: { book, duplicate: false } });
|
||||
else await route.fallback();
|
||||
});
|
||||
}
|
||||
|
||||
// Bundle scanner.ts (the production module) so the page can call its detector.
|
||||
const rows = (page: Page) => page.locator('.scan .right li.book');
|
||||
const statusLine = (page: Page) => page.getByRole('status').filter({ hasText: /\S/ }).first();
|
||||
|
||||
// Bundle the production scanner so a page can call its decode functions directly.
|
||||
const bundled = await build({
|
||||
stdin: { contents: "export { makeDetector } from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' },
|
||||
stdin: { contents: "export * 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({
|
||||
// Videos for the fake camera: a barcode on white at a readable size, a hard (small, soft) one, and an empty page.
|
||||
const videoOk = join(work, 'barcode.y4m');
|
||||
const videoHard = join(work, 'barcode-small.y4m');
|
||||
const videoBlank = join(work, 'blank.y4m');
|
||||
makeBarcodeY4m(videoOk, { isbn: ISBN, moduleScale: 2.0, frames: 24 });
|
||||
makeBarcodeY4m(videoHard, { isbn: ISBN, moduleScale: 1.6, frames: 24 });
|
||||
makeBarcodeY4m(videoBlank, { isbn: ISBN, moduleScale: 0.01, frames: 4 });
|
||||
|
||||
const chromiumFor = (video: string) => chromium.launch({
|
||||
headless: true,
|
||||
firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true },
|
||||
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-video-capture=${video}`],
|
||||
});
|
||||
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 darkContext = (b: Browser, extra: Parameters<Browser['newContext']>[0] = {}) =>
|
||||
b.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark', permissions: ['camera'], ...extra });
|
||||
|
||||
const shot = async (name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); };
|
||||
const tab = (name: RegExp) => page.getByRole('tab', { name });
|
||||
/** Records every stream the page opens, and every change of the status line, for later assertions. */
|
||||
const instrument = (ctx: BrowserContext, gumDelayMs = 0) => ctx.addInitScript((delay) => {
|
||||
const w = window as any;
|
||||
w.__streams = []; w.__statuses = []; w.__flashes = 0;
|
||||
const md = navigator.mediaDevices;
|
||||
const orig = md.getUserMedia.bind(md);
|
||||
md.getUserMedia = async (c) => {
|
||||
if (delay) await new Promise((r) => setTimeout(r, delay));
|
||||
const s = await orig(c); w.__streams.push(s); return s;
|
||||
};
|
||||
new MutationObserver((list) => {
|
||||
for (const m of list) {
|
||||
const t = m.target as HTMLElement;
|
||||
if (t.classList?.contains('video-wrap') && t.classList.contains('flash')) w.__flashes++;
|
||||
}
|
||||
const st = document.querySelector('p.status');
|
||||
if (st && st.textContent && w.__statuses[w.__statuses.length - 1] !== st.textContent) w.__statuses.push(st.textContent);
|
||||
}).observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
|
||||
}, gumDelayMs);
|
||||
const liveTracks = (page: Page) => page.evaluate(() => (window as any).__streams.flatMap((s: MediaStream) => s.getTracks()).filter((t: MediaStreamTrack) => t.readyState === 'live').length);
|
||||
|
||||
try {
|
||||
let server404 = false;
|
||||
try { const r = await fetch(base); server404 = !r.ok; } catch { server404 = true; }
|
||||
if (server404) { console.error(`No Booksorter server answering at ${base}`); process.exit(2); }
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
// 1. Typed ISBNs: one Enter is one request and one row (Chromium and Firefox)
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
for (const [name, type] of [['chromium', chromium], ['firefox', firefox]] as const) {
|
||||
await section(`${name}: typed ISBN`, async () => {
|
||||
const browser = await type.launch({ headless: true });
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
||||
const page = await ctx.newPage(); watch(page, name);
|
||||
const posts: string[] = [];
|
||||
page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); });
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
await removeBook(page, ISBN); // the lookup cache makes the re-add quick; a scratch database is assumed
|
||||
const box = page.getByLabel('ISBN');
|
||||
check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement));
|
||||
check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible());
|
||||
await box.fill(ISBN);
|
||||
await box.press('Enter');
|
||||
await rows(page).first().waitFor();
|
||||
await page.waitForTimeout(700);
|
||||
check('one typed ISBN + Enter sends exactly one POST /api/scan', posts.length === 1, `${posts.length} request(s)`);
|
||||
check('one typed ISBN makes exactly one row', (await rows(page).count()) === 1);
|
||||
await rows(page).first().locator('[data-state]').or(rows(page).first()).first().waitFor();
|
||||
await page.locator('.scan .right li.book:not(.looking)').first().waitFor({ timeout: 150_000 });
|
||||
const text = norm(await rows(page).first().innerText());
|
||||
check('the row shows one state', /Ready|Needs attention/.test(text) && !/Looking up/.test(text), text.slice(0, 120));
|
||||
|
||||
await box.fill(ISBN);
|
||||
await box.press('Enter');
|
||||
await page.waitForTimeout(800);
|
||||
check('typing the same ISBN again leaves one row', (await rows(page).count()) === 1, `${await rows(page).count()} row(s), ${posts.length} POSTs`);
|
||||
check('the book already in this session is not marked "Already in catalog"', !/Already in catalog/.test(await rows(page).first().innerText()));
|
||||
|
||||
// Two Enters while the first request is still in flight: still one request, one row.
|
||||
await page.route('**/api/scan', async (route) => { await new Promise((r) => setTimeout(r, 600)); await route.fallback(); });
|
||||
const before = posts.length;
|
||||
await box.fill(ISBN); await box.press('Enter');
|
||||
await box.fill(ISBN); await box.press('Enter');
|
||||
await page.waitForTimeout(1500);
|
||||
check('two quick Enters for one ISBN send one request', posts.length - before === 1, `${posts.length - before} request(s)`);
|
||||
check('and still one row', (await rows(page).count()) === 1);
|
||||
|
||||
// Reload: the book is now an earlier one, so it is shown once with the note.
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
await page.getByLabel('ISBN').fill(ISBN); await page.getByLabel('ISBN').press('Enter');
|
||||
await rows(page).first().waitFor();
|
||||
const earlier = norm(await rows(page).first().innerText());
|
||||
check('a book from an earlier session shows one row with "Already in catalog"', (await rows(page).count()) === 1 && /Already in catalog/.test(earlier), earlier.slice(0, 120));
|
||||
await browser.close();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
// 2. States, summary, queue (Chromium, invented books for the states that cannot be held still for real)
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
await section('session states, summary and print queue', async () => {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
||||
const page = await ctx.newPage(); watch(page, 'states');
|
||||
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 });
|
||||
await removeBook(page, ISBN);
|
||||
const pendingBook = fakeBook(900001, { isbn13: ISBN2, title: 'The Mythical Man-Month', authors: ['Frederick P. Brooks'], attentionReason: 'Library of Congress did not answer. Trying again shortly.' });
|
||||
await inventScan(page, ISBN2, pendingBook);
|
||||
const attentionBook = fakeBook(900002, { isbn13: null, title: 'A Book Nobody Catalogued', authors: ['Anon.'], status: 'needs_attention', attentionReason: 'No catalog record matched this ISBN.', inQueue: false });
|
||||
await page.route('**/api/books/lccn', (route) => route.fulfill({ json: { book: attentionBook } }));
|
||||
|
||||
// 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);
|
||||
// Ready book 1: typed ISBN (resolved from cache). Ready book 2: entered by hand with a call number.
|
||||
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');
|
||||
await box.fill(ISBN); await box.press('Enter');
|
||||
await page.locator('.scan .right li.book.ready').first().waitFor({ timeout: 150_000 });
|
||||
await page.locator('summary', { hasText: 'Enter by hand' }).click();
|
||||
const manual = page.locator('details', { hasText: 'Enter by hand' });
|
||||
await manual.getByLabel('Title').fill('Structure and Interpretation of Computer Programs');
|
||||
await manual.getByLabel('Authors (separate with ;)').fill('Harold Abelson; Gerald Jay Sussman');
|
||||
await manual.getByLabel('Call number (optional)').fill('QA76.6 .A24 1996');
|
||||
await manual.getByRole('button', { name: 'Add' }).click();
|
||||
await page.locator('.scan .right li.book.ready', { hasText: 'Structure and Interpretation' }).waitFor();
|
||||
// Looking-up book (invented scan), and a needs-attention book (invented LCCN answer).
|
||||
await box.fill(ISBN2); await box.press('Enter');
|
||||
await rows(page).first().waitFor();
|
||||
await page.locator('summary', { hasText: 'Enter LCCN' }).click();
|
||||
const lccn = page.locator('details', { hasText: 'Enter LCCN' });
|
||||
await lccn.getByLabel('LCCN').fill('00000000');
|
||||
await lccn.getByRole('button', { name: 'Add' }).click();
|
||||
await page.locator('.scan .right li.book.attention').waitFor();
|
||||
await page.waitForTimeout(2200); // let the seconds count
|
||||
|
||||
// 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);
|
||||
const summary = norm(await page.locator('.scan .summary').innerText());
|
||||
check('summary counts all four rows', summary === '4 scanned · 2 ready · 1 looking up · 1 needs attention', summary);
|
||||
const looking = rows(page).filter({ hasText: 'Looking up' });
|
||||
const lookingText = norm(await looking.innerText());
|
||||
check('a pending book shows Looking up with elapsed seconds', /Looking up… \d+ s/.test(lookingText), lookingText);
|
||||
check('a pending book shows its retry note', lookingText.includes('Trying again shortly'));
|
||||
check('a pending book never says "No call number"', !/No call number/.test(lookingText));
|
||||
check('a pending book has a spinner', (await looking.locator('.spinner').count()) === 1);
|
||||
const secs = Number(/(\d+) s/.exec(lookingText)?.[1] ?? 0);
|
||||
check('the elapsed seconds are counting', secs >= 2, `${secs} s`);
|
||||
const attn = norm(await rows(page).filter({ hasText: 'Needs attention' }).innerText());
|
||||
check('a needs-attention row shows the reason and a Fix button', attn.includes('No catalog record matched') && attn.includes('Fix'), attn);
|
||||
check('every row shows exactly one state label',
|
||||
(await rows(page).evaluateAll((els) => els.map((e) => e.querySelectorAll('.state-label').length))).every((n) => n === 1));
|
||||
await rows(page).filter({ hasText: 'Needs attention' }).getByRole('button', { name: 'Fix' }).click();
|
||||
check('Fix opens the editor', await page.getByLabel('Call number', { exact: true }).isVisible());
|
||||
// The year field rejects text, never sends NaN.
|
||||
let patched = false;
|
||||
await page.route('**/api/books/900002', async (route) => { patched = true; await route.fulfill({ json: attentionBook }); });
|
||||
await page.locator('.editor').getByLabel('Year').fill('abc');
|
||||
await page.locator('.editor').getByRole('button', { name: 'Save' }).click();
|
||||
check('the editor shows an error for a non-numeric year and sends nothing', (await page.locator('.editor [role=alert]').first().isVisible()) && !patched);
|
||||
await page.locator('.editor').getByLabel('Year').fill('');
|
||||
await page.locator('.editor').getByRole('button', { name: 'Save' }).click();
|
||||
await page.waitForTimeout(300);
|
||||
check('an empty year is saved as null', patched);
|
||||
await shot(page, 'scan-three-states');
|
||||
|
||||
// Print queue
|
||||
await tab(/^Print queue/).click();
|
||||
const readyCount = (await api<any[]>(page, '/api/books?filter=queue')).filter((b) => b.status === 'resolved' && b.callNumber).length;
|
||||
await page.getByRole('tab', { name: /^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'] ?? ''));
|
||||
const head = norm(await page.locator('.queue .summary').innerText());
|
||||
const want = `${readyCount} ${readyCount === 1 ? 'card' : 'cards'} ready · 1 still looking up`;
|
||||
check('queue header counts ready and looking-up books', head === want, `${head} (expected ${want})`);
|
||||
check('the pending book is listed in the queue, greyed, with the spinner', (await page.locator('.queue li.item.dim .spinner').count()) === 1);
|
||||
check('the tab label counts queued books (ready + looking up)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === `Print queue (${readyCount + 1})`);
|
||||
check('"Needs attention" does not claim every book has a call number', !/Every book has a call number/.test(await page.locator('.queue').innerText()));
|
||||
const pdfBtn = page.getByRole('button', { name: /^Make PDF/ });
|
||||
check('Make PDF says how many cards', norm(await pdfBtn.innerText()) === `Make PDF (${readyCount} ${readyCount === 1 ? 'card' : 'cards'})`, norm(await pdfBtn.innerText()));
|
||||
await shot(page, 'queue-ready-and-looking');
|
||||
const [pdfResp] = await Promise.all([page.waitForResponse((r) => r.url().includes('/api/print.pdf')), pdfBtn.click()]);
|
||||
const body = await pdfResp.body();
|
||||
check('Make PDF fetches a PDF', pdfResp.status() === 200 && body.subarray(0, 4).toString() === '%PDF', `${body.length} bytes`);
|
||||
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);
|
||||
await shot(page, 'queue-after-pdf');
|
||||
const catalog = page.getByRole('tab', { name: /^Catalog/ });
|
||||
await catalog.click();
|
||||
await page.waitForTimeout(400);
|
||||
check('Catalog tab renders', (await page.locator('main').innerText()).trim().length > 0);
|
||||
await shot('catalog-1280');
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
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');
|
||||
await section('print queue with nothing ready', async () => {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
||||
const page = await ctx.newPage(); watch(page, 'empty-queue');
|
||||
// Show only a pending book: the server's list is answered by an invented one.
|
||||
await page.route('**/api/books?*', (route) => route.fulfill({ json: [fakeBook(900003, { title: 'Still Looking' })] }));
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
await page.getByRole('tab', { name: /^Print queue/ }).click();
|
||||
const head = norm(await page.locator('.queue .summary').innerText());
|
||||
check('queue with only a pending book reads "0 cards ready · 1 still looking up"', head === '0 cards ready · 1 still looking up', head);
|
||||
const pdfBtn = page.getByRole('button', { name: /^Make PDF/ });
|
||||
check('Make PDF is disabled with an explanation', (await pdfBtn.isDisabled()) && (await page.locator('#pdf-why').innerText()).includes('No card is ready yet'));
|
||||
check('the tab label says (1)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === 'Print queue (1)');
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
// 3. The camera, in Chromium with a fake camera playing a video of a barcode
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
await section('camera: Start camera reads the barcode from video alone', async () => {
|
||||
const browser = await chromiumFor(videoOk);
|
||||
const ctx = await darkContext(browser);
|
||||
await instrument(ctx);
|
||||
const page = await ctx.newPage(); watch(page, 'camera');
|
||||
const posts: string[] = [];
|
||||
page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); });
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
await removeBook(page, ISBN);
|
||||
check('camera off: Start camera is in the middle of the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible());
|
||||
check('camera off: the status line says so', /camera is off/i.test(await statusLine(page).innerText()));
|
||||
|
||||
await page.getByRole('button', { name: 'Start camera' }).dblclick(); // a double click must not open two streams
|
||||
await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 });
|
||||
check('the target box and instruction are shown', await page.locator('.target').isVisible());
|
||||
check('the Scanning indicator is shown', await page.locator('.scanning').isVisible());
|
||||
await page.waitForFunction(() => (window as any).__statuses.some((s: string) => /^Read \d{13}$/.test(s)), null, { timeout: 30_000 });
|
||||
const statuses: string[] = await page.evaluate(() => (window as any).__statuses);
|
||||
check('status line went "Looking for a barcode…" then "Read <isbn>"', statuses.includes('Looking for a barcode…') && statuses.includes(`Read ${ISBN}`), JSON.stringify(statuses));
|
||||
check('the video border flashed green on the read', (await page.evaluate(() => (window as any).__flashes)) >= 1);
|
||||
await rows(page).first().waitFor({ timeout: 15_000 });
|
||||
await page.waitForTimeout(1500);
|
||||
check('the book appeared in the session list from the camera alone, one row', (await rows(page).count()) === 1, norm(await rows(page).first().innerText()).slice(0, 100));
|
||||
check('a barcode held in view posts once, not once per frame', posts.length === 1, `${posts.length} POST(s)`);
|
||||
check('a double click on Start camera opened one stream', (await page.evaluate(() => (window as any).__streams.length)) === 1);
|
||||
check('the video has real size', await page.evaluate(() => { const v = document.querySelector('video')!; return v.videoWidth > 0; }));
|
||||
await shot(page, 'scan-camera-read');
|
||||
|
||||
// Capture button and Space
|
||||
await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 });
|
||||
const mark = await page.evaluate(() => (window as any).__statuses.length);
|
||||
await page.getByRole('button', { name: 'Capture' }).click();
|
||||
await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark, { timeout: 20_000 });
|
||||
const after: string[] = await page.evaluate((m) => (window as any).__statuses.slice(m), mark);
|
||||
check('Capture takes a picture and reads the barcode', after[0] === 'Taking a picture and reading it…' && after.includes(`Read ${ISBN}`), JSON.stringify(after));
|
||||
await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 });
|
||||
const mark2 = await page.evaluate(() => (window as any).__statuses.length);
|
||||
await page.locator('video').click({ force: true }); // focus leaves the text field
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement)?.blur?.());
|
||||
await page.keyboard.press('Space');
|
||||
await page.waitForFunction((m) => (window as any).__statuses.slice(m).includes('Taking a picture and reading it…'), mark2, { timeout: 10_000 });
|
||||
check('Space triggers Capture when focus is not in a text field', true);
|
||||
await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark2, { timeout: 20_000 });
|
||||
const box = page.getByLabel('ISBN');
|
||||
await box.focus(); await page.keyboard.press('Space');
|
||||
check('Space in the ISBN box also captures and types no space', (await box.inputValue()) === '');
|
||||
check('the Capture reads never added a second row', (await rows(page).count()) === 1);
|
||||
|
||||
// Remembered: reload starts the camera by itself; Stop forgets it.
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 });
|
||||
check('after a reload the camera starts by itself (permission already granted)', true);
|
||||
await page.getByRole('button', { name: 'Stop camera' }).click();
|
||||
await page.getByRole('button', { name: 'Start camera' }).waitFor();
|
||||
check('Stop camera releases every stream', (await liveTracks(page)) === 0);
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
await page.waitForTimeout(800);
|
||||
check('after Stop and a reload the camera stays off, with the Start button in the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible());
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
await section('camera: leaving the view while the permission prompt is open', async () => {
|
||||
const browser = await chromiumFor(videoOk);
|
||||
const ctx = await darkContext(browser);
|
||||
await instrument(ctx, 1500); // getUserMedia answers 1.5 s late, like a person reading the prompt
|
||||
const page = await ctx.newPage(); watch(page, 'prompt');
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
const btn = page.getByRole('button', { name: /^Start camera|^Starting camera/ });
|
||||
await btn.click();
|
||||
check('Start is disabled while starting', await page.getByRole('button', { name: 'Starting camera…' }).isDisabled());
|
||||
await page.getByRole('tab', { name: /^Print queue/ }).click(); // the Scan view unmounts mid-prompt
|
||||
await page.waitForFunction(() => (window as any).__streams.length === 1, null, { timeout: 10_000 });
|
||||
await page.waitForTimeout(300);
|
||||
check('the stream that arrives after leaving is stopped at once', (await liveTracks(page)) === 0);
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
await section('camera: nothing readable in view', async () => {
|
||||
const browser = await chromiumFor(videoBlank);
|
||||
const ctx = await darkContext(browser);
|
||||
await instrument(ctx);
|
||||
const page = await ctx.newPage(); watch(page, 'blank');
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
await page.getByRole('button', { name: 'Start camera' }).click();
|
||||
await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 });
|
||||
await page.waitForTimeout(1000);
|
||||
check('with no barcode the status stays "Looking for a barcode…"', (await statusLine(page).innerText()) === 'Looking for a barcode…');
|
||||
await page.getByRole('button', { name: 'Capture' }).click();
|
||||
await page.getByText('No barcode found in that picture. Move closer, add light, or type the ISBN below.').waitFor({ timeout: 20_000 });
|
||||
check('Capture says plainly when it finds nothing', true);
|
||||
check('and no row was added', (await rows(page).count()) === 0);
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
await section('decoder: the thorough decode reads a small, soft barcode the live loop misses', async () => {
|
||||
const browser = await chromiumFor(videoHard);
|
||||
const ctx = await darkContext(browser);
|
||||
const page = await ctx.newPage(); watch(page, 'decode');
|
||||
await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs }));
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
const r = await page.evaluate(async (isbn) => {
|
||||
const mod = await import(/* @vite-ignore */ ('/__check/' + 'scanner.js')); mod.prepare();
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 1920, height: 1080 } });
|
||||
const v = document.createElement('video'); v.srcObject = stream; v.muted = true; await v.play();
|
||||
await new Promise((res) => setTimeout(res, 500));
|
||||
const live = await mod.decodeLive(v); const thorough = await mod.decodeThorough(v);
|
||||
stream.getTracks().forEach((t: MediaStreamTrack) => t.stop());
|
||||
return { live, thorough, isbn };
|
||||
}, ISBN);
|
||||
check('thorough decode reads the small barcode', r.thorough.isbn === ISBN, JSON.stringify(r));
|
||||
check('live decode never returns a wrong ISBN for it', r.live.isbn === null || r.live.isbn === ISBN, JSON.stringify(r.live));
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
// 4. Firefox's fake camera starts and stops
|
||||
// ---------------------------------------------------------------------------------------------------
|
||||
await section('firefox: fake camera starts and stops', async () => {
|
||||
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 }, colorScheme: 'dark' });
|
||||
const page = await ctx.newPage(); watch(page, 'firefox-cam');
|
||||
await page.goto(base, { waitUntil: 'networkidle' });
|
||||
await page.getByRole('button', { name: 'Start camera' }).click();
|
||||
await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 });
|
||||
check('Start camera plays video', await page.waitForFunction(() => { const v = document.querySelector('video') as HTMLVideoElement; return !!v.srcObject && v.videoWidth > 0 && !v.paused; }, null, { timeout: 15_000 }).then(() => true, () => false));
|
||||
await page.getByRole('button', { name: 'Stop camera' }).click();
|
||||
await page.getByRole('button', { name: 'Start camera' }).waitFor();
|
||||
check('Stop camera releases the stream', await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject));
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
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(' | '));
|
||||
console.log(failures.length ? `\n${failures.length} check(s) failed: ${failures.join('; ')}` : '\nAll checks passed');
|
||||
process.exit(failures.length ? 1 : 0);
|
||||
@@ -0,0 +1,81 @@
|
||||
// Helpers for scripts/browser-check.ts: an EAN-13 bitmap, and a .y4m video of it for Chromium's fake camera.
|
||||
import { writeFileSync } from 'node:fs';
|
||||
|
||||
/** EAN-13 module pattern (95 modules, 1 = bar) for a 13-digit string. */
|
||||
export 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';
|
||||
}
|
||||
|
||||
export interface VideoOptions {
|
||||
isbn: string;
|
||||
width?: number; height?: number; frames?: number;
|
||||
/** Pixels per barcode module. A real book held about 30 cm from a 720p webcam is roughly 1.2 to 2 px per module. */
|
||||
moduleScale?: number;
|
||||
}
|
||||
|
||||
/** Deterministic noise so a run is repeatable. */
|
||||
function rng(seed: number) { let s = seed >>> 0; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); }
|
||||
|
||||
/** Gray frames (Uint8Array, width*height) of a barcode on a white page: soft focus, sensor noise, hand jitter. */
|
||||
export function barcodeFrames(o: VideoOptions): Uint8Array[] {
|
||||
const W = o.width ?? 1280, H = o.height ?? 720, n = o.frames ?? 24, m = o.moduleScale ?? 2.6;
|
||||
const mods = ean13Modules(o.isbn);
|
||||
const bw = 95 * m, bh = Math.round(bw * 0.62);
|
||||
const rand = rng(7);
|
||||
const frames: Uint8Array[] = [];
|
||||
for (let f = 0; f < n; f++) {
|
||||
const jx = (rand() - 0.5) * 5, jy = (rand() - 0.5) * 5;
|
||||
const x0 = W / 2 - bw / 2 + jx, y0 = H / 2 - bh / 2 + jy;
|
||||
const raw = new Float32Array(W * H);
|
||||
for (let y = 0; y < H; y++) {
|
||||
for (let x = 0; x < W; x++) {
|
||||
let v = 238 - 14 * (x / W) - 8 * (y / H); // a lit page, slightly uneven
|
||||
if (y >= y0 && y < y0 + bh) {
|
||||
let dark = 0;
|
||||
for (let s = 0; s < 4; s++) { // 4 samples across the pixel
|
||||
const mi = Math.floor((x + (s + 0.5) / 4 - x0) / m);
|
||||
if (mi >= 0 && mi < 95 && mods[mi] === '1') dark++;
|
||||
}
|
||||
v = v * (1 - dark / 4) + 22 * (dark / 4);
|
||||
}
|
||||
raw[y * W + x] = v;
|
||||
}
|
||||
}
|
||||
// Soft focus: a [1 2 1] blur both ways, then noise.
|
||||
const out = new Uint8Array(W * H);
|
||||
const tmp = new Float32Array(W * H);
|
||||
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
||||
const a = raw[y * W + Math.max(0, x - 1)], b = raw[y * W + x], c = raw[y * W + Math.min(W - 1, x + 1)];
|
||||
tmp[y * W + x] = (a + 2 * b + c) / 4;
|
||||
}
|
||||
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
||||
const a = tmp[Math.max(0, y - 1) * W + x], b = tmp[y * W + x], c = tmp[Math.min(H - 1, y + 1) * W + x];
|
||||
out[y * W + x] = Math.max(0, Math.min(255, Math.round((a + 2 * b + c) / 4 + (rand() - 0.5) * 8)));
|
||||
}
|
||||
frames.push(out);
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
/** Write gray frames as a YUV4MPEG2 (4:2:0) file, the format Chromium's --use-file-for-fake-video-capture reads. */
|
||||
export function writeY4m(path: string, frames: Uint8Array[], width: number, height: number): void {
|
||||
const header = Buffer.from(`YUV4MPEG2 W${width} H${height} F30:1 Ip A1:1 C420jpeg\n`);
|
||||
const chroma = Buffer.alloc((width / 2) * (height / 2) * 2, 128);
|
||||
const parts: Buffer[] = [header];
|
||||
for (const f of frames) parts.push(Buffer.from('FRAME\n'), Buffer.from(f), chroma);
|
||||
writeFileSync(path, Buffer.concat(parts));
|
||||
}
|
||||
|
||||
export function makeBarcodeY4m(path: string, o: VideoOptions): void {
|
||||
const W = o.width ?? 1280, H = o.height ?? 720;
|
||||
writeY4m(path, barcodeFrames(o), W, H);
|
||||
}
|
||||
Reference in new issue
Block a user