Add resolver, server, PDF rendering and web app

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 09:46:46 -07:00
1 parent 6a7fcdc4b8
commit bdfdf581f3
59 files changed
+4088

No files matched your search

+178
View File
@@ -0,0 +1,178 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { openDb } from './db.ts';
import { createJobs } from './jobs.ts';
import { createApp, createEventBus } from './app.ts';
import type { CardData, Resolution, Settings } from '../shared/types.ts';
const found: Resolution = {
meta: { title: 'Rust', authors: ['Klabnik, Steve'], subjects: [] },
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
};
function setup(resolve = async () => found) {
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 pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
const app = createApp({
db, jobs, resolver, events,
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' } }) });
return { db, jobs, app, req, pdfCalls, events };
}
test('scan: valid, invalid, duplicate', async () => {
const { req, jobs, db } = setup();
const bad = await req('POST', '/api/scan', { isbn: '123' });
assert.equal(bad.status, 400);
assert.deepEqual(await bad.json(), { error: 'Not a valid ISBN' });
const ok = await req('POST', '/api/scan', { isbn: '978-1-59327-828-1' });
const j = await ok.json() as any;
assert.equal(j.duplicate, false);
assert.equal(j.book.isbn13, '9781593278281');
assert.equal(j.book.inQueue, true);
assert.equal(j.book.title, '9781593278281');
await jobs.idle();
assert.equal(db.getBook(j.book.id)!.status, 'resolved');
const dup = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
assert.equal(dup.duplicate, true);
assert.equal(dup.book.id, j.book.id);
assert.equal(dup.book.status, 'resolved');
});
test('two simultaneous scans of one ISBN yield one row', async () => {
const { req, db } = setup();
const rs = await Promise.all([1, 2, 3].map(() => req('POST', '/api/scan', { isbn: '9781593278281' })));
const js = await Promise.all(rs.map((r) => r.json() as Promise<any>));
assert.equal(db.listBooks().length, 1);
assert.equal(js.filter((j) => !j.duplicate).length, 1);
});
test('PATCH call number that parses, and one that does not', async () => {
const { req, db } = setup();
const { book } = db.insertPending({ isbn13: '9781593278281', title: 't' });
const a = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'QA76.73.R87 K53 2018' })).json() as any;
assert.equal(a.book.callNumber, 'QA76.73.R87 K53 2018');
assert.equal(a.book.status, 'resolved');
assert.equal(a.book.manualOverride, true);
assert.equal(a.book.confidence, 'manual');
const b = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'shelf by the window' })).json() as any;
assert.equal(b.book.callNumber, 'shelf by the window');
assert.equal(b.book.status, 'needs_attention');
assert.equal(b.book.attentionReason, 'Call number not recognised');
assert.equal(b.book.manualOverride, true);
assert.equal((await req('PATCH', '/api/books/999', { title: 'x' })).status, 404);
});
test('list order follows sort key with unparseable last; filters', async () => {
const { req } = setup();
const mk = async (title: string, callNumber: string) =>
req('POST', '/api/books/manual', { title, authors: ['A'], callNumber });
await mk('Window', 'shelf by the window');
await mk('Second', 'QA76.73.R87 K53 2018');
await mk('First', 'PS3558.E63 D8 2005');
const all = await (await req('GET', '/api/books')).json() as any[];
assert.deepEqual(all.map((b) => b.title), ['First', 'Second', 'Window']);
assert.equal(((await (await req('GET', '/api/books?filter=attention')).json()) as any[]).length, 1);
assert.equal(((await (await req('GET', '/api/books?q=second')).json()) as any[]).length, 1);
});
test('manual without call number enqueues a lookup; retry refused for override', async () => {
const { req, jobs, db } = setup();
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', authors: ['Bar'] })).json() as any;
assert.equal(m.book.status, 'pending');
await jobs.idle();
assert.equal(db.getBook(m.book.id)!.status, 'resolved');
const r = await req('POST', `/api/books/${m.book.id}/retry`);
assert.equal(r.status, 200);
await jobs.idle();
await req('PATCH', `/api/books/${m.book.id}`, { callNumber: 'QA76' });
assert.equal((await req('POST', `/api/books/${m.book.id}/retry`)).status, 400);
});
test('lccn, from-search, search, delete, queue', async () => {
const { req, jobs, db } = setup();
const l = await (await req('POST', '/api/books/lccn', { lccn: '88005934' })).json() as any;
assert.equal(l.book.lccn, '88005934');
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], year: 1999, lccn: '1', lcc: [] } })).json() as any;
assert.equal(f.book.year, 1999);
assert.equal(((await (await req('GET', '/api/search?title=a&author=b')).json()) as any[])[0].title, 'Hit');
await jobs.idle();
db.updateBook(l.book.id, { inQueue: false });
assert.equal(((await (await req('POST', `/api/books/${l.book.id}/queue`)).json()) as any).book.inQueue, true);
assert.equal((await req('DELETE', `/api/books/${l.book.id}`)).status, 200);
assert.equal(db.getBook(l.book.id), null);
});
test('print with empty queue -> 400', async () => {
const { req } = setup();
const r = await req('GET', '/api/print.pdf');
assert.equal(r.status, 400);
assert.deepEqual(await r.json(), { error: 'Nothing to print' });
});
test('print passes cards in shelf order and honours start; confirm clears queue', async () => {
const { req, pdfCalls, db } = setup();
await req('POST', '/api/books/manual', { title: 'Second', callNumber: 'QA76.73.R87 K53 2018' });
await req('POST', '/api/books/manual', { title: 'First', callNumber: 'PS3558.E63 D8 2005' });
await req('POST', '/api/books/manual', { title: 'Odd', callNumber: 'shelf by the window' });
const approx = db.insertPending({ title: 'Approx', callNumber: 'B1 .A1 2000', sortKey: 'B 1', status: 'resolved', confidence: 'approximate', inQueue: true }).book;
const r = await req('GET', '/api/print.pdf?start=2');
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-type'), 'application/pdf');
assert.equal(await r.text(), '%PDF-stub');
const call = pdfCalls[0]!;
assert.deepEqual(call.cards.map((c) => c.title), ['Approx', 'First', 'Second']);
assert.equal(call.opts.startPosition, 2);
assert.equal(call.cards[1]!.className, 'Class P');
assert.equal(call.cards[1]!.subclassName, 'Sub PS');
assert.equal(call.cards[0]!.approximate, true);
assert.equal(call.cards[1]!.approximate, false);
const ids = r.headers.get('x-book-ids')!.split(',').map(Number);
assert.equal(ids.length, 3);
assert.equal(ids[0], approx.id);
await req('POST', '/api/print/confirm', { ids });
assert.equal((await req('GET', '/api/print.pdf')).status, 400);
assert.ok(db.getBook(ids[0]!)!.printedAt);
assert.equal(((await (await req('GET', '/api/books?filter=queue')).json()) as any[]).length, 1);
});
test('settings clamp and calibration pdf', async () => {
const { req } = setup();
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 0, offsetYmm: 0 });
const s = await (await req('PUT', '/api/settings', { offsetXmm: 50, offsetYmm: -50 })).json();
assert.deepEqual(s, { offsetXmm: 10, offsetYmm: -10 });
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 10, offsetYmm: -10 });
assert.equal((await req('PUT', '/api/settings', { offsetXmm: 'a', offsetYmm: 1 })).status, 400);
assert.equal(await (await req('GET', '/api/calibration.pdf')).text(), '%PDF-cal');
});
test('events stream delivers changes and cleans up on disconnect', async () => {
const { app, req, events, db } = setup();
const ac = new AbortController();
const res = await app.request('/api/events', { signal: ac.signal });
assert.equal(res.headers.get('content-type'), 'text/event-stream');
assert.equal(events.listenerCount(), 1);
const reader = res.body!.getReader();
const dec = new TextDecoder();
await reader.read(); // initial comment
const { book } = db.insertPending({ title: 'x' });
await req('PATCH', `/api/books/${book.id}`, { title: 'y' });
const chunk = dec.decode((await reader.read()).value);
assert.match(chunk, /^event: book\ndata: .*"title":"y"/);
await req('DELETE', `/api/books/${book.id}`);
assert.match(dec.decode((await reader.read()).value), /^event: deleted\ndata: \{"id":\d+\}/);
ac.abort();
assert.equal(events.listenerCount(), 0);
const res2 = await app.request('/api/events');
assert.equal(events.listenerCount(), 1);
await res2.body!.cancel();
assert.equal(events.listenerCount(), 0);
});