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:
swaitsandClaude Fable 5.2 committed 2026-11-18 10:19:32 -07:00
1 parent 468cafc6db
commit b5defb4e4f
46 files changed
+1957 -406

No files matched your search

+386 -117
View File
@@ -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);
+81
View File
@@ -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);
}
+51 -5
View File
@@ -10,20 +10,20 @@ const found: Resolution = {
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
};
function setup(resolve = async () => found) {
function setup(resolve = async () => found, port?: number) {
const db = openDb(':memory:');
const events = createEventBus();
const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0] });
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} });
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
const app = createApp({
db, jobs, resolver, events,
db, jobs, resolver, events, port,
renderCardsPdf: async (cards, opts) => { pdfCalls.push({ cards, opts }); return new TextEncoder().encode('%PDF-stub'); },
renderCalibrationPdf: async () => new TextEncoder().encode('%PDF-cal'),
classNames: (l) => ({ className: 'Class ' + l[0], subclassName: 'Sub ' + l }),
});
const req = (method: string, path: string, json?: unknown) =>
app.request(path, { method, ...(json === undefined ? {} : { body: JSON.stringify(json), headers: { 'content-type': 'application/json' } }) });
const req = (method: string, path: string, json?: unknown, extra: Record<string, string> = {}) =>
app.request(path, { method, headers: { ...(json === undefined ? {} : { 'content-type': 'application/json' }), ...extra }, ...(json === undefined ? {} : { body: JSON.stringify(json) }) });
return { db, jobs, app, req, pdfCalls, events };
}
@@ -176,3 +176,49 @@ test('events stream delivers changes and cleans up on disconnect', async () => {
await res2.body!.cancel();
assert.equal(events.listenerCount(), 0);
});
test('state-changing requests from another origin are refused', async () => {
const { req, db } = setup(undefined, 4321);
const ok = ['http://localhost:4321', 'http://127.0.0.1:4321'];
const bad = ['http://evil.example', 'http://localhost:9999', 'http://localhost:4321.evil.com', 'null', 'https://localhost:4321'];
for (const origin of ok) assert.equal((await req('POST', '/api/books/manual', { title: 'T' }, { origin })).status, 200, origin);
for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
for (const origin of bad) {
const r = await req(method, '/api/books/1', method === 'DELETE' ? undefined : { title: 'x' }, { origin });
assert.equal(r.status, 403, `${method} ${origin}`);
}
}
assert.equal(db.listBooks().length, 2);
assert.equal((await req('GET', '/api/books', undefined, { origin: 'http://evil.example' })).status, 200);
assert.equal((await req('POST', '/api/books/manual', { title: 'No origin header' })).status, 200);
});
test('PATCH year must be an integer or null', async () => {
const { req, db, jobs } = setup();
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', year: 2000 })).json() as any;
await jobs.idle();
for (const year of ['abc', 1999.5, true, {}, -4]) {
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year })).status, 400, JSON.stringify(year));
}
assert.equal(db.getBook(m.book.id)!.year, 2000);
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: 2011 })).status, 200);
assert.equal(db.getBook(m.book.id)!.year, 2011);
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: null })).status, 200);
assert.equal(db.getBook(m.book.id)!.year, null);
});
test('retry forgets the book\'s cached source responses', async () => {
const { req, db, jobs } = setup();
const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
await jobs.idle();
db.updateBook(s.book.id, { lccn: '2018012345', title: 'Rust Book' });
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345',
'loc-title:Rust Book|Steve Klabnik', 'ol-data:9780201835953', 'loc-title:Other|X']) db.cache.set(k, 'body');
assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200);
await jobs.idle();
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345', 'loc-title:Rust Book|Steve Klabnik']) {
assert.equal(db.cache.get(k), null, k);
}
assert.equal(db.cache.get('ol-data:9780201835953'), 'body');
assert.equal(db.cache.get('loc-title:Other|X'), 'body');
});
+26
View File
@@ -31,6 +31,8 @@ export function createEventBus(): EventBus {
}
export interface AppDeps {
/** The port the page is served from; the only Origin (on localhost / 127.0.0.1) allowed to change state. */
port?: number;
db: Db; jobs: Jobs; resolver: ResolverLike;
renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf;
classNames: ClassNames;
@@ -58,6 +60,13 @@ function callNumberFields(raw: string): Partial<Book> {
manualOverride: true, confidence: 'manual', source: 'manual' };
}
function cacheKeys(book: Book): string[] {
const keys: string[] = [];
if (book.isbn13) keys.push(`ol-data:${book.isbn13}`, `ol-search:${book.isbn13}`, `loc-isbn:${book.isbn13}`);
if (book.lccn) keys.push(`loc-lccn:${book.lccn}`);
return keys;
}
export function createApp(deps: AppDeps): Hono {
const { db, jobs, resolver, classNames } = deps;
const events = deps.events ?? createEventBus();
@@ -69,6 +78,20 @@ export function createApp(deps: AppDeps): Hono {
return c.json({ error: 'Internal error' }, 500);
});
// A web page on another origin must not be able to drive this local app. Requests without an
// Origin header (curl, tests, same-origin GET-like navigations) are not browser cross-site requests.
app.use('*', async (c, next) => {
const method = c.req.method;
const origin = c.req.header('origin');
if (origin !== undefined && (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE')) {
const port = deps.port ?? (new URL(c.req.url).port || '80');
if (origin !== `http://localhost:${port}` && origin !== `http://127.0.0.1:${port}`) {
return c.json({ error: 'Cross-origin request refused' }, 403);
}
}
await next();
});
async function body(c: Context): Promise<Record<string, unknown>> {
try {
const v = await c.req.json();
@@ -189,6 +212,9 @@ export function createApp(deps: AppDeps): Hono {
app.post('/api/books/:id/retry', (c) => {
const book = bookParam(c);
if (book.manualOverride) throw new HttpError(400, 'This call number was entered by hand, so there is nothing to look up');
// "Look up again" must really ask again, so forget what the sources told us for this book.
for (const key of cacheKeys(book)) db.cache.delete(key);
if (book.title) db.cache.deletePrefix(`loc-title:${book.title}|`);
const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!;
events.emitBook(updated);
jobs.enqueue(book.id);
+8 -2
View File
@@ -3,7 +3,7 @@ import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts';
import type { SourceCache } from './sources/http.ts';
import type { ForgettableCache, SourceCache } from './sources/http.ts';
export type { SourceCache };
export interface NewBook {
@@ -26,7 +26,7 @@ export interface Db {
listPendingIds(): number[];
getSettings(): Settings;
putSettings(s: Settings): void;
cache: SourceCache;
cache: ForgettableCache;
close(): void;
}
@@ -169,6 +169,12 @@ export function openDb(path: string): Db {
db.prepare('INSERT INTO source_cache (key, body) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET body = excluded.body')
.run(key, body);
},
delete(key) {
db.prepare('DELETE FROM source_cache WHERE key = ?').run(key);
},
deletePrefix(prefix) {
db.prepare('DELETE FROM source_cache WHERE substr(key, 1, length(?)) = ?').run(prefix, prefix);
},
},
close() { db.close(); },
};
+123 -5
View File
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { openDb } from './db.ts';
import { createJobs } from './jobs.ts';
import { createJobs, DEFAULT_RETRY_DELAYS_MS } from './jobs.ts';
import type { ResolverLike } from './jobs.ts';
import type { Book, Resolution } from '../shared/types.ts';
@@ -13,12 +13,13 @@ const found: Resolution = {
reason: null,
};
function setup(resolve: ResolverLike['resolve']) {
function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) {
const db = openDb(':memory:');
const changes: Book[] = [];
const logs: string[] = [];
const resolver: ResolverLike = { resolve, search: async () => [] };
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0, 0, 0] });
return { db, jobs, changes };
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: delays, log: (l) => logs.push(l) });
return { db, jobs, changes, logs };
}
test('success resolves the book and emits changes', async () => {
@@ -37,7 +38,7 @@ test('success resolves the book and emits changes', async () => {
test('no call number -> needs_attention with reason, metadata kept', async () => {
const { db, jobs } = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' }));
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' });
jobs.enqueue(book.id);
await jobs.idle();
const b = db.getBook(book.id)!;
@@ -140,3 +141,120 @@ test('deleting a book mid-queue is harmless', async () => {
await jobs.idle();
assert.equal(db.getBook(book.id), null);
});
test('default retry delays are 5 s, 30 s, 120 s', () => {
assert.deepEqual(DEFAULT_RETRY_DELAYS_MS, [5000, 30000, 120000]);
});
test('a waiting retry does not block the books behind it', async () => {
const order: string[] = [];
let aCalls = 0;
const { db, jobs } = setup(async (i) => {
if (i.isbn13 === '9781593278281' && ++aCalls === 1) throw new TemporaryError('LoC did not answer');
order.push(i.isbn13!);
return found;
}, [60, 60, 60]);
const a = db.insertPending({ isbn13: '9781593278281', title: 'a' }).book;
const b = db.insertPending({ isbn13: '9780201835953', title: 'b' }).book;
jobs.enqueue(a.id); jobs.enqueue(b.id);
await jobs.idle();
assert.deepEqual(order, ['9780201835953', '9781593278281']);
assert.equal(db.getBook(a.id)!.status, 'resolved');
});
test('a book waiting for a retry stays pending with a progress note, cleared when it resolves', async () => {
let calls = 0;
const { db, jobs, changes } = setup(async () => {
if (++calls === 1) throw new TemporaryError('Network error for https://lx2.loc.gov/sru/lcdb: fetch failed');
return found;
}, [40, 40, 40]);
const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' });
jobs.enqueue(book.id);
await new Promise((r) => setTimeout(r, 15));
const mid = db.getBook(book.id)!;
assert.equal(mid.status, 'pending');
assert.equal(mid.attentionReason, 'Library of Congress did not answer. Trying again shortly.');
assert.ok(changes.some((c) => c.attentionReason === mid.attentionReason), 'a change was emitted');
await jobs.idle();
const done = db.getBook(book.id)!;
assert.equal(done.status, 'resolved');
assert.equal(done.attentionReason, null);
});
test('retry timers are unref\'d', async () => {
const real = globalThis.setTimeout;
const made: ReturnType<typeof setTimeout>[] = [];
globalThis.setTimeout = ((fn: () => void, ms?: number) => { const t = real(fn, ms); made.push(t); return t; }) as typeof setTimeout;
try {
const { db, jobs } = setup(async () => { throw new TemporaryError('x'); }, [60_000]);
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
jobs.enqueue(book.id);
await new Promise((r) => real(r, 20));
assert.equal(made.length, 1);
assert.equal(made[0]!.hasRef(), false);
jobs.enqueue(book.id); // cancels the wait; ends the test cleanly
} finally { globalThis.setTimeout = real; }
});
test('only the final attempt asks the resolver to tolerate LoC failure', async () => {
const flags: (boolean | undefined)[] = [];
const { db, jobs } = setup(async (_i, o) => {
flags.push(o?.tolerateLocFailure);
if (flags.length < 4) throw new TemporaryError('blocked');
return found;
});
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
jobs.enqueue(book.id);
await jobs.idle();
assert.deepEqual(flags, [false, false, false, true]);
assert.equal(db.getBook(book.id)!.status, 'resolved');
});
test('"Look up again" while waiting restarts the retries at once', async () => {
let calls = 0;
const { db, jobs } = setup(async () => { if (++calls === 1) throw new TemporaryError('x'); return found; }, [60_000]);
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
jobs.enqueue(book.id);
await new Promise((r) => setTimeout(r, 15));
assert.equal(db.getBook(book.id)!.status, 'pending');
jobs.enqueue(book.id);
await jobs.idle();
assert.equal(db.getBook(book.id)!.status, 'resolved');
});
test('one log line per attempt: ISBN, outcome and elapsed ms', async () => {
let calls = 0;
const { db, jobs, logs } = setup(async () => { if (++calls === 1) throw new TemporaryError('timed out'); return found; });
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
jobs.enqueue(book.id);
await jobs.idle();
assert.equal(logs.length, 2);
assert.match(logs[0]!, /9781593278281.*timed out.*\d+ ms/);
assert.match(logs[1]!, /9781593278281.*QA76\.73\.R87 K53 2018 \(loc-isbn\).* in \d+ ms/);
const t = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' }));
const nb = t.db.insertPending({ title: 'Some Title', authors: ['A'] }).book;
t.jobs.enqueue(nb.id);
await t.jobs.idle();
assert.match(t.logs[0]!, /Some Title.*No Library of Congress number found.*\d+ ms/);
});
test('lookup metadata fills empty fields but never overwrites what the user typed', async () => {
const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; });
const typed = db.insertPending({ isbn13: '9781593278281', title: 'My Title', authors: ['Me Myself'], publisher: 'Mine', year: 1999 }).book;
const bare = db.insertPending({ isbn13: '9780201835953', title: '9780201835953' }).book;
jobs.enqueue(typed.id); jobs.enqueue(bare.id);
await jobs.idle();
const t = db.getBook(typed.id)!;
assert.deepEqual([t.title, t.authors, t.publisher, t.year], ['My Title', ['Me Myself'], 'Mine', 1999]);
assert.deepEqual(t.subjects, ['Rust']); // was empty, so filled
const b = db.getBook(bare.id)!;
assert.deepEqual([b.title, b.authors, b.publisher, b.year], ['The Rust Book', ['Klabnik, Steve'], 'No Starch', 2018]);
});
test('an LCCN placeholder title counts as empty', async () => {
const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; });
const { book } = db.insertPending({ lccn: '88005934', title: '88005934' });
jobs.enqueue(book.id);
await jobs.idle();
assert.equal(db.getBook(book.id)!.title, 'The Rust Book');
});
+104 -58
View File
@@ -2,6 +2,8 @@ import type { Book, BookMeta, ResolveInput } from '../shared/types.ts';
import type { Db } from './db.ts';
import type { Resolver } from './resolve/resolver.ts';
export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
export type ResolverLike = Resolver;
export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise<void> }
@@ -14,86 +16,118 @@ function defaultIsTemporary(e: unknown): boolean {
return false;
}
function sleep(ms: number): Promise<void> {
if (ms <= 0) return Promise.resolve();
return new Promise((resolve) => { setTimeout(resolve, ms).unref(); });
/** What the page shows while a book waits for another try. */
export function retryNote(message: string): string {
const who = /loc\.gov|Library of Congress/i.test(message) ? 'Library of Congress'
: /openlibrary|Open Library/i.test(message) ? 'Open Library' : 'A lookup service';
return `${who} did not answer. Trying again shortly.`;
}
export function createJobs(deps: {
db: Db; resolver: ResolverLike; onChange: (book: Book) => void;
retryDelaysMs?: number[]; isTemporary?: (e: unknown) => boolean;
log?: (line: string) => void;
}): Jobs {
const { db, resolver, onChange } = deps;
const delays = deps.retryDelaysMs ?? [30000, 120000, 600000];
const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
const isTemporary = deps.isTemporary ?? defaultIsTemporary;
const log = deps.log ?? ((line: string) => console.log(line));
const queue: number[] = [];
const queued = new Set<number>();
const attempts = new Map<number, number>();
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
let running: Promise<void> | null = null;
let idlers = 0;
let wake: (() => void)[] = [];
const notify = () => { const w = wake; wake = []; for (const f of w) f(); };
function emit(id: number, patch: Parameters<Db['updateBook']>[1]): void {
const b = db.updateBook(id, patch);
if (b) onChange(b);
}
/** Lookup metadata only fills what is empty; the placeholder title (the ISBN or LCCN) counts as empty. */
function applyMeta(id: number, meta: BookMeta): void {
const cur = db.getBook(id);
if (!cur) return;
const patch: Parameters<Db['updateBook']>[1] = {
subtitle: meta.subtitle ?? cur.subtitle ?? undefined,
publisher: meta.publisher ?? cur.publisher ?? undefined,
year: meta.year ?? cur.year ?? undefined,
subjects: meta.subjects.length ? meta.subjects : cur.subjects,
lccn: meta.lccn ?? cur.lccn ?? undefined,
};
// A hand-edited book keeps the title and authors the user typed.
if (!cur.manualOverride) {
if (meta.title) patch.title = meta.title;
if (meta.authors.length) patch.authors = meta.authors;
}
emit(id, patch);
const patch: Parameters<Db['updateBook']>[1] = {};
if (meta.title && (cur.title === cur.isbn13 || cur.title === cur.lccn || !cur.title.trim())) patch.title = meta.title;
if (meta.authors.length && cur.authors.length === 0) patch.authors = meta.authors;
if (meta.subtitle && !cur.subtitle) patch.subtitle = meta.subtitle;
if (meta.publisher && !cur.publisher) patch.publisher = meta.publisher;
if (meta.year && !cur.year) patch.year = meta.year;
if (meta.subjects.length && cur.subjects.length === 0) patch.subjects = meta.subjects;
if (meta.lccn && !cur.lccn) patch.lccn = meta.lccn;
if (Object.keys(patch).length) emit(id, patch);
}
async function lookup(id: number): Promise<void> {
for (let attempt = 0; ; attempt++) {
const book = db.getBook(id);
if (!book || book.status !== 'pending') return;
const input: ResolveInput = {};
if (book.isbn13) input.isbn13 = book.isbn13;
if (book.lccn) input.lccn = book.lccn;
if (!book.isbn13) {
input.title = book.title;
if (book.authors[0]) input.author = book.authors[0];
function schedule(id: number, delayMs: number): void {
if (delayMs <= 0) { queued.add(id); queue.push(id); start(); return; }
const t = setTimeout(() => {
waiting.delete(id);
queued.add(id); queue.push(id);
start();
notify();
}, delayMs);
// Do not hold the process open for a retry, unless a test is awaiting idle().
if (idlers === 0) t.unref();
waiting.set(id, t);
}
async function attempt(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.status !== 'pending') { attempts.delete(id); return; }
const n = attempts.get(id) ?? 0;
const final = n >= delays.length;
const input: ResolveInput = {};
if (book.isbn13) input.isbn13 = book.isbn13;
if (book.lccn) input.lccn = book.lccn;
if (!book.isbn13) {
input.title = book.title;
if (book.authors[0]) input.author = book.authors[0];
}
if (book.year) input.year = book.year;
const label = book.isbn13 ?? book.title;
const started = Date.now();
const took = () => `${Date.now() - started} ms`;
try {
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final });
attempts.delete(id);
const cur = db.getBook(id);
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
const dewey = res.dewey ?? cur.dewey ?? undefined;
if (cur.manualOverride) {
emit(id, { dewey });
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
} else if (res.callNumber) {
emit(id, {
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
source: res.source, dewey, status: 'resolved', attentionReason: null,
});
log(`[lookup] ${label}: ${res.callNumber} (${res.source}) in ${took()}`);
} else {
const reason = res.reason ?? 'No Library of Congress number found';
emit(id, { dewey, status: 'needs_attention', attentionReason: reason });
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
}
if (book.year) input.year = book.year;
try {
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m) });
const cur = db.getBook(id);
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
const dewey = res.dewey ?? cur.dewey ?? undefined;
if (cur.manualOverride) {
emit(id, { dewey });
} else if (res.callNumber) {
emit(id, {
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
source: res.source, dewey, status: 'resolved', attentionReason: null,
});
} else {
emit(id, { dewey, status: 'needs_attention', attentionReason: res.reason ?? 'No Library of Congress number found' });
}
return;
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && attempt < delays.length) {
await sleep(delays[attempt]!);
continue;
}
const cur = db.getBook(id);
if (cur && !cur.manualOverride) {
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
}
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && !final) {
attempts.set(id, n + 1);
const delay = delays[n]!;
log(`[lookup] ${label}: attempt ${n + 1} failed, ${message}; trying again in ${Math.round(delay / 1000)} s (${took()})`);
if (db.getBook(id)?.status === 'pending') emit(id, { attentionReason: retryNote(message) });
schedule(id, delay);
return;
}
attempts.delete(id);
log(`[lookup] ${label}: failed, ${message} in ${took()}`);
const cur = db.getBook(id);
if (cur && !cur.manualOverride) {
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
}
}
}
@@ -101,17 +135,20 @@ export function createJobs(deps: {
while (queue.length) {
const id = queue.shift()!;
queued.delete(id);
try { await lookup(id); } catch { /* a failure on one book must not stop the queue */ }
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
}
}
function start(): void {
if (running) return;
running = drain().finally(() => { running = null; if (queue.length) start(); });
running = drain().finally(() => { running = null; if (queue.length) start(); notify(); });
}
return {
enqueue(id) {
// A fresh request (scan, "Look up again") overrides any wait and starts the retries over.
const t = waiting.get(id);
if (t) { clearTimeout(t); waiting.delete(id); attempts.delete(id); }
if (queued.has(id)) return;
queued.add(id);
queue.push(id);
@@ -119,7 +156,16 @@ export function createJobs(deps: {
},
resume() { for (const id of db.listPendingIds()) this.enqueue(id); },
async idle() {
while (running || queue.length) await running;
idlers++;
for (const t of waiting.values()) t.ref();
try {
while (running || queue.length || waiting.size) {
if (running) await running;
else await new Promise<void>((r) => { wake.push(r); });
}
} finally {
if (--idlers === 0) for (const t of waiting.values()) t.unref();
}
},
};
}
+5 -5
View File
@@ -1,5 +1,6 @@
import { existsSync, readFileSync, statSync } from 'node:fs';
import { extname, join, normalize, resolve as resolvePath } from 'node:path';
import { extname, join, resolve as resolvePath } from 'node:path';
import { staticPath } from './static.ts';
import { serve } from '@hono/node-server';
import { openDb } from './db.ts';
import { createJobs } from './jobs.ts';
@@ -24,15 +25,14 @@ const resolver = createResolver({ fetch: globalThis.fetch, cache: db.cache });
const jobs = createJobs({
db, resolver, onChange: (b) => events.emitBook(b), isTemporary: (e) => e instanceof TemporaryError,
});
const app = createApp({ db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events });
const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events });
app.get('*', (c) => {
if (!existsSync(join(webRoot, 'index.html'))) {
return c.text('The web app has not been built. Run `npm run build` and reload.', 503);
}
const rel = normalize(decodeURIComponent(c.req.path)).replace(/^([/\\])+/, '');
const file = resolvePath(webRoot, rel === '' ? 'index.html' : rel);
if (!file.startsWith(webRoot) || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404);
const file = staticPath(webRoot, c.req.path);
if (!file || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404);
return c.body(readFileSync(file), 200, { 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream' });
});
+12
View File
@@ -68,3 +68,15 @@ test('earlier tier wins over later tiers', () => {
test('unparseable only -> null', () => {
assert.equal(chooseCallNumber({ ...none, olEdition: raws('[E]', 'Fic') }, m), null);
});
test('literature class-only number with the author cutter gets a title cutter', () => {
const r = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'Dune', year: 2010 });
assert.equal(r?.callNumber, 'PS3552.R89 D86 2010');
const the = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'The Dune' });
assert.equal(the?.callNumber, 'PS3552.R89 D86');
});
test('non-literature class-only numbers still get the author cutter', () => {
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language', year: 2018 });
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
});
+3 -1
View File
@@ -59,7 +59,9 @@ export function chooseCallNumber(
const approximate = tier === 'locTitle' || tier === 'olWork';
let { cn, complete } = pickMostFrequent(ps);
if (!complete && cn.cutters.length < 3) {
const c = cutterFor(mainEntry(meta.authors, meta.title));
// Literature (P plus one letter) already carries the author as its first cutter; the next one is the title.
const literature = /^P[A-Z]$/.test(cn.letters) && cn.cutters.length >= 1;
const c = cutterFor(literature ? meta.title.trim().replace(/^(a|an|the)\s+/i, '') : mainEntry(meta.authors, meta.title));
cn = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }] };
if (meta.year) cn = withYear(cn, meta.year);
}
+28
View File
@@ -0,0 +1,28 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { normalizeTitle, recordMatches, titlesMatch } from './match.ts';
import type { MarcFields } from '../sources/marc.ts';
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names });
test('normalizeTitle', () => {
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
assert.equal(normalizeTitle('An Introduction!'), 'introduction');
});
test('titlesMatch: equal or prefix, nothing looser', () => {
assert.ok(titlesMatch('The mythical man-month :', 'Mythical Man-Month'));
assert.ok(titlesMatch('Dune', 'Dune Messiah'));
assert.ok(!titlesMatch('Dunes', 'Dune'));
assert.ok(!titlesMatch('', 'Dune'));
assert.ok(titlesMatch('Rust', 'The Rust Programming Language'));
});
test('recordMatches needs title and an author surname', () => {
const r = rec('The mythical man-month', ['Brooks, Frederick P.']);
assert.ok(recordMatches(r, 'The Mythical Man-Month: Essays', 'Frederick P. Brooks'));
assert.ok(recordMatches(r, 'Mythical Man-Month', 'Brooks, Frederick P.'));
assert.ok(!recordMatches(r, 'Mythical Man-Month', 'Tolkien'));
assert.ok(!recordMatches(r, 'Something Else', 'Brooks'));
assert.ok(recordMatches(rec('Dune', ['Smith, Bob', 'Herbert, Frank']), 'Dune', 'Frank Herbert'));
});
+26
View File
@@ -0,0 +1,26 @@
import { mainEntry } from '../../shared/cutter.ts';
import type { MarcFields } from '../sources/marc.ts';
const plain = (s: string): string =>
s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
/** Lower-case, main title only (before any ":"), no punctuation, no leading article. */
export function normalizeTitle(title: string): string {
return plain(title.split(':')[0]!).replace(/^(a|an|the) /, '');
}
/** Equal, or one is a prefix of the other (a record may carry a longer or shorter main title). */
export function titlesMatch(a: string, b: string): boolean {
const x = normalizeTitle(a);
const y = normalizeTitle(b);
if (!x || !y) return false;
return x === y || x.startsWith(y + ' ') || y.startsWith(x + ' ');
}
/** Does a LoC record plausibly describe this book? Title must match and a 100/700 name must contain the surname. */
export function recordMatches(rec: MarcFields, title: string, author: string): boolean {
if (!rec.meta.title || !titlesMatch(rec.meta.title, title)) return false;
const surname = plain(mainEntry([author], title));
if (!surname) return false;
return rec.names.some((n) => (' ' + plain(n) + ' ').includes(' ' + surname + ' '));
}
+107 -13
View File
@@ -2,6 +2,8 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createResolver, TemporaryError } from './resolver.ts';
import type { SourceCache } from './resolver.ts';
import { createLoc } from '../sources/loc.ts';
import { createOpenLibrary } from '../sources/openlibrary.ts';
import { fixtureFetch } from '../sources/fixture-fetch.ts';
function memCache(): SourceCache & { map: Map<string, string> } {
@@ -102,22 +104,72 @@ test('cache hits are not delayed by the throttle', async () => {
assert.equal(sleeps.length, before);
});
test('two uncached ISBNs are spaced by locIntervalMs', async () => {
const f = fixtureFetch();
const emptyLoc = '<?xml version="1.0"?><zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:numberOfRecords>0</zs:numberOfRecords></zs:searchRetrieveResponse>';
const locSetup = (sleeps: number[]) => {
const urls: string[] = [];
const fetchStub = (async (u: string) => { urls.push(String(u)); return new Response(emptyLoc, { status: 200 }); }) as typeof fetch;
const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
return { loc, urls };
};
test('token bucket: three LoC calls go out at once, the fourth waits one interval', async () => {
const sleeps: number[] = [];
const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
await r.resolve({ isbn13: '9781593278281' });
await r.resolve({ isbn13: '9780201835953' });
const { loc } = locSetup(sleeps);
for (const i of ['1', '2', '3']) await loc.byIsbn(i);
assert.deepEqual(sleeps, []);
await loc.byIsbn('4');
assert.equal(sleeps.length, 1);
assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000, String(sleeps[0]));
});
test('concurrent resolves are also spaced', async () => {
const f = fixtureFetch();
test('token bucket: concurrent callers beyond the burst are spaced one interval apart', async () => {
const sleeps: number[] = [];
const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
await Promise.all([r.resolve({ isbn13: '9781593278281' }), r.resolve({ isbn13: '9780201835953' })]);
assert.equal(sleeps.length, 1);
const { loc } = locSetup(sleeps);
await Promise.all(['1', '2', '3', '4', '5'].map((i) => loc.byIsbn(i)));
assert.equal(sleeps.length, 2);
assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000);
assert.ok(sleeps[1]! > 11000 && sleeps[1]! <= 12000);
});
test('LoC tries https first and the port-210 endpoint only as the fallback', async () => {
const { loc, urls } = locSetup([]);
await loc.byIsbn('1');
assert.ok(urls[0]!.startsWith('https://lx2.loc.gov/sru/lcdb?'), urls[0]);
const urls2: string[] = [];
const failFirst = (async (u: string) => {
urls2.push(String(u));
if (urls2.length === 1) throw new TypeError('down');
return new Response(emptyLoc, { status: 200 });
}) as typeof fetch;
await createLoc({ fetch: failFirst, cache: memCache(), intervalMs: 0, sleep: noSleep }).byIsbn('1');
assert.equal(urls2.length, 2);
assert.ok(urls2[1]!.startsWith('http://lx2.loc.gov:210/lcdb?'), urls2[1]);
});
test('a LoC response with no record is not cached; one with a record is', async () => {
const cache = memCache();
const loc = createLoc({ fetch: (async () => new Response(emptyLoc)) as typeof fetch, cache, intervalMs: 0, sleep: noSleep });
assert.deepEqual(await loc.byIsbn('9780999999998'), []);
assert.equal(cache.map.size, 0);
const f = fixtureFetch();
const loc2 = createLoc({ fetch: f.fetch, cache, intervalMs: 0, sleep: noSleep });
assert.equal((await loc2.byIsbn('9781593278281')).length, 1);
assert.equal(cache.map.size, 1);
});
test('an Open Library miss is not cached, so the next lookup asks again', async () => {
const cache = memCache();
let n = 0;
const miss = (async () => { n++; return new Response('{}'); }) as typeof fetch;
const ol = createOpenLibrary({ fetch: miss, cache });
assert.equal(await ol.edition('9780999999998'), null);
assert.equal(await ol.work('9780999999998'), null);
assert.equal(cache.map.size, 0);
await ol.edition('9780999999998');
assert.equal(n, 3);
const f = fixtureFetch();
await createOpenLibrary({ fetch: f.fetch, cache }).edition('9781593278281');
assert.deepEqual([...cache.map.keys()], ['ol-data:9781593278281']);
});
test('LCCN only', async () => {
@@ -138,10 +190,10 @@ test('title and author only uses the LoC title tier', async () => {
assert.ok(res.meta);
});
test('falls back to the HTTPS SRU endpoint when the first refuses', async () => {
test('falls back to the port-210 SRU endpoint when https fails', async () => {
const f = fixtureFetch();
const wrapped = (async (input: string | URL | Request, init?: RequestInit) => {
if (String(input).includes(':210')) throw new TypeError('connect ECONNREFUSED');
if (String(input).startsWith('https://lx2.loc.gov')) throw new TypeError('connect ECONNREFUSED');
return f.fetch(input as string, init);
}) as typeof fetch;
const res = await createResolver({ fetch: wrapped, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
@@ -156,8 +208,50 @@ test('search by title and author', async () => {
});
test('lccn.loc.gov "Record not found" (HTTP 200) is an empty result, not a block page', async () => {
const { createLoc } = await import('../sources/loc.ts');
const fetchStub = (async () => new Response('<?xml version="1.0" encoding="UTF-8"?><error>Record not found for LCCN: 2003054578.</error>', { status: 200 })) as typeof fetch;
const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 0, sleep: noSleep });
assert.deepEqual(await loc.byLccn('2003054578'), []);
});
test('title tier is skipped when the book has no author', async () => {
const f = fixtureFetch();
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ title: 'The Mythical Man-Month' });
assert.equal(res.callNumber, null);
assert.equal(f.locCalls().length, 0);
});
test('title tier ignores records for a different author', async () => {
const f = fixtureFetch();
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
.resolve({ title: 'The Mythical Man-Month', author: 'Tolkien, J. R. R.' });
assert.ok(f.locCalls().length > 0);
assert.equal(res.callNumber, null);
});
test('title tier ignores records for a different title', async () => {
const f = fixtureFetch();
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
.resolve({ title: 'The Mythical Dragon', author: 'Frederick Brooks' });
assert.equal(res.callNumber, null);
});
function locDown(f: ReturnType<typeof fixtureFetch>): typeof fetch {
return (async (input: string | URL | Request, init?: RequestInit) =>
/loc\.gov/.test(String(input)) ? new Response('down', { status: 503 }) : f.fetch(input as string, init)) as typeof fetch;
}
test('tolerateLocFailure: Open Library numbers are used when the LoC is down', async () => {
const f = fixtureFetch();
const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep });
await assert.rejects(r.resolve({ isbn13: '9780441172719' }), TemporaryError);
const res = await r.resolve({ isbn13: '9780441172719' }, { tolerateLocFailure: true });
assert.ok(res.callNumber, res.reason ?? '');
assert.match(res.callNumber!, /^PS3558/);
assert.ok(res.source === 'ol-edition' || res.source === 'ol-work');
});
test('tolerateLocFailure: nothing from Open Library either still fails', async () => {
const f = fixtureFetch();
const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep });
await assert.rejects(r.resolve({ isbn13: '9780999999998' }, { tolerateLocFailure: true }), TemporaryError);
});
+27 -6
View File
@@ -6,13 +6,20 @@ import { createOpenLibrary } from '../sources/openlibrary.ts';
import type { OlInfo } from '../sources/openlibrary.ts';
import type { MarcFields } from '../sources/marc.ts';
import { TemporaryError } from '../sources/http.ts';
import { recordMatches } from './match.ts';
import type { SourceCache } from '../sources/http.ts';
export { TemporaryError };
export type { SourceCache };
export interface ResolveOpts {
onMeta?: (meta: BookMeta) => void;
/** Last-attempt mode: a Library of Congress failure is not fatal; use Open Library's numbers if it has any. */
tolerateLocFailure?: boolean;
}
export interface Resolver {
resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise<Resolution>;
resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution>;
search(title: string, author: string): Promise<SearchResult[]>;
}
@@ -50,7 +57,16 @@ export function createResolver(deps: {
sleep: deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
});
async function resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise<Resolution> {
async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
// In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup.
let locError: unknown = null;
const locCall = async (fn: () => Promise<MarcFields[]>): Promise<MarcFields[]> => {
if (locError) return [];
try { return await fn(); } catch (e) {
if (opts?.tolerateLocFailure && e instanceof TemporaryError) { locError = e; return []; }
throw e;
}
};
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
let notified = false;
const notify = (m: BookMeta | null) => {
@@ -82,11 +98,11 @@ export function createResolver(deps: {
let locRecs: MarcFields[] = [];
let exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn';
if (lccn) {
locRecs = await loc.byLccn(lccn);
locRecs = await locCall(() => loc.byLccn(lccn));
if (locRecs.length > 0) exactSource = 'loc-lccn';
}
if (isbn && lccOf(locRecs).length === 0) {
const recs = await loc.byIsbn(isbn);
const recs = await locCall(() => loc.byIsbn(isbn));
if (recs.length > 0) { locRecs = recs; exactSource = 'loc-isbn'; }
}
@@ -112,8 +128,11 @@ export function createResolver(deps: {
work ??= await getWork(false);
const m = metaOf([work?.meta]);
const title = m?.title ?? input.title;
if (title) {
locTitleRecs = await loc.byTitle(title, m?.authors[0] ?? input.author ?? '');
const author = m?.authors[0] ?? input.author ?? '';
// Without an author a title search cannot be verified, so the tier is skipped.
if (title && author) {
const found = await locCall(() => loc.byTitle(title, author));
locTitleRecs = found.filter((r) => recordMatches(r, title, author));
chosen = chooseCallNumber(
{ locExact: [], olEdition: [], locTitle: lccOf(locTitleRecs), olWork: [] },
forChoose(m), exactSource,
@@ -141,6 +160,8 @@ export function createResolver(deps: {
confidence: chosen.confidence, source: chosen.source, dewey, reason: null,
};
}
// Open Library had nothing and the LoC could not be asked: report that, not "no number found".
if (locError) throw locError;
return {
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey,
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
+27
View File
@@ -0,0 +1,27 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { getText, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts';
test('every request carries a 15 s abort signal', async () => {
assert.equal(REQUEST_TIMEOUT_MS, 15_000);
let signal: AbortSignal | undefined;
await getText((async (_u: string, init?: RequestInit) => { signal = init?.signal ?? undefined; return new Response('ok'); }) as typeof fetch, 'http://x/');
assert.ok(signal instanceof AbortSignal);
assert.equal(signal.aborted, false);
});
test('a request that never answers becomes a TemporaryError', async () => {
const hang = ((_u: string, init?: RequestInit) => new Promise((_res, rej) => {
init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason));
})) as typeof fetch;
await assert.rejects(getText(hang, 'http://x/', 20), (e: Error) => e instanceof TemporaryError && /Timed out/.test(e.message));
});
test('a body that stalls past the timeout is a TemporaryError too', async () => {
const slowBody = (async (_u: string, init?: RequestInit) => {
const res = new Response('x');
res.text = () => new Promise((_a, rej) => { init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason)); });
return res;
}) as typeof fetch;
await assert.rejects(getText(slowBody, 'http://x/', 20), TemporaryError);
});
+14 -2
View File
@@ -2,16 +2,27 @@ export class TemporaryError extends Error {}
export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void }
/** The database cache can also forget entries, so "Look up again" really asks again. */
export interface ForgettableCache extends SourceCache {
delete(key: string): void;
deletePrefix(prefix: string): void;
}
export const REQUEST_TIMEOUT_MS = 15_000;
export const USER_AGENT = 'booksorter/0.1 (personal library tool)';
export interface HttpResult { status: number; body: string }
/** One GET. Network errors and 5xx/429 become TemporaryError; other statuses are returned. */
export async function getText(f: typeof fetch, url: string): Promise<HttpResult> {
export async function getText(f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS): Promise<HttpResult> {
const signal = AbortSignal.timeout(timeoutMs);
const timedOut = (e: unknown) => signal.aborted || (e as Error)?.name === 'TimeoutError';
let res: Response;
try {
res = await f(url, { headers: { 'User-Agent': USER_AGENT } });
res = await f(url, { headers: { 'User-Agent': USER_AGENT }, signal });
} catch (e) {
if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`);
throw new TemporaryError(`Network error for ${url}: ${(e as Error).message}`);
}
if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`);
@@ -19,6 +30,7 @@ export async function getText(f: typeof fetch, url: string): Promise<HttpResult>
try {
body = await res.text();
} catch (e) {
if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`);
throw new TemporaryError(`Network error reading ${url}: ${(e as Error).message}`);
}
return { status: res.status, body };
+22 -11
View File
@@ -4,7 +4,9 @@ import type { SourceCache } from './http.ts';
import { parseMarcXml } from './marc.ts';
import type { MarcFields } from './marc.ts';
const SRU_URLS = ['http://lx2.loc.gov:210/lcdb', 'https://lx2.loc.gov/sru/lcdb'];
// https first; port 210 is blocked on some networks, so plain http on 210 is only the fallback.
export const SRU_URLS = ['https://lx2.loc.gov/sru/lcdb', 'http://lx2.loc.gov:210/lcdb'];
export const BURST = 3;
const MAX_INTERVAL_MS = 60_000;
export function isLocXml(body: string): boolean {
@@ -22,19 +24,26 @@ export function createLoc(deps: {
}): Loc {
const baseInterval = deps.intervalMs;
let interval = baseInterval;
let lastSlot: number | null = null;
// Token bucket: BURST tokens, one returns every `interval`. A book's two or three calls go out together;
// the long-run rate is one per interval. Tokens may go negative: that is a queue of reserved future slots.
let tokens = BURST;
let lastRefill = Date.now();
/** Reserve the next request slot synchronously so concurrent callers are spaced too. */
/** Take a token synchronously (so concurrent callers queue up too), then wait if it was not yet available. */
async function throttle(): Promise<void> {
if (interval <= 0) return;
const now = Date.now();
const slot = lastSlot === null ? now : Math.max(now, lastSlot + interval);
lastSlot = slot;
if (slot > now) await deps.sleep(slot - now);
tokens = Math.min(BURST, tokens + (now - lastRefill) / interval);
lastRefill = now;
const wait = tokens >= 1 ? 0 : Math.ceil((1 - tokens) * interval);
tokens -= 1;
if (wait > 0) await deps.sleep(wait);
}
function blocked(): never {
interval = Math.min(interval * 2, MAX_INTERVAL_MS);
lastSlot = Date.now();
tokens = 0; // the next call waits one (doubled) interval from the block
lastRefill = Date.now();
throw new TemporaryError('Library of Congress returned a block page');
}
@@ -63,8 +72,9 @@ export function createLoc(deps: {
if (body === null) throw lastErr;
if (!isLocXml(body)) blocked();
ok();
deps.cache.set(cacheKey, body);
return parseMarcXml(body);
const recs = parseMarcXml(body);
if (recs.length > 0) deps.cache.set(cacheKey, body); // a miss is not cached: asking again may find it
return recs;
}
return {
@@ -79,8 +89,9 @@ export function createLoc(deps: {
if (res.status === 404 || /<error>\s*Record not found/i.test(res.body)) { ok(); return []; }
if (res.status >= 400 || !isLocXml(res.body)) blocked();
ok();
deps.cache.set(key, res.body);
return parseMarcXml(res.body);
const recs = parseMarcXml(res.body);
if (recs.length > 0) deps.cache.set(key, res.body);
return recs;
},
byTitle(title, author) {
const t = title.replace(/"/g, ' ').trim();
+25 -1
View File
@@ -10,7 +10,7 @@ test('SRU wrapped record', () => {
const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml'));
assert.deepEqual(r!.lcc, [{ raw: 'QA76.73.R87 K53 2018', complete: true }]);
assert.match(r!.meta.title!, /Rust/);
assert.ok(r!.meta.authors!.some((a) => a.startsWith('Klabnik')));
assert.ok(r!.meta.authors!.some((a) => a.endsWith('Klabnik')));
assert.equal(r!.meta.year, 2018);
assert.ok(r!.lccn);
});
@@ -53,3 +53,27 @@ test('non-text records (a DVD of the book) contribute no call number', () => {
assert.equal(parseMarcXml(rec('g'))[0]!.meta.title, 'Harry Potter');
assert.equal(parseMarcXml(rec('a'))[0]!.lcc.length, 1);
});
test('authors: 100 only, dates and commas stripped, shown as Forename Surname', () => {
const xml = `<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="100" ind1="1" ind2=" "><subfield code="a">Herbert, Frank,</subfield><subfield code="d">1920-1986.</subfield></datafield>
<datafield tag="245" ind1="1" ind2="0"><subfield code="a">Dune /</subfield></datafield>
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">Whelan, Michael,</subfield><subfield code="d">1950-</subfield></datafield></record>`;
const [r] = parseMarcXml(xml);
assert.deepEqual(r!.meta.authors, ['Frank Herbert']);
assert.deepEqual(r!.names, ['Herbert, Frank', 'Whelan, Michael']);
});
test('authors: 700 only stands in when there is no 100; dates inside $a are removed', () => {
const xml = `<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="245" ind1="1" ind2="0"><subfield code="a">Anthology</subfield></datafield>
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">Brooks, Frederick P., 1931-</subfield></datafield>
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">King, Martin Luther, Jr.,</subfield></datafield></record>`;
const [r] = parseMarcXml(xml);
assert.deepEqual(r!.meta.authors, ['Frederick P. Brooks', 'Martin Luther King Jr.']);
});
test('the Rust fixture shows a plain author name', () => {
const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml'));
assert.ok(r!.meta.authors!.every((a) => !a.includes(',') && !/\d/.test(a)), String(r!.meta.authors));
});
+26 -4
View File
@@ -7,6 +7,8 @@ export interface MarcFields {
lcc: Candidate[];
dewey: string | null;
meta: Partial<BookMeta>;
/** Every 100/700 $a, cleaned but still in "Surname, Forename" form; used to verify title/author matches. */
names: string[];
}
type Node = Record<string, unknown>;
@@ -60,6 +62,25 @@ function sub(f: Field, code: string): string {
function uniq(a: string[]): string[] { return [...new Set(a)]; }
/** Strip trailing punctuation and life dates from a MARC name: "Brooks, Frederick P., 1931-" -> "Brooks, Frederick P." */
export function cleanName(raw: string): string {
let s = raw.trim();
s = s.replace(/[,\s]*\(?\b(?:b\.\s*|d\.\s*|ca\.\s*)?\d{3,4}\??\s*-\s*(?:\d{3,4})?\)?[.,\s]*$/i, '');
s = s.replace(/[\s,;:\/]+$/, '');
// Keep the period of an initial or Jr./Sr.; drop the ISBD full stop after other words.
const last = /([^\s,]+)\.$/.exec(s)?.[1];
if (last && last.length > 1 && !/^(jr|sr)$/i.test(last)) s = s.slice(0, -1);
return s.trim();
}
/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. */
export function displayName(name: string): string {
const parts = name.split(',').map((p) => p.trim()).filter(Boolean);
if (parts.length < 2) return name.trim();
const [surname, forenames, ...suffix] = parts as [string, string, ...string[]];
return [forenames, surname, ...suffix].join(' ');
}
export function parseMarcRecord(rec: Node): MarcFields {
const fields = fieldsOf(rec);
const all = (tag: string) => fields.filter((f) => f.tag === tag);
@@ -83,9 +104,10 @@ export function parseMarcRecord(rec: Node): MarcFields {
const title = f245 ? trimPunct(sub(f245, 'a')) : '';
const subtitle = f245 ? trimPunct(sub(f245, 'b')) : '';
const authors = uniq(
[...all('100'), ...all('700')].map((f) => trimPunct(sub(f, 'a'))).filter(Boolean),
);
const f100 = all('100');
const names = uniq([...f100, ...all('700')].map((f) => cleanName(sub(f, 'a'))).filter(Boolean));
// The 100 is the author; 700s (editors, illustrators, co-authors) only stand in when there is none.
const authors = uniq((f100.length ? f100 : all('700')).map((f) => cleanName(sub(f, 'a'))).filter(Boolean).map(displayName));
const pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0];
const publisher = pub ? trimPunct(sub(pub, 'b')) : '';
@@ -101,7 +123,7 @@ export function parseMarcRecord(rec: Node): MarcFields {
if (publisher) meta.publisher = publisher;
if (ym) meta.year = Number(ym[1]);
if (lccn) meta.lccn = lccn;
return { lccn, lcc, dewey, meta };
return { lccn, lcc, dewey, meta, names };
}
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
+5 -4
View File
@@ -102,7 +102,8 @@ export interface OpenLibrary {
}
export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCache }): OpenLibrary {
async function body(key: string | null, url: string): Promise<string> {
/** Only a response that actually held a record (per `hasRecord`) is cached, so misses are asked again. */
async function body(key: string | null, url: string, hasRecord: (text: string) => boolean = () => true): Promise<string> {
if (key) {
const hit = deps.cache.get(key);
if (hit !== null) return hit;
@@ -111,17 +112,17 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach
// Other 4xx: treat as an empty answer rather than an error.
const text = res.status >= 400 ? '{}' : res.body;
parseJson(text); // reject HTML overload pages before they reach the cache
if (key && res.status < 400) deps.cache.set(key, text);
if (key && res.status < 400 && hasRecord(text)) deps.cache.set(key, text);
return text;
}
return {
async edition(isbn) {
const url = `https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&jscmd=data&format=json`;
return parseEdition(await body(`ol-data:${isbn}`, url), isbn);
return parseEdition(await body(`ol-data:${isbn}`, url, (t) => parseEdition(t, isbn) !== null), isbn);
},
async work(isbn) {
const url = `https://openlibrary.org/search.json?isbn=${isbn}&fields=${FIELDS}`;
return parseWork(await body(`ol-search:${isbn}`, url));
return parseWork(await body(`ol-search:${isbn}`, url, (t) => parseWork(t) !== null));
},
async search(title, author) {
const q = new URLSearchParams();
+14
View File
@@ -0,0 +1,14 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { staticPath } from './static.ts';
test('static paths stay inside the web root', () => {
const root = '/srv/dist/web';
assert.equal(staticPath(root, '/'), '/srv/dist/web/index.html');
assert.equal(staticPath(root, '/assets/app.js'), '/srv/dist/web/assets/app.js');
assert.equal(staticPath(root, '/../webx/secret'), '/srv/dist/web/webx/secret');
assert.equal(staticPath(root, '..%2Fwebx/secret'), null);
assert.equal(staticPath(root, '/%2e%2e/%2e%2e/etc/passwd'), '/srv/dist/web/etc/passwd');
assert.equal(staticPath(root, '/bad%zz'), null);
assert.equal(staticPath(root, '/a%00b'), null);
});
+12
View File
@@ -0,0 +1,12 @@
import { sep, normalize, resolve as resolvePath } from 'node:path';
/** Map a request path to a file under `root`, or null when it would leave the root. Does not check existence. */
export function staticPath(root: string, urlPath: string): string | null {
let decoded: string;
try { decoded = decodeURIComponent(urlPath); } catch { return null; }
if (decoded.includes('\0')) return null;
const rel = normalize(decoded).replace(/^([/\\])+/, '');
const file = resolvePath(root, rel === '' ? 'index.html' : rel);
// Compare with a trailing separator so a sibling like "<root>x" cannot pass as inside "<root>".
return file.startsWith(root.endsWith(sep) ? root : root + sep) ? file : null;
}
+17
View File
@@ -16,6 +16,7 @@ test('format', () => {
['PS-3558.00000000.E63 D8 2005', 'PS3558.E63 D8 2005'],
['PZ7.R79835 Har 1998', 'PZ7.R79835 Har 1998'],
['qa76.73.r87 k53 2018', 'QA76.73.R87 K53 2018'],
['QA76.73.R87x K53 2018', 'QA76.73.R87x K53 2018'],
];
for (const [i, o] of cases) assert.equal(fmt(i), o, i);
});
@@ -54,3 +55,19 @@ test('sort order', () => {
shuffled.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
assert.deepEqual(shuffled, want);
});
test('cutter with one trailing lower-case letter', () => {
const cn = parseCallNumber('QA76.73.R87x K53 2018')!;
assert.deepEqual(cn.cutters, [{ letter: 'R', digits: '87x' }, { letter: 'K', digits: '53' }]);
assert.equal(cn.suffix, '2018');
assert.deepEqual(parseCallNumber('QA76.73.C15K47 1988')!.cutters, [{ letter: 'C', digits: '15' }, { letter: 'K', digits: '47' }]);
assert.deepEqual(parseCallNumber('qa76.73.r87 k53 2018')!.cutters.map((c) => c.letter + c.digits), ['R87', 'K53']);
});
test('years with a trailing copy letter', () => {
const w = (raw: string, y: number) => formatCallNumber(withYear(parseCallNumber(raw)!, y));
assert.equal(w('PS3562.E353 B3 1997c', 2005), 'PS3562.E353 B3 2005');
assert.equal(w('PS3562.E353 B3 2005b', 2007), 'PS3562.E353 B3 2007');
assert.equal(w('PZ7.R79835 Har 1998', 2001), 'PZ7.R79835 Har 2001');
assert.equal(hasYear(parseCallNumber('PS3562.E353 B3 1997c')!), true);
});
+4 -2
View File
@@ -16,7 +16,8 @@ export function parseCallNumber(raw: string): CallNumber | null {
let rest = m[4]!;
const cutters: { letter: string; digits: string }[] = [];
while (cutters.length < 3) {
const c = /^\s*\.?\s*([A-Za-z])(\d+)/.exec(rest);
// A cutter may carry one trailing lower-case letter ("R87x") when nothing alphanumeric follows it.
const c = /^\s*\.?\s*([A-Za-z])(\d+(?:[a-z](?![A-Za-z0-9]))?)/.exec(rest);
if (!c) break;
cutters.push({ letter: c[1]!.toUpperCase(), digits: c[2]! });
rest = rest.slice(c[0].length);
@@ -58,7 +59,8 @@ export function cardLines(cn: CallNumber): [string, string] {
return [line1, line2];
}
const YEAR = /\b(1[4-9]\d\d|20\d\d)\b/;
// A year may carry a copy-letter: 1997c.
const YEAR = /\b(1[4-9]\d\d|20\d\d)[a-z]?\b/;
export function hasYear(cn: CallNumber): boolean { return YEAR.test(cn.suffix); }
export function withYear(cn: CallNumber, year: number): CallNumber {
+8
View File
@@ -16,3 +16,11 @@ test('mainEntry', () => {
assert.equal(mainEntry(['Steve Klabnik'], 'x'), 'Klabnik');
assert.equal(mainEntry([], 'The Mythical Man-Month'), 'Mythical Man-Month');
});
test('mainEntry: both name forms and suffixes give the surname', () => {
assert.equal(mainEntry(['Herbert, Frank'], 'x'), 'Herbert');
assert.equal(mainEntry(['Frank Herbert'], 'x'), 'Herbert');
assert.equal(mainEntry(['Martin Luther King Jr.'], 'x'), 'King');
assert.equal(mainEntry(['King, Martin Luther, Jr.'], 'x'), 'King');
assert.equal(mainEntry(['Martin Luther King, Jr.'], 'x'), 'King');
});
+12 -3
View File
@@ -51,12 +51,21 @@ export function cutterFor(name: string): string {
return out;
}
const SUFFIX = /^(jr|sr|ii|iii|iv|esq|md|phd)\.?$/i;
export function mainEntry(authors: string[], title: string): string {
const a = authors[0]?.trim();
const a = authors[0]?.trim().replace(/[\s,;]+$/, '');
if (a) {
if (a.includes(',')) return a.split(',')[0]!.trim();
if (a.includes(',')) {
const head = a.split(',')[0]!.trim();
// "Frank Herbert, Jr." has its suffix after the comma; "Herbert, Frank" has the forenames.
const words = head.split(/\s+/);
if (words.length > 1 && a.split(',').slice(1).every((p) => SUFFIX.test(p.trim()))) return words[words.length - 1]!;
return head;
}
const words = a.split(/\s+/);
return words[words.length - 1]!;
while (words.length > 1 && SUFFIX.test(words[words.length - 1]!)) words.pop();
return words[words.length - 1]!.replace(/\.$/, '');
}
return title.trim().replace(/^(a|an|the)\s+/i, '');
}
+60
View File
@@ -0,0 +1,60 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import type { Book } from '../shared/types.ts';
import { elapsedText, pdfLabel, queueHeader, queueSplit, queueTabLabel, rowState, sessionSummary } from './bookstate.ts';
function book(id: number, over: Partial<Book>): Book {
return {
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], 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: '', updatedAt: '', ...over,
};
}
const ready = (id: number) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id });
const looking = (id: number) => book(id, {});
const attention = (id: number) => book(id, { status: 'needs_attention', attentionReason: 'No match' });
test('a pending book is "looking", never "no call number"', () => {
assert.deepEqual(rowState(looking(1)), { kind: 'looking', note: null });
assert.deepEqual(rowState(book(1, { attentionReason: 'LC did not answer. Trying again shortly.' })),
{ kind: 'looking', note: 'LC did not answer. Trying again shortly.' });
});
test('ready and attention states', () => {
assert.deepEqual(rowState(ready(1)), { kind: 'ready' });
assert.deepEqual(rowState(attention(1)), { kind: 'attention', reason: 'No match' });
assert.equal(rowState(book(1, { status: 'resolved' })).kind, 'attention');
});
test('session summary', () => {
assert.equal(sessionSummary([ready(1), ready(2), ready(3), looking(4)]), '4 scanned · 3 ready · 1 looking up');
assert.equal(sessionSummary([ready(1)]), '1 scanned · 1 ready');
assert.equal(sessionSummary([attention(1), attention(2), looking(3)]), '3 scanned · 1 looking up · 2 need attention');
assert.equal(sessionSummary([]), '0 scanned');
});
test('queue split ignores books that are not queued or need attention', () => {
const printed = { ...ready(9), inQueue: false };
const q = queueSplit([ready(1), looking(2), attention(3), printed, ready(4)]);
assert.deepEqual(q.ready.map(b => b.id), [1, 4]);
assert.deepEqual(q.looking.map(b => b.id), [2]);
});
test('queue labels', () => {
assert.equal(queueHeader(3, 1), '3 cards ready · 1 still looking up');
assert.equal(queueHeader(1, 0), '1 card ready');
assert.equal(queueHeader(0, 1), '0 cards ready · 1 still looking up');
assert.equal(pdfLabel(3), 'Make PDF (3 cards)');
assert.equal(pdfLabel(1), 'Make PDF (1 card)');
assert.equal(pdfLabel(0), 'Make PDF');
assert.equal(queueTabLabel(3, 1), 'Print queue (4)');
assert.equal(queueTabLabel(0, 0), 'Print queue');
});
test('elapsed text', () => {
assert.equal(elapsedText(0), '0 s');
assert.equal(elapsedText(59_900), '59 s');
assert.equal(elapsedText(65_000), '1 min 05 s');
assert.equal(elapsedText(-5), '0 s');
});
+62
View File
@@ -0,0 +1,62 @@
import type { Book } from '../shared/types.ts';
/** The single state a book is shown in. */
export type RowState =
| { kind: 'looking'; note: string | null }
| { kind: 'ready' }
| { kind: 'attention'; reason: string };
export function rowState(book: Book): RowState {
if (book.status === 'pending') return { kind: 'looking', note: book.attentionReason };
if (book.status === 'resolved' && book.callNumber) return { kind: 'ready' };
if (book.status === 'resolved') return { kind: 'attention', reason: 'No call number was found.' };
return { kind: 'attention', reason: book.attentionReason ?? 'This book needs a look.' };
}
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
export function sessionSummary(books: Book[]): string {
let ready = 0, looking = 0, attention = 0;
for (const b of books) {
const s = rowState(b).kind;
if (s === 'ready') ready++; else if (s === 'looking') looking++; else attention++;
}
const parts = [`${books.length} scanned`];
if (ready) parts.push(`${ready} ready`);
if (looking) parts.push(`${looking} looking up`);
if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} attention`);
return parts.join(' · ');
}
export interface QueueSplit { ready: Book[]; looking: Book[] }
/** Queued books, split into the ones that can be printed now and the ones still being looked up. */
export function queueSplit(books: Book[]): QueueSplit {
const ready: Book[] = [], looking: Book[] = [];
for (const b of books) {
if (!b.inQueue) continue;
const s = rowState(b).kind;
if (s === 'ready') ready.push(b); else if (s === 'looking') looking.push(b);
}
return { ready, looking };
}
export function queueHeader(ready: number, looking: number): string {
const head = plural(ready, 'card', 'cards') + ' ready';
return looking ? `${head} · ${looking} still looking up` : head;
}
export function pdfLabel(ready: number): string {
return ready ? `Make PDF (${plural(ready, 'card', 'cards')})` : 'Make PDF';
}
export function queueTabLabel(ready: number, looking: number): string {
const n = ready + looking;
return n ? `Print queue (${n})` : 'Print queue';
}
/** "12 s", "1 min 05 s" */
export function elapsedText(ms: number): string {
const s = Math.max(0, Math.floor(ms / 1000));
return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`;
}
+13 -4
View File
@@ -2,6 +2,7 @@ import { useState } from 'preact/hooks';
import type { Book } from '../../shared/types.ts';
import { api } from '../api.ts';
import { upsertBook, dispatch } from '../live.ts';
import { parseYear } from '../year.ts';
export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) {
const [title, setTitle] = useState(book.title);
@@ -10,6 +11,7 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
const [year, setYear] = useState(book.year?.toString() ?? '');
const [callNumber, setCallNumber] = useState(book.callNumber ?? '');
const [msg, setMsg] = useState('');
const [yearError, setYearError] = useState('');
const [busy, setBusy] = useState(false);
async function run(fn: () => Promise<void>) {
@@ -18,17 +20,23 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
setBusy(false);
}
const save = (ev: Event) => { ev.preventDefault(); void run(async () => {
const save = (ev: Event) => {
ev.preventDefault();
const y = parseYear(year);
if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; }
setYearError('');
void run(async () => {
const patch: Record<string, unknown> = {
title: title.trim(),
authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
publisher: publisher.trim() || null,
year: year.trim() ? Number(year) : null,
year: y.value,
};
if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim();
upsertBook(await api.patchBook(book.id, patch));
onClose();
}); };
});
};
return (
<form class="card editor" onSubmit={save}>
@@ -36,8 +44,9 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
<div class="row">
<label class="grow">Publisher<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} /></label>
<label class="year">Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
<label class="year">Year<input inputMode="numeric" value={year} aria-invalid={yearError ? 'true' : undefined} onInput={e => { setYear(e.currentTarget.value); setYearError(''); }} /></label>
</div>
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
<label>Call number
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
<small>Changing this locks the number</small>
+23
View File
@@ -0,0 +1,23 @@
import type { Book } from '../../shared/types.ts';
import { elapsedText, rowState } from '../bookstate.ts';
import { lookupStartedAt, useNow } from '../live.ts';
const CheckIcon = () => (
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3.2L13 4.8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
);
const AlertIcon = () => (
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2.2L14.6 13.5H1.4L8 2.2z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" /><path d="M8 6.6v3.2M8 11.6v.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
);
function Looking({ book }: { book: Book }) {
const now = useNow(true);
return <span class="state-label"><span class="spinner" aria-hidden="true" />Looking up… <span class="elapsed">{elapsedText(now - lookupStartedAt(book))}</span></span>;
}
/** The one label a book shows: Looking up… (spinner, seconds), Ready, or Needs attention. */
export function StateLabel({ book }: { book: Book }) {
const s = rowState(book);
if (s.kind === 'looking') return <Looking book={book} />;
if (s.kind === 'ready') return <span class="state-label"><CheckIcon />Ready</span>;
return <span class="state-label"><AlertIcon />Needs attention</span>;
}
+1 -1
View File
@@ -7,7 +7,7 @@ export function CallNo({ value, approximate }: { value: string | null; approxima
return (
<span class="callno">
<span class="callno-line">{lines[0]}{approximate ? <span class="approx" title="Approximate number"> ~</span> : null}</span>
<span class="callno-line">{lines[1] || ' '}</span>
<span class="callno-line">{lines[1] || ' '}</span>
</span>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cropRect, upscaleFor } from './frame.ts';
test('the crop is the target box inside the frame', () => {
const r = cropRect(1920, 1080);
assert.deepEqual(r, { x: 192, y: 292, w: 1536, h: 497 });
assert.ok(r.x + r.w <= 1920 && r.y + r.h <= 1080);
});
test('small crops are enlarged 2x, large ones are not', () => {
assert.equal(upscaleFor(512), 2);
assert.equal(upscaleFor(999), 2);
assert.equal(upscaleFor(1000), 1);
assert.equal(upscaleFor(1536), 1);
});
+15
View File
@@ -0,0 +1,15 @@
/** Where the barcode is expected, as fractions of the video frame. The overlay box is drawn from the same numbers. */
export const TARGET = { x: 0.1, y: 0.27, w: 0.8, h: 0.46 };
export interface Rect { x: number; y: number; w: number; h: number }
/** The target box in pixels of a frame of the given size. */
export function cropRect(width: number, height: number): Rect {
const x = Math.round(width * TARGET.x), y = Math.round(height * TARGET.y);
return { x, y, w: Math.min(width - x, Math.round(width * TARGET.w)), h: Math.min(height - y, Math.round(height * TARGET.h)) };
}
/** A small crop is enlarged so that thin bars cover enough pixels for the decoder: 2x below 1000 px wide. */
export function upscaleFor(cropWidth: number): number {
return cropWidth < 1000 ? 2 : 1;
}
+28
View File
@@ -7,7 +7,35 @@ import type { BookAction, BookState } from './store.ts';
let state: BookState = emptyState;
const listeners = new Set<() => void>();
/** When each book was first seen waiting for its lookup, for the elapsed-seconds display. */
const pendingSince = new Map<number, number>();
function trackPending(action: BookAction): void {
const note = (b: Book, fromServerTime: boolean) => {
if (b.status !== 'pending') { pendingSince.delete(b.id); return; }
if (pendingSince.has(b.id)) return;
const created = Date.parse(b.createdAt);
pendingSince.set(b.id, fromServerTime && Number.isFinite(created) ? Math.min(created, Date.now()) : Date.now());
};
if (action.type === 'upsert') note(action.book, false);
else if (action.type === 'replace') { pendingSince.clear(); action.books.forEach(b => note(b, true)); }
else pendingSince.delete(action.id);
}
export function lookupStartedAt(book: Book): number { return pendingSince.get(book.id) ?? Date.now(); }
/** Re-renders once a second while `active`, and returns the current time. */
export function useNow(active: boolean): number {
const [now, setNow] = useState(Date.now());
useEffect(() => {
if (!active) return;
setNow(Date.now());
const t = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(t);
}, [active]);
return now;
}
export function dispatch(action: BookAction): void {
trackPending(action);
state = reduce(state, action);
listeners.forEach(l => l());
}
+3 -2
View File
@@ -1,6 +1,7 @@
import { render } from 'preact';
import { useState } from 'preact/hooks';
import { startLive, useBooks } from './live.ts';
import { queueSplit, queueTabLabel } from './bookstate.ts';
import { Scan } from './views/Scan.tsx';
import { Queue } from './views/Queue.tsx';
import { Catalog } from './views/Catalog.tsx';
@@ -10,8 +11,8 @@ type Tab = 'scan' | 'queue' | 'catalog';
function App() {
const [tab, setTab] = useState<Tab>('scan');
const books = useBooks();
const ready = books.filter(b => b.inQueue && b.status === 'resolved' && b.callNumber).length;
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', ready ? `Print queue (${ready})` : 'Print queue'], ['catalog', 'Catalog']];
const { ready, looking } = queueSplit(books);
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', queueTabLabel(ready.length, looking.length)], ['catalog', 'Catalog']];
return (
<>
<header>
+30 -34
View File
@@ -1,52 +1,48 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { acceptRead, endRound, newReadState } from './readstate.ts';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
const ISBN = '9780306406157';
test('single read emits nothing, second consecutive read emits', () => {
let r = acceptRead(newReadState(), ISBN, 0);
assert.equal(r.emit, null);
r = acceptRead(endRound(r.state, [ISBN]), ISBN, 150);
test('a valid ISBN-13 is accepted on the first read', () => {
const r = acceptRead(newReadState(), ISBN, 0);
assert.equal(r.emit, ISBN);
assert.equal(r.reject, false);
});
test('a gap between reads resets the streak', () => {
test('the same ISBN is not repeated within 5 s, then is again', () => {
let r = acceptRead(newReadState(), ISBN, 0);
const s = endRound(r.state, []);
r = acceptRead(s, ISBN, 150);
r = acceptRead(r.state, ISBN, 150);
assert.equal(r.emit, null);
assert.equal(r.reject, false);
r = acceptRead(r.state, ISBN, 4900);
assert.equal(r.emit, null);
r = acceptRead(r.state, ISBN, 5100);
assert.equal(r.emit, ISBN);
});
test('third read does not emit again; emits again after 5 s', () => {
let s = newReadState();
let t = 0;
const read = () => { const r = acceptRead(s, ISBN, t); s = endRound(r.state, [ISBN]); t += 150; return r; };
read();
assert.equal(read().emit, ISBN);
assert.equal(read().emit, null);
t = 5200;
assert.equal(read().emit, ISBN);
test('a 979 ISBN is accepted', () => {
assert.equal(acceptRead(newReadState(), '9791034305261', 0).emit, '9791034305261');
});
test('a UPC rejects once per 5 s', () => {
test('a UPC-A rejects once per 5 s', () => {
const upc = '036000291452';
let s = newReadState();
let t = 0;
const read = () => { const r = acceptRead(s, upc, t); s = endRound(r.state, [upc]); t += 150; return r; };
assert.equal(read().reject, false);
const second = read();
assert.equal(second.reject, true);
assert.equal(second.emit, null);
assert.equal(read().reject, false);
t = 6000;
assert.equal(read().reject, true);
});
test('bad check digit rejects', () => {
let s = newReadState();
let r = acceptRead(s, '9780306406158', 0); s = endRound(r.state, ['9780306406158']);
r = acceptRead(s, '9780306406158', 150);
let r = acceptRead(newReadState(), upc, 0);
assert.equal(r.reject, true);
assert.equal(r.emit, null);
r = acceptRead(r.state, upc, 150);
assert.equal(r.reject, false);
r = acceptRead(r.state, upc, 6000);
assert.equal(r.reject, true);
});
test('a 13-digit code without a 978/979 prefix, or with a bad check digit, rejects', () => {
assert.equal(acceptRead(newReadState(), '5012345678900', 0).reject, true);
assert.equal(acceptRead(newReadState(), '9780306406158', 0).reject, true);
});
test('markEmitted silences the loop for 5 s', () => {
const s = markEmitted(newReadState(), ISBN, 1000);
assert.equal(acceptRead(s, ISBN, 2000).emit, null);
assert.equal(acceptRead(s, ISBN, 6100).emit, ISBN);
});
+15 -17
View File
@@ -2,38 +2,36 @@ import { normalizeIsbn } from '../shared/isbn.ts';
export const REPEAT_MS = 5000;
/** Remembers when each code was last reported, so a barcode held in view is announced once per 5 seconds. */
export interface ReadState {
streak: Record<string, number>;
emittedAt: Record<string, number>;
rejectedAt: Record<string, number>;
}
export function newReadState(): ReadState {
return { streak: {}, emittedAt: {}, rejectedAt: {} };
return { emittedAt: {}, rejectedAt: {} };
}
/** Call once per detected code in a detection round. */
/**
* Judge one decoded barcode. A valid ISBN-13 (check digit, 978 or 979 prefix) is accepted at once, with no
* second confirming read: the EAN checksum already makes a false read very unlikely. Anything else
* (a UPC, a price code, a bad check digit) is rejected. Neither is repeated within REPEAT_MS.
*/
export function acceptRead(
state: ReadState, code: string, now: number,
): { state: ReadState; emit: string | null; reject: boolean } {
const streak = { ...state.streak, [code]: (state.streak[code] ?? 0) + 1 };
const next: ReadState = { ...state, streak };
if (streak[code] < 2) return { state: next, emit: null, reject: false };
const isbn = normalizeIsbn(code);
const isbn = /^\d{13}$/.test(code) ? normalizeIsbn(code) : null;
if (isbn === null) {
const last = state.rejectedAt[code];
if (last !== undefined && now - last < REPEAT_MS) return { state: next, emit: null, reject: false };
return { state: { ...next, rejectedAt: { ...state.rejectedAt, [code]: now } }, emit: null, reject: true };
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false };
return { state: { ...state, rejectedAt: { ...state.rejectedAt, [code]: now } }, emit: null, reject: true };
}
const last = state.emittedAt[isbn];
if (last !== undefined && now - last < REPEAT_MS) return { state: next, emit: null, reject: false };
return { state: { ...next, emittedAt: { ...state.emittedAt, [isbn]: now } }, emit: isbn, reject: false };
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false };
return { state: { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } }, emit: isbn, reject: false };
}
/** Call at the end of every detection round with the codes seen in it; codes not seen lose their streak. */
export function endRound(state: ReadState, seen: string[]): ReadState {
const streak: Record<string, number> = {};
for (const c of seen) if (state.streak[c] !== undefined) streak[c] = state.streak[c];
return { ...state, streak };
/** Record that an ISBN was just reported by some other path (the Capture button), so the loop stays quiet. */
export function markEmitted(state: ReadState, isbn: string, now: number): ReadState {
return { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } };
}
+156 -29
View File
@@ -1,5 +1,8 @@
import { BarcodeDetector, prepareZXingModule } from 'barcode-detector/ponyfill';
import { acceptRead, endRound, newReadState } from './readstate.ts';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import type { ReaderOptions } from 'zxing-wasm/reader';
import { normalizeIsbn } from '../shared/isbn.ts';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { cropRect, upscaleFor } from './frame.ts';
export { acceptRead } from './readstate.ts';
export type { ReadState } from './readstate.ts';
@@ -8,10 +11,10 @@ export type { ReadState } from './readstate.ts';
export const WASM_PATH = '/zxing_reader.wasm';
let prepared = false;
function prepare(): void {
export function prepare(): void {
if (prepared) return;
prepared = true;
prepareZXingModule({
void prepareZXingModule({
overrides: {
locateFile: (path: string, prefix: string) =>
path.endsWith('.wasm') ? WASM_PATH : prefix + path,
@@ -20,34 +23,139 @@ function prepare(): void {
});
}
/** The one detector configuration the scanner uses; also used by scripts/browser-check.ts. */
export function makeDetector(): BarcodeDetector {
prepare();
return new BarcodeDetector({ formats: ['ean_13'] });
/**
* Book barcodes are EAN-13 (978/979); UPC-A is read too so that a US price/UPC code can be reported as
* "not an ISBN" instead of silently ignored. Everything else (QR, Code 128, ...) is not searched for.
* Settings are for a fixed-focus laptop webcam: try hard, try rotated (a book held sideways), and try
* downscaled copies (a soft image of thin bars decodes better smaller).
*/
const BASE: ReaderOptions = {
formats: ['EAN13', 'UPCA'],
tryHarder: true, tryRotate: true, tryDownscale: true, tryInvert: false,
maxNumberOfSymbols: 2,
};
/** Extra passes for the Capture button: other thresholding, and light-on-dark codes. */
const THOROUGH: ReaderOptions[] = [
{ ...BASE, binarizer: 'LocalAverage', tryInvert: true },
{ ...BASE, binarizer: 'GlobalHistogram', tryInvert: true },
{ ...BASE, binarizer: 'FixedThreshold', tryInvert: true, tryDownscale: false },
{ ...BASE, binarizer: 'LocalAverage', downscaleThreshold: 200, downscaleFactor: 2 },
];
export interface DecodeOutcome { isbn: string | null; other: string | null }
/** Decoding runs one at a time: a new request waits for the one in progress. */
let queue: Promise<unknown> = Promise.resolve();
function exclusive<T>(fn: () => Promise<T>): Promise<T> {
const run = queue.then(fn, fn);
queue = run.catch(() => undefined);
return run;
}
const INTERVAL_MS = 150;
type Source = HTMLVideoElement | ImageBitmap;
const sizeOf = (s: Source) => s instanceof HTMLVideoElement ? { w: s.videoWidth, h: s.videoHeight } : { w: s.width, h: s.height };
let scratch: HTMLCanvasElement | null = null;
/** Draw a region of the source into a canvas of the given size and return its pixels. */
function pixels(src: Source, sx: number, sy: number, sw: number, sh: number, dw: number, dh: number): ImageData {
scratch ??= document.createElement('canvas');
scratch.width = dw; scratch.height = dh;
const g = scratch.getContext('2d', { willReadFrequently: true })!;
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high';
g.drawImage(src, sx, sy, sw, sh, 0, 0, dw, dh);
return g.getImageData(0, 0, dw, dh);
}
function judge(codes: { text: string }[], into: DecodeOutcome): void {
for (const c of codes) {
const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null;
if (isbn) into.isbn ??= isbn; else into.other ??= c.text;
}
}
/** The images to try, most promising first: the target box (enlarged when small), then the whole frame. */
function views(src: Source, maxSide: number): ImageData[] {
const { w, h } = sizeOf(src);
const c = cropRect(w, h);
const k = upscaleFor(c.w);
const full = Math.min(1, maxSide / Math.max(w, h));
return [
pixels(src, c.x, c.y, c.w, c.h, Math.round(c.w * k), Math.round(c.h * k)),
pixels(src, 0, 0, w, h, Math.round(w * full), Math.round(h * full)),
];
}
/** One quick pass for the live loop: the target box, then the full frame if the box held no ISBN. */
export function decodeLive(src: Source): Promise<DecodeOutcome> {
return exclusive(async () => {
const out: DecodeOutcome = { isbn: null, other: null };
for (const img of views(src, 2560)) {
judge(await readBarcodes(img, BASE), out);
if (out.isbn) break;
}
return out;
});
}
/** The most thorough decode: every view with every setting, stopping at the first valid ISBN. */
export function decodeThorough(src: Source): Promise<DecodeOutcome> {
return exclusive(async () => {
const out: DecodeOutcome = { isbn: null, other: null };
const imgs = views(src, 3000);
for (const opts of [BASE, ...THOROUGH]) {
for (const img of imgs) {
judge(await readBarcodes(img, opts), out);
if (out.isbn) return out;
}
}
return out;
});
}
export interface ScannerHandlers {
/** A valid ISBN-13 was read (at most once per 5 seconds per book). */
onIsbn(isbn13: string): void;
/** A barcode was read that is not a book ISBN. */
onOther(code: string): void;
/** The camera stopped by itself (unplugged, taken by another program). */
onEnded(): void;
}
export interface Scanner {
stop(): void;
/** Take one still at the highest resolution available and decode it as thoroughly as possible. */
capture(): Promise<DecodeOutcome>;
}
const INTERVAL_MS = 120;
/**
* Open the camera and start the sequential decode loop. If `signal` aborts while the permission prompt is
* open, the stream is stopped the moment it arrives and null is returned.
*/
export async function startScanner(
video: HTMLVideoElement,
deviceId: string | undefined,
onIsbn: (isbn13: string) => void,
onReject: (code: string) => void,
): Promise<() => void> {
video: HTMLVideoElement, deviceId: string | undefined, handlers: ScannerHandlers, signal?: AbortSignal,
): Promise<Scanner | null> {
prepare();
const stream = await navigator.mediaDevices.getUserMedia({
video: {
...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'environment' }),
width: { ideal: 1920 }, height: { ideal: 1080 },
...(deviceId ? { deviceId: { exact: deviceId } } : {}),
width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 30 },
// Not in every TypeScript lib; ignored by cameras without focus control.
...({ advanced: [{ focusMode: 'continuous' }] } as object),
},
audio: false,
});
const release = () => stream.getTracks().forEach(t => t.stop());
if (signal?.aborted) { release(); return null; }
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const stop = () => {
if (stopped) return;
stopped = true;
if (timer !== undefined) clearTimeout(timer);
stream.getTracks().forEach(t => t.stop());
release();
if (video.srcObject === stream) video.srcObject = null;
};
@@ -59,33 +167,52 @@ export async function startScanner(
stop();
throw e;
}
if (signal?.aborted) { stop(); return null; }
stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (!stopped) { stop(); handlers.onEnded(); } });
const detector = makeDetector();
let state = newReadState();
// Sequential loop: the next round is scheduled only after the previous detection finished,
// so two detections never overlap.
// Sequential: the next round is scheduled only after the previous detection finished.
const tick = async () => {
if (stopped) return;
const began = performance.now();
if (video.readyState >= 2 && video.videoWidth > 0) {
try {
const found = await detector.detect(video);
const found = await decodeLive(video);
if (stopped) return;
const codes = found.filter(f => f.format === 'ean_13').map(f => f.rawValue);
const now = Date.now();
for (const code of codes) {
const r = acceptRead(state, code, now);
for (const code of [found.isbn, found.other]) {
if (!code) continue;
const r = acceptRead(state, code, Date.now());
state = r.state;
if (r.emit) onIsbn(r.emit);
else if (r.reject) onReject(code);
if (r.emit) handlers.onIsbn(r.emit);
else if (r.reject) handlers.onOther(code);
}
state = endRound(state, codes);
} catch { /* a failed frame is skipped */ }
}
if (stopped) return;
timer = setTimeout(tick, Math.max(0, INTERVAL_MS - (performance.now() - began)));
};
timer = setTimeout(tick, INTERVAL_MS);
return stop;
async function capture(): Promise<DecodeOutcome> {
let result: DecodeOutcome = { isbn: null, other: null };
// Highest resolution first: the camera's still-photo mode where it exists.
const IC = (window as unknown as { ImageCapture?: new (t: MediaStreamTrack) => { takePhoto(): Promise<Blob> } }).ImageCapture;
const track = stream.getVideoTracks()[0];
if (IC && track) {
let photo: ImageBitmap | null = null;
try { photo = await createImageBitmap(await new IC(track).takePhoto()); } catch { /* use the current frame */ }
if (photo) {
try { result = await decodeThorough(photo); } finally { photo.close(); }
}
}
if (!result.isbn && video.videoWidth > 0) {
const frame = await decodeThorough(video);
result = { isbn: frame.isbn, other: result.other ?? frame.other };
}
if (result.isbn) state = markEmitted(state, result.isbn, Date.now());
return result;
}
return { stop, capture };
}
+29
View File
@@ -0,0 +1,29 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { emptySession, forget, touch } from './session.ts';
test('a book listed twice stays one row and moves to the top', () => {
let s = touch(emptySession, 1, false);
s = touch(s, 2, false);
s = touch(s, 1, true);
assert.deepEqual(s.order, [1, 2]);
assert.equal(s.touched[1], 2);
assert.equal(s.touched[2], 1);
});
test('"earlier" is decided when the book is first listed, not by later scans', () => {
let s = touch(emptySession, 1, false);
s = touch(s, 1, true);
assert.equal(s.earlier[1], undefined);
s = touch(s, 2, true);
s = touch(s, 2, false);
assert.equal(s.earlier[2], true);
});
test('forget removes a book everywhere', () => {
let s = touch(touch(emptySession, 1, true), 2, false);
s = forget(s, 1);
assert.deepEqual(s.order, [2]);
assert.equal(s.earlier[1], undefined);
assert.equal(s.touched[1], undefined);
});
+26
View File
@@ -0,0 +1,26 @@
/** The books touched in this browsing session, one row per book id, newest activity first. */
export interface SessionState {
order: number[];
/** Books that were already in the catalog when first added to this session. */
earlier: Record<number, true>;
/** How many times each book was added or scanned; above 1 means "seen again", so its row flashes. */
touched: Record<number, number>;
}
export const emptySession: SessionState = { order: [], earlier: {}, touched: {} };
/** Add a book, or move it to the top if it is listed already. Never creates a second row. */
export function touch(s: SessionState, bookId: number, alreadyInCatalog: boolean): SessionState {
const known = s.order.includes(bookId);
return {
order: [bookId, ...s.order.filter(i => i !== bookId)],
earlier: !known && alreadyInCatalog ? { ...s.earlier, [bookId]: true } : s.earlier,
touched: { ...s.touched, [bookId]: (s.touched[bookId] ?? 0) + 1 },
};
}
export function forget(s: SessionState, bookId: number): SessionState {
const { [bookId]: _a, ...earlier } = s.earlier;
const { [bookId]: _b, ...touched } = s.touched;
return { ...s, order: s.order.filter(i => i !== bookId), earlier, touched };
}
+44 -4
View File
@@ -40,11 +40,25 @@ label small { display: block; margin-top: 4px; }
.scan { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px; }
.scan .forms { grid-column: 1 / -1; }
@media (max-width: 760px) { .scan { grid-template-columns: 1fr; } main { padding: 14px 12px; } }
.video-wrap { position: relative; aspect-ratio: 16 / 9; background: #000; border-radius: 12px; overflow: hidden; border: 3px solid transparent; }
.video-wrap.flash { border-color: var(--flash); }
.video-wrap { position: relative; width: 100%; background: #0b0c0e; border-radius: 12px; overflow: hidden; border: 3px solid var(--line); transition: border-color .15s; }
.video-wrap.flash { border-color: var(--flash); transition: none; }
video { width: 100%; height: 100%; object-fit: cover; display: block; }
video.mirror { transform: scaleX(-1); }
.video-empty { position: absolute; inset: 0; display: grid; place-items: center; color: #aaa; }
.video-empty { position: absolute; inset: 0; display: grid; place-items: center; }
button.big { font-size: 1.1rem; padding: 12px 26px; }
.target { position: absolute; border: 2px solid rgba(255,255,255,.92); border-radius: 10px; box-shadow: 0 0 0 100vmax rgba(0,0,0,.38); pointer-events: none; transition: border-color .15s; }
.video-wrap.flash .target { border-color: var(--flash); box-shadow: 0 0 0 100vmax rgba(0,0,0,.38), 0 0 0 3px var(--flash); }
.hint { position: absolute; left: 50%; bottom: 5%; transform: translateX(-50%); max-width: 92%; padding: 4px 12px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .9rem; white-space: nowrap; pointer-events: none; }
.scanning { position: absolute; top: 10px; right: 10px; display: flex; align-items: center; gap: 7px; padding: 3px 11px 3px 9px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .82rem; pointer-events: none; }
.pulse { width: 9px; height: 9px; border-radius: 50%; background: #52c586; animation: pulse 1.2s ease-in-out infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.7); } }
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes rowflash { from { opacity: .35; } to { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .pulse { animation: none; } .spinner { animation-duration: 3s; } .flashbar { animation-duration: .01s; } }
.status { margin: 10px 0; padding: 8px 12px; border-radius: 8px; border-left: 4px solid var(--line); background: var(--panel); font-weight: 500; min-height: 2.6em; }
.status.ok { border-left-color: var(--ok); color: var(--ok); }
.status.warn { border-left-color: var(--warn); color: var(--warn); }
.small { font-size: .85rem; }
.summary { font-weight: 600; margin: 0 0 6px; }
.isbn-form input { font-size: 1.1rem; }
.list { list-style: none; margin: 0; padding: 0; }
@@ -76,3 +90,29 @@ legend { color: var(--muted); font-size: .9rem; padding: 0; margin-bottom: 6px;
.slot.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
.slot.used { opacity: .45; }
.confirm { border-color: var(--accent); }
/* Books: one row each, one state each. */
.book { position: relative; display: grid; gap: 8px; padding: 12px 12px 12px 14px; border-bottom: 1px solid var(--line); border-left: 4px solid var(--line); overflow: hidden; }
.book.looking { border-left-color: var(--accent); }
.book.ready { border-left-color: var(--ok); }
.book.attention { border-left-color: var(--warn); background: color-mix(in srgb, var(--warn) 8%, transparent); }
.book-head { display: flex; gap: 12px; justify-content: space-between; align-items: flex-start; }
.book-head .item-main { flex: 1; }
.earlier { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
.book-state { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
.state-label { display: inline-flex; align-items: center; gap: 7px; font-weight: 600; white-space: nowrap; }
.book.looking .state-label, .item[data-state=looking] .state-label { color: var(--accent); }
.book.ready .state-label, .item .state-label { color: var(--ok); }
.book.attention .state-label { color: var(--warn); }
.item[data-state=looking] .state-label { color: var(--accent); }
.elapsed { font-weight: 400; font-variant-numeric: tabular-nums; color: var(--muted); }
.icon { width: 16px; height: 16px; flex: none; }
.spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid color-mix(in srgb, var(--accent) 30%, transparent); border-top-color: var(--accent); animation: spin .8s linear infinite; flex: none; }
.reason { color: var(--text); overflow-wrap: anywhere; }
.note { overflow-wrap: anywhere; }
.flashbar { position: absolute; inset: 0; background: var(--flash); opacity: 0; animation: rowflash 1.4s ease-out; pointer-events: none; }
.item { align-items: center; }
.item > .state-label { margin-left: auto; }
.item.dim .title { color: var(--muted); }
.callno-slot { min-width: 9.5em; }
.queue-head { font-weight: 600; }
+2 -1
View File
@@ -26,11 +26,12 @@ export function Catalog() {
{shown.map(b => (
<li class="item column" key={b.id}>
<button class="item-btn" onClick={() => setOpenId(openId === b.id ? null : b.id)} aria-expanded={openId === b.id}>
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
{b.status === 'pending' ? <span class="callno muted">Looking up…</span> : <CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />}
<span class="item-main">
<strong class="title">{b.title}</strong>
<span class="muted">{[b.authors.join(', '), b.year].filter(Boolean).join(' · ')}</span>
{b.status === 'needs_attention' ? <span class="chip warn">Needs attention</span> : null}
{b.status === 'pending' ? <span class="chip pending">Looking up…</span> : null}
</span>
</button>
{openId === b.id ? <BookEditor book={b} onClose={() => setOpenId(null)} /> : null}
+30 -7
View File
@@ -2,12 +2,14 @@ import { useEffect, useRef, useState } from 'preact/hooks';
import { api } from '../api.ts';
import { dispatch, upsertBook, useBooks } from '../live.ts';
import { sheetCount } from '../sheets.ts';
import { pdfLabel, queueHeader, queueSplit } from '../bookstate.ts';
import { StateLabel } from '../components/BookState.tsx';
import { CallNo } from '../components/CallNo.tsx';
import { BookEditor } from '../components/BookEditor.tsx';
export function Queue() {
const books = useBooks();
const queued = books.filter(b => b.inQueue && b.status === 'resolved' && b.callNumber);
const { ready: queued, looking } = queueSplit(books);
const attention = books.filter(b => b.status === 'needs_attention');
const [start, setStart] = useState(1);
const [msg, setMsg] = useState('');
@@ -15,6 +17,8 @@ export function Queue() {
const [pending, setPending] = useState<{ ids: number[]; url: string } | null>(null);
const [editId, setEditId] = useState<number | null>(null);
const sheets = sheetCount(queued.length, start);
const pdfUrl = useRef<string | null>(null);
useEffect(() => () => { if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); }, []);
async function makePdf() {
setMsg(''); setBusy(true);
@@ -22,7 +26,9 @@ export function Queue() {
const tab = window.open('', '_blank');
try {
const { blob, ids } = await api.fetchPdf(start);
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); // the previous PDF is no longer needed
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
pdfUrl.current = url;
if (tab) tab.location.href = url;
setPending({ ids, url });
} catch (e) {
@@ -35,7 +41,7 @@ export function Queue() {
if (!pending) return;
try {
await api.confirmPrint(pending.ids);
URL.revokeObjectURL(pending.url);
URL.revokeObjectURL(pending.url); pdfUrl.current = null;
setPending(null);
setMsg('');
// Live events will update the books; refresh the local copies too.
@@ -47,13 +53,25 @@ export function Queue() {
<div class="queue">
<section>
<h2>Print queue</h2>
<p>{queued.length} {queued.length === 1 ? 'card' : 'cards'} ready, {sheets} {sheets === 1 ? 'sheet' : 'sheets'}</p>
{queued.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
<p class="summary" aria-live="polite">{queueHeader(queued.length, looking.length)}</p>
{queued.length ? <p class="muted small">{sheets} {sheets === 1 ? 'sheet' : 'sheets'} of 3 cards</p> : null}
{queued.length === 0 && looking.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
<ul class="list">
{queued.map(b => (
<li class="item" key={b.id}>
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
<span class="item-main"><strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span></span>
<StateLabel book={b} />
</li>
))}
{looking.map(b => (
<li class="item dim" key={b.id} data-state="looking">
<span class="callno-slot" aria-hidden="true" />
<span class="item-main">
<strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span>
{b.attentionReason ? <span class="muted small note">{b.attentionReason}</span> : null}
</span>
<StateLabel book={b} />
</li>
))}
</ul>
@@ -68,7 +86,12 @@ export function Queue() {
</div>
</fieldset>
<p class="muted">Print at actual size (100%), single-sided, from the manual feed slot.</p>
<button class="primary" disabled={busy || queued.length === 0} onClick={makePdf}>{busy ? 'Making PDF' : 'Make PDF'}</button>
<button class="primary" disabled={busy || queued.length === 0} aria-describedby={queued.length === 0 ? 'pdf-why' : undefined} onClick={makePdf}>{busy ? 'Making PDF' : pdfLabel(queued.length)}</button>
{queued.length === 0 ? (
<p class="muted small" id="pdf-why">{looking.length
? 'No card is ready yet. Books still being looked up are added to the PDF once they have a call number.'
: 'There are no cards to print. Scan a book first.'}</p>
) : looking.length ? <p class="muted small">The PDF holds the ready cards only. The {looking.length === 1 ? 'book' : 'books'} still looking up will be in the next one.</p> : null}
{msg ? <p class="error" role="alert">{msg}</p> : null}
{pending ? (
<div class="card confirm" role="alert">
@@ -76,7 +99,7 @@ export function Queue() {
<p class="muted"><a href={pending.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
<div class="row wrap">
<button class="primary" onClick={confirmPrinted}>Yes, clear these from the queue</button>
<button onClick={() => { URL.revokeObjectURL(pending.url); setPending(null); }}>Not yet</button>
<button onClick={() => { URL.revokeObjectURL(pending.url); pdfUrl.current = null; setPending(null); }}>Not yet</button>
</div>
</div>
) : null}
@@ -84,7 +107,7 @@ export function Queue() {
<section>
<h2>Needs attention</h2>
{attention.length === 0 ? <p class="muted">Every book has a call number.</p> : null}
{attention.length === 0 ? <p class="muted">No book needs attention.</p> : null}
<ul class="list">
{attention.map(b => (
<li class="item column" key={b.id}>
+212 -68
View File
@@ -4,13 +4,27 @@ import { normalizeIsbn } from '../../shared/isbn.ts';
import { api } from '../api.ts';
import { getBook, upsertBook, useBooks } from '../live.ts';
import { startScanner } from '../scanner.ts';
import type { Scanner } from '../scanner.ts';
import { TARGET } from '../frame.ts';
import { beepAccept, beepLow, unlockAudio } from '../sound.ts';
import { emptySession, touch } from '../session.ts';
import type { SessionState } from '../session.ts';
import { rowState, sessionSummary } from '../bookstate.ts';
import { parseYear } from '../year.ts';
import { CallNo } from '../components/CallNo.tsx';
import { BookEditor } from '../components/BookEditor.tsx';
import { StateLabel } from '../components/BookState.tsx';
interface Entry { key: number; bookId?: number; duplicate?: boolean; note?: string; error?: boolean }
// Kept at module level so the list survives switching tabs.
let entries: Entry[] = [];
let nextKey = 1;
let session: SessionState = emptySession;
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
const inflight = new Map<string, Promise<void>>();
const CAMERA_FLAG = 'cameraOn';
const readFlag = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
const writeFlag = (k: string, v: string | null) => {
try { if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* ignore */ }
};
function cameraMessage(e: unknown): string {
const name = (e as { name?: string })?.name;
@@ -20,58 +34,142 @@ function cameraMessage(e: unknown): string {
return 'The camera could not be started. You can still type the ISBN below.';
}
type Cam = 'off' | 'starting' | 'on';
type Tone = 'info' | 'ok' | 'warn';
interface Status { text: string; tone: Tone; hold: boolean }
const NOT_FOUND = 'No barcode found in that picture. Move closer, add light, or type the ISBN below.';
export function Scan() {
useBooks(); // re-render on live updates
const [, bump] = useState(0);
const refresh = () => bump(n => n + 1);
const video = useRef<HTMLVideoElement>(null);
const isbnBox = useRef<HTMLInputElement>(null);
const stopRef = useRef<(() => void) | null>(null);
const [running, setRunning] = useState(false);
const scanner = useRef<Scanner | null>(null);
const opening = useRef<AbortController | null>(null);
const statusTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const [cam, setCam] = useState<Cam>('off');
const [camError, setCamError] = useState('');
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
const [deviceId, setDeviceId] = useState(() => { try { return localStorage.getItem('camera') ?? ''; } catch { return ''; } });
const [deviceId, setDeviceId] = useState(() => readFlag('camera') ?? '');
const [aspect, setAspect] = useState('16 / 9');
const [flash, setFlash] = useState(false);
const [status, setStatus] = useState<Status | null>(null);
const [capturing, setCapturing] = useState(false);
const [typed, setTyped] = useState('');
const [typedError, setTypedError] = useState('');
const [sendError, setSendError] = useState('');
const [editId, setEditId] = useState<number | null>(null);
const addEntry = (e: Omit<Entry, 'key'>) => { entries = [{ key: nextKey++, ...e }, ...entries]; refresh(); };
/** Show a message under the video. Unless `hold`, it falls back to "Looking for a barcode…" after a few seconds. */
const say = (text: string, tone: Tone, hold = false) => {
clearTimeout(statusTimer.current);
setStatus({ text, tone, hold });
if (!hold) statusTimer.current = setTimeout(() => setStatus(null), 4000);
};
async function submitIsbn(isbn: string) {
try {
const r = await api.scan(isbn);
upsertBook(r.book);
if (r.duplicate) beepLow();
addEntry({ bookId: r.book.id, duplicate: r.duplicate });
} catch (e) {
beepLow();
addEntry({ note: `${isbn}: ${(e as Error).message}`, error: true });
setSendError('');
let p = inflight.get(isbn);
if (!p) {
p = (async () => {
try {
const r = await api.scan(isbn);
upsertBook(r.book);
session = touch(session, r.book.id, r.duplicate);
} catch (e) {
beepLow();
setSendError(`${isbn}: ${(e as Error).message}`);
}
})();
inflight.set(isbn, p);
void p.finally(() => inflight.delete(isbn));
}
await p;
refresh();
}
const onIsbn = (isbn: string) => { beepAccept(); setFlash(true); setTimeout(() => setFlash(false), 250); void submitIsbn(isbn); };
const onReject = (code: string) => { beepLow(); addEntry({ note: `${code} is not a book barcode`, error: true }); };
const addBook = (b: Book) => { session = touch(session, b.id, false); refresh(); };
function stopCamera() {
stopRef.current?.(); stopRef.current = null; setRunning(false);
const gotIsbn = (isbn: string) => {
beepAccept();
setFlash(true); setTimeout(() => setFlash(false), 600);
say(`Read ${isbn}`, 'ok');
void submitIsbn(isbn);
};
const handlers = useRef({ onIsbn: gotIsbn, onOther: (_c: string) => {}, onEnded: () => {} });
handlers.current = {
onIsbn: gotIsbn,
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
onEnded: () => { scanner.current = null; setCam('off'); say('The camera stopped. Press Start camera to turn it on again.', 'warn', true); },
};
/** `user` is true when the person pressed Stop: only then is the camera forgotten for the next visit. */
function stopCamera(user: boolean) {
opening.current?.abort(); opening.current = null;
scanner.current?.stop(); scanner.current = null;
setCam('off'); setStatus(null); setCapturing(false); setAspect('16 / 9');
if (user) writeFlag(CAMERA_FLAG, null);
}
async function startCamera() {
unlockAudio(); // needs the user gesture
setCamError('');
stopCamera();
if (opening.current || scanner.current || !video.current) return; // a second click does nothing
unlockAudio(); // needs the user gesture (a no-op for an automatic start)
const ac = new AbortController();
opening.current = ac;
setCam('starting'); setCamError('');
try {
if (!video.current) return;
stopRef.current = await startScanner(video.current, deviceId || undefined, onIsbn, onReject);
setRunning(true);
const all = await navigator.mediaDevices.enumerateDevices();
setDevices(all.filter(d => d.kind === 'videoinput'));
const sc = await startScanner(video.current, deviceId || undefined, {
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(c), onEnded: () => handlers.current.onEnded(),
}, ac.signal);
if (!sc) return; // stopped or left the view while the permission prompt was open
if (ac.signal.aborted) { sc.stop(); return; }
scanner.current = sc;
setCam('on');
writeFlag(CAMERA_FLAG, '1');
const v = video.current;
if (v?.videoWidth) setAspect(`${v.videoWidth} / ${v.videoHeight}`);
setDevices((await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput'));
} catch (e) {
if (ac.signal.aborted) return;
setCam('off');
setCamError(cameraMessage(e));
if ((e as { name?: string })?.name === 'NotAllowedError') writeFlag(CAMERA_FLAG, null);
} finally {
if (opening.current === ac) opening.current = null;
}
isbnBox.current?.focus();
}
useEffect(() => stopCamera, []); // stop on leaving the view
// Keep the ISBN box focused unless the user is typing in another field.
async function capture() {
const sc = scanner.current;
if (!sc || capturing) return;
setCapturing(true);
say('Taking a picture and reading it…', 'info', true);
try {
const r = await sc.capture();
if (scanner.current !== sc) return;
if (r.isbn) gotIsbn(r.isbn);
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
else { beepLow(); say(NOT_FOUND, 'warn', true); }
} catch {
say(NOT_FOUND, 'warn', true);
}
setCapturing(false);
}
const captureRef = useRef(capture);
captureRef.current = capture;
// Stop the camera when leaving the view, and start it again when it was on last time and the browser
// already allows it (no prompt).
useEffect(() => {
if (readFlag(CAMERA_FLAG) === '1') {
navigator.permissions?.query({ name: 'camera' as PermissionName })
.then(p => { if (p.state === 'granted') void startCamera(); }, () => {});
}
return () => { stopCamera(false); clearTimeout(statusTimer.current); };
}, []);
// Keep the ISBN box focused unless the user is typing in another field; Space takes a picture.
useEffect(() => {
const focusBox = () => {
const a = document.activeElement;
@@ -80,13 +178,23 @@ export function Scan() {
focusBox();
const onOut = () => setTimeout(focusBox, 0);
const onKey = (e: KeyboardEvent) => {
unlockAudio();
if (e.ctrlKey || e.metaKey || e.altKey) return;
const a = document.activeElement;
const a = document.activeElement as HTMLElement | null;
if (e.code === 'Space') {
const inOtherField = a && a !== isbnBox.current && (a.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'SUMMARY'].includes(a.tagName));
if (!inOtherField && scanner.current) { e.preventDefault(); if (!e.repeat) void captureRef.current(); }
return;
}
if ((!a || a === document.body) && /^[0-9xX-]$/.test(e.key)) isbnBox.current?.focus();
};
document.addEventListener('focusout', onOut);
document.addEventListener('keydown', onKey);
return () => { document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey); };
document.addEventListener('pointerdown', unlockAudio);
return () => {
document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey);
document.removeEventListener('pointerdown', unlockAudio);
};
}, []);
const onSubmit = (ev: Event) => {
@@ -100,24 +208,46 @@ export function Scan() {
void submitIsbn(isbn);
};
const rows = session.order.map(id => getBook(id)).filter((b): b is Book => !!b);
const shown: Status = status ?? (cam === 'on'
? { text: 'Looking for a barcode…', tone: 'info', hold: true }
: cam === 'starting'
? { text: 'Starting the camera. Allow access if the browser asks.', tone: 'info', hold: true }
: { text: 'The camera is off. Start it to scan, or type the ISBN below.', tone: 'info', hold: true });
return (
<div class="scan">
<section class="left">
<div class={'video-wrap' + (flash ? ' flash' : '')}>
<video ref={video} playsInline muted class="mirror" />
{!running ? <div class="video-empty">Camera is off</div> : null}
<div class={'video-wrap' + (flash ? ' flash' : '')} style={{ aspectRatio: aspect }}>
<video ref={video} playsInline muted onLoadedMetadata={e => {
const v = e.currentTarget; if (v.videoWidth) setAspect(`${v.videoWidth} / ${v.videoHeight}`);
}} />
{cam === 'on' ? (
<>
<div class="target" aria-hidden="true" style={{ left: `${TARGET.x * 100}%`, top: `${TARGET.y * 100}%`, width: `${TARGET.w * 100}%`, height: `${TARGET.h * 100}%` }} />
<div class="hint" aria-hidden="true">Hold the barcode inside the box</div>
<div class="scanning" aria-hidden="true"><span class="pulse" />Scanning</div>
</>
) : (
<div class="video-empty">
<button class="primary big" disabled={cam === 'starting'} onClick={startCamera}>{cam === 'starting' ? 'Starting camera…' : 'Start camera'}</button>
</div>
)}
</div>
<p class={'status ' + shown.tone} role="status" aria-live="polite" data-tone={shown.tone}>{shown.text}</p>
<div class="row wrap">
<button class="primary" onClick={running ? stopCamera : startCamera}>{running ? 'Stop camera' : 'Start camera'}</button>
<button class="primary" disabled={cam !== 'on' || capturing} onClick={() => void capture()}
title="Take one picture now and read it as carefully as possible (Space)">{capturing ? 'Reading…' : 'Capture'}</button>
{cam === 'on' ? <button onClick={() => stopCamera(true)}>Stop camera</button> : null}
{devices.length > 1 ? (
<select aria-label="Camera" value={deviceId} onChange={e => {
const v = e.currentTarget.value; setDeviceId(v);
try { localStorage.setItem('camera', v); } catch { /* ignore */ }
const v = e.currentTarget.value; setDeviceId(v); writeFlag('camera', v);
}}>
<option value="">Default camera</option>
{devices.map((d, i) => <option value={d.deviceId}>{d.label || `Camera ${i + 1}`}</option>)}
</select>
) : null}
<span class="muted small">{cam === 'on' ? 'Scans by itself. Capture or Space takes one careful picture.' : ''}</span>
</div>
{camError ? <p class="warn" role="alert">{camError}</p> : null}
<form class="isbn-form" onSubmit={onSubmit}>
@@ -126,54 +256,66 @@ export function Scan() {
value={typed} onInput={e => { setTyped(e.currentTarget.value); setTypedError(''); }} />
</label>
{typedError ? <p class="error" role="alert">{typedError}</p> : null}
{sendError ? <p class="error" role="alert">{sendError}</p> : null}
</form>
</section>
<section class="right">
<h2>This session</h2>
{entries.length === 0 ? <p class="muted">Scanned books appear here.</p> : null}
{rows.length === 0 ? <p class="muted">Scanned books appear here, one row per book.</p> : <p class="summary" aria-live="polite">{sessionSummary(rows)}</p>}
<ul class="list">
{entries.map(e => <EntryRow key={e.key} entry={e} />)}
{rows.map(b => (
<BookRow key={b.id} book={b} earlier={!!session.earlier[b.id]} touched={session.touched[b.id] ?? 0}
editing={editId === b.id} onEdit={() => setEditId(editId === b.id ? null : b.id)} />
))}
</ul>
</section>
<section class="forms">
<SearchForm onAdded={b => addEntry({ bookId: b.id })} />
<LccnForm onAdded={b => addEntry({ bookId: b.id })} />
<ManualForm onAdded={b => addEntry({ bookId: b.id })} />
<SearchForm onAdded={addBook} />
<LccnForm onAdded={addBook} />
<ManualForm onAdded={addBook} />
</section>
</div>
);
}
function EntryRow({ entry }: { entry: Entry }) {
function BookRow({ book, earlier, touched, editing, onEdit }: { book: Book; earlier: boolean; touched: number; editing: boolean; onEdit: () => void }) {
const [queuing, setQueuing] = useState(false);
if (entry.bookId === undefined) return <li class="item error-item"><span class="error">{entry.note}</span></li>;
const book = getBook(entry.bookId);
if (!book) return <li class="item"><span class="muted">Removed</span></li>;
let chip;
if (entry.duplicate) chip = <span class="chip dup">Already in catalog</span>;
else if (book.status === 'pending') chip = <span class="chip pending">Looking up</span>;
else if (book.status === 'resolved') chip = <span class="chip ok">Ready</span>;
else chip = <span class="chip warn">Needs attention</span>;
const s = rowState(book);
return (
<li class="item">
<div class="item-main">
<strong class="title">{book.title}</strong>
{book.authors.length ? <span class="muted"> {book.authors.join(', ')}</span> : null}
<CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} />
<li class={'book ' + s.kind} data-state={s.kind} data-book-id={book.id}>
{touched > 1 ? <span class="flashbar" key={touched} aria-hidden="true" /> : null}
<div class="book-head">
<div class="item-main">
<strong class="title">{book.title}</strong>
{book.authors.length ? <span class="muted">{book.authors.join(', ')}</span> : null}
</div>
{earlier ? (
<div class="earlier">
<span class="muted small">Already in catalog</span>
{!book.inQueue ? (
<button disabled={queuing} onClick={async () => {
setQueuing(true);
try { upsertBook(await api.queueBook(book.id)); } catch { /* the row stays as it was */ }
setQueuing(false);
}}>Queue reprint</button>
) : null}
</div>
) : null}
</div>
<div class="item-side">
{chip}
{!entry.duplicate && book.status === 'needs_attention' && book.attentionReason ? <small class="muted">{book.attentionReason}</small> : null}
{entry.duplicate ? (book.inQueue
? <small class="muted">In the print queue</small>
: <button disabled={queuing} onClick={async () => {
setQueuing(true);
try { upsertBook(await api.queueBook(book.id)); } catch { /* shown via chip staying */ }
setQueuing(false);
}}>Queue reprint</button>) : null}
<div class="book-state">
<StateLabel book={book} />
{s.kind === 'ready' ? <CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} /> : null}
{s.kind === 'looking' && s.note ? <span class="muted small note">{s.note}</span> : null}
{s.kind === 'attention' ? (
<>
<span class="reason">{s.reason}</span>
<button class="fix" onClick={onEdit} aria-expanded={editing}>Fix</button>
</>
) : null}
</div>
{editing ? <BookEditor book={book} onClose={onEdit} /> : null}
</li>
);
}
@@ -236,10 +378,12 @@ function ManualForm({ onAdded }: { onAdded: (b: Book) => void }) {
<summary>Enter by hand</summary>
<form class="stack" onSubmit={async ev => {
ev.preventDefault(); setMsg('');
const y = parseYear(year);
if (!y.ok) { setMsg('Enter the year as digits, for example 2018, or leave it empty.'); return; }
try {
const b = await api.addManual({
title: title.trim(), authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
...(year.trim() ? { year: Number(year) } : {}), ...(cn.trim() ? { callNumber: cn.trim() } : {}),
...(y.value !== null ? { year: y.value } : {}), ...(cn.trim() ? { callNumber: cn.trim() } : {}),
});
upsertBook(b); onAdded(b); setTitle(''); setAuthors(''); setYear(''); setCn('');
} catch (e) { setMsg((e as Error).message); }
+12
View File
@@ -0,0 +1,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseYear } from './year.ts';
test('empty year is null', () => {
assert.deepEqual(parseYear(''), { ok: true, value: null });
assert.deepEqual(parseYear(' '), { ok: true, value: null });
});
test('numeric year is a number', () => assert.deepEqual(parseYear(' 2018 '), { ok: true, value: 2018 }));
test('non-numeric year is an error, not NaN', () => {
for (const t of ['abc', '20x8', '2018.5', '-5', '12345']) assert.deepEqual(parseYear(t), { ok: false }, t);
});
+7
View File
@@ -0,0 +1,7 @@
/** Empty means "no year" (null); anything that is not a whole number is an error, never NaN. */
export function parseYear(text: string): { ok: true; value: number | null } | { ok: false } {
const t = text.trim();
if (t === '') return { ok: true, value: null };
if (!/^\d{1,4}$/.test(t)) return { ok: false };
return { ok: true, value: Number(t) };
}