Integrate the app end to end, add class outline, browser check and README
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdfdf581f3
commit
468cafc6db
17 files changed
+702
-16
No files matched your search
@@ -0,0 +1,155 @@
|
||||
// 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';
|
||||
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);
|
||||
@@ -0,0 +1,118 @@
|
||||
// Generates src/shared/lcc-outline.ts from the Library of Congress Classification
|
||||
// Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication.
|
||||
// Usage: node scripts/gen-lcc-outline.ts [cacheDir] (or env LCC_CACHE_DIR)
|
||||
// Requires `pdftotext` (poppler). Downloads are cached outside the repo.
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const INDEX = 'https://www.loc.gov/catdir/cpso/lcco/';
|
||||
const UA = 'Mozilla/5.0 (compatible; lcc-outline-generator)';
|
||||
const cache = process.argv[2] ?? process.env.LCC_CACHE_DIR ?? join(tmpdir(), 'lcc-outline-cache');
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const out = new URL('../src/shared/lcc-outline.ts', import.meta.url);
|
||||
|
||||
// Fix-ups applied to names after sentence-casing / extraction.
|
||||
const MAIN_FIXES: Record<string, string> = {
|
||||
'Auxiliary sciences of history': 'Auxiliary sciences of history',
|
||||
};
|
||||
const SUB_FIXES: Record<string, string> = {
|
||||
'Christian Denominations': 'Christian denominations',
|
||||
};
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function get(url: string, file: string): Promise<Buffer> {
|
||||
const p = join(cache, file);
|
||||
if (existsSync(p)) return readFileSync(p);
|
||||
const res = await fetch(url, { headers: { 'User-Agent': UA } });
|
||||
if (!res.ok) throw new Error(`${url}: ${res.status}`);
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
writeFileSync(p, buf);
|
||||
await sleep(1000);
|
||||
return buf;
|
||||
}
|
||||
|
||||
const clean = (s: string) => s.replace(/\s+/g, ' ').trim();
|
||||
function sentenceCase(s: string): string {
|
||||
const t = clean(s).toLowerCase();
|
||||
return t
|
||||
.replace(/(^|\. )([a-z])/g, (_m, a: string, b: string) => a + b.toUpperCase())
|
||||
.replace(/\((general)\)/g, '(General)')
|
||||
.replace(/\b(europe|asia|africa|australia|new zealand|americas?)\b/g, (w) => w.replace(/\b[a-z]/g, (c) => c.toUpperCase()))
|
||||
.replace(/,? etc$/, ', etc.');
|
||||
}
|
||||
|
||||
// Captions over 120 chars (PT lists many literatures) are cut at the last " - " that fits.
|
||||
function shorten(s: string): string {
|
||||
if (s.length <= 120) return s;
|
||||
const parts = s.split(' - ');
|
||||
let r = parts[0]!;
|
||||
for (const p of parts.slice(1)) {
|
||||
if ((r + ' - ' + p).length > 120) break;
|
||||
r += ' - ' + p;
|
||||
}
|
||||
return r.length <= 120 ? r : r.slice(0, 119).trimEnd() + '…';
|
||||
}
|
||||
|
||||
const indexHtml = (await get(INDEX, 'index.html')).toString('utf8');
|
||||
const hrefs = [...new Set([...indexHtml.matchAll(/href="([^"]*lcco_[a-z]+\.pdf)"/g)].map((m) => m[1]!))];
|
||||
if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.length}`);
|
||||
|
||||
const MAIN: Record<string, string> = {};
|
||||
const SUB: Record<string, string> = {};
|
||||
|
||||
for (const href of hrefs) {
|
||||
const name = href.split('/').pop()!;
|
||||
const pdf = join(cache, name);
|
||||
await get(new URL(href, INDEX).href, name);
|
||||
const lines = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\n');
|
||||
|
||||
// Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines.
|
||||
const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l));
|
||||
if (ti < 0) throw new Error(`no title in ${name}`);
|
||||
const tm = lines[ti]!.match(/CLASS ([A-Z])(?:-([A-Z]))? - (.*)$/)!;
|
||||
let title = tm[3]!;
|
||||
for (let i = ti + 1; i < lines.length && lines[i]!.trim() && !lines[i]!.includes('Click'); i++) title += ' ' + lines[i]!.trim();
|
||||
const mainName = sentenceCase(title.replace(/[.,]\s*$/, ''));
|
||||
for (const c of [tm[1]!, tm[2]].filter(Boolean) as string[]) MAIN[c] = MAIN_FIXES[mainName] ?? mainName;
|
||||
|
||||
// Summary list at top: "Subclass QA Mathematics" with indented wrapped continuations.
|
||||
for (let i = ti; i < lines.length; i++) {
|
||||
const l = lines[i]!;
|
||||
if (/^\s*Subclass [A-Z]+\s*$/.test(l) || /^[A-Z]{1,3}\d/.test(l)) break; // detail section starts
|
||||
const m = l.match(/^\s*Subclass ([A-Z]{1,3})\s{2,}(\S.*)$/);
|
||||
if (!m) continue;
|
||||
let cap = m[2]!;
|
||||
while (i + 1 < lines.length && /^\s{4,}\S/.test(lines[i + 1]!) && !/^\s*Subclass /.test(lines[i + 1]!)) cap += ' ' + lines[++i]!.trim();
|
||||
cap = clean(cap).replace(/\.$/, '');
|
||||
SUB[m[1]!] = shorten(SUB_FIXES[cap] ?? cap);
|
||||
}
|
||||
}
|
||||
|
||||
const q = (s: string) => JSON.stringify(s);
|
||||
const rec = (o: Record<string, string>) =>
|
||||
Object.keys(o).sort().map((k) => ` ${k}: ${q(o[k]!)},`).join('\n');
|
||||
|
||||
const src = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand.
|
||||
// Source: Library of Congress Classification Outline, ${INDEX}
|
||||
// (a US government publication). Re-run: node scripts/gen-lcc-outline.ts
|
||||
|
||||
export const MAIN_CLASSES: Record<string, string> = {
|
||||
${rec(MAIN)}
|
||||
};
|
||||
|
||||
export const SUBCLASSES: Record<string, string> = {
|
||||
${rec(SUB)}
|
||||
};
|
||||
|
||||
export function classNames(letters: string): { className: string | null; subclassName: string | null } {
|
||||
const l = letters.trim().toUpperCase();
|
||||
if (!/^[A-Z]{1,3}$/.test(l)) return { className: null, subclassName: null };
|
||||
const className = MAIN_CLASSES[l[0]!] ?? null;
|
||||
const subclassName = SUBCLASSES[l] ?? (l.length === 3 ? (SUBCLASSES[l.slice(0, 2)] ?? null) : null);
|
||||
return { className, subclassName };
|
||||
}
|
||||
`;
|
||||
writeFileSync(out, src);
|
||||
console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`);
|
||||
Reference in new issue
Block a user