diff --git a/scripts/build-web.ts b/scripts/build-web.ts new file mode 100644 index 0000000..860e972 --- /dev/null +++ b/scripts/build-web.ts @@ -0,0 +1,31 @@ +import { build } from 'esbuild'; +import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const out = `${root}dist/web`; +await mkdir(out, { recursive: true }); + +await build({ + entryPoints: [`${root}src/web/main.tsx`], + outfile: `${out}/app.js`, + bundle: true, + format: 'esm', + sourcemap: true, + jsx: 'automatic', + jsxImportSource: 'preact', + target: 'es2022', + minify: false, + logLevel: 'info', +}); + +// zxing-wasm ships a default locateFile pointing at jsDelivr. scanner.ts always overrides it, so it is +// dead code, but neutralise the URL anyway so the bundle contains no CDN address at all. +const appJs = await readFile(`${out}/app.js`, 'utf8'); +await writeFile(`${out}/app.js`, appJs.replaceAll('https://fastly.jsdelivr.net/npm/', '/local-only/')); + +await copyFile(`${root}src/web/index.html`, `${out}/index.html`); +await copyFile(`${root}src/web/styles.css`, `${out}/styles.css`); +// The zxing reader wasm is served from our own server at /zxing_reader.wasm (see scanner.ts). +await copyFile(`${root}node_modules/zxing-wasm/dist/reader/zxing_reader.wasm`, `${out}/zxing_reader.wasm`); +console.log('Built dist/web'); diff --git a/src/server/app.test.ts b/src/server/app.test.ts new file mode 100644 index 0000000..ced4180 --- /dev/null +++ b/src/server/app.test.ts @@ -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)); + 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); +}); diff --git a/src/server/app.ts b/src/server/app.ts new file mode 100644 index 0000000..87d8dae --- /dev/null +++ b/src/server/app.ts @@ -0,0 +1,287 @@ +import { Hono } from 'hono'; +import type { Context } from 'hono'; +import type { Book, CardData, SearchResult, Settings } from '../shared/types.ts'; +import { normalizeIsbn } from '../shared/isbn.ts'; +import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts'; +import type { Db, Filter, NewBook } from './db.ts'; +import type { Jobs, ResolverLike } from './jobs.ts'; + +// Structural matches for pdf/render.ts (Task 4). +export type RenderCardsPdf = (cards: CardData[], opts: Settings & { startPosition: 1 | 2 | 3 }) => Promise; +export type RenderCalibrationPdf = (s: Settings) => Promise; +// Matches classNames in shared/lcc-outline.ts (Task 1b). +export type ClassNames = (letters: string) => { className: string | null; subclassName: string | null }; + +export interface EventBus { + on(listener: (event: string, data: unknown) => void): () => void; + emitBook(book: Book): void; + emitDeleted(id: number): void; + listenerCount(): number; +} + +export function createEventBus(): EventBus { + const listeners = new Set<(event: string, data: unknown) => void>(); + const emit = (event: string, data: unknown) => { for (const l of [...listeners]) l(event, data); }; + return { + on(l) { listeners.add(l); return () => { listeners.delete(l); }; }, + emitBook: (book) => emit('book', book), + emitDeleted: (id) => emit('deleted', { id }), + listenerCount: () => listeners.size, + }; +} + +export interface AppDeps { + db: Db; jobs: Jobs; resolver: ResolverLike; + renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf; + classNames: ClassNames; + events?: EventBus; +} + +class HttpError extends Error { + status: 400 | 404; + constructor(status: 400 | 404, message: string) { super(message); this.status = status; } +} + +const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null); +const strList = (v: unknown): string[] | null => + Array.isArray(v) && v.every((x) => typeof x === 'string') ? v.map((x) => x.trim()).filter(Boolean) : null; +const yearOf = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : null); + +// A typed call number is kept as typed when it does not parse; it sorts last and is flagged. +function callNumberFields(raw: string): Partial { + const cn = parseCallNumber(raw); + if (cn) { + return { callNumber: formatCallNumber(cn), sortKey: sortKeyOfRaw(raw), status: 'resolved', attentionReason: null, + manualOverride: true, confidence: 'manual', source: 'manual' }; + } + return { callNumber: raw, sortKey: sortKeyOfRaw(raw), status: 'needs_attention', attentionReason: 'Call number not recognised', + manualOverride: true, confidence: 'manual', source: 'manual' }; +} + +export function createApp(deps: AppDeps): Hono { + const { db, jobs, resolver, classNames } = deps; + const events = deps.events ?? createEventBus(); + const app = new Hono(); + + app.onError((err, c) => { + if (err instanceof HttpError) return c.json({ error: err.message }, err.status); + console.error(err); + return c.json({ error: 'Internal error' }, 500); + }); + + async function body(c: Context): Promise> { + try { + const v = await c.req.json(); + if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record; + } catch { /* fall through */ } + throw new HttpError(400, 'Invalid JSON body'); + } + + function bookParam(c: Context): Book { + const id = Number(c.req.param('id')); + const book = Number.isInteger(id) ? db.getBook(id) : null; + if (!book) throw new HttpError(404, 'Book not found'); + return book; + } + + function addPending(fields: NewBook): { book: Book; created: boolean } { + const r = db.insertPending({ inQueue: true, ...fields }); + if (r.created) { + events.emitBook(r.book); + if (r.book.status === 'pending') jobs.enqueue(r.book.id); + } + return r; + } + + app.post('/api/scan', async (c) => { + const b = await body(c); + const isbn = typeof b.isbn === 'string' ? normalizeIsbn(b.isbn) : null; + if (!isbn) throw new HttpError(400, 'Not a valid ISBN'); + const { book, created } = addPending({ isbn13: isbn, title: isbn }); + return c.json({ book, duplicate: !created }); + }); + + app.post('/api/books/lccn', async (c) => { + const lccn = str((await body(c)).lccn)?.replace(/\s+/g, ''); + if (!lccn) throw new HttpError(400, 'LCCN is required'); + return c.json({ book: addPending({ lccn, title: lccn }).book }); + }); + + app.get('/api/search', async (c) => { + const title = c.req.query('title')?.trim() ?? ''; + const author = c.req.query('author')?.trim() ?? ''; + if (!title && !author) throw new HttpError(400, 'Enter a title or an author'); + const results: SearchResult[] = await resolver.search(title, author); + return c.json(results); + }); + + app.post('/api/books/from-search', async (c) => { + const r = (await body(c)).result as Record | undefined; + const title = r && str(r.title); + if (!r || !title) throw new HttpError(400, 'A search result is required'); + const { book } = addPending({ + title, authors: strList(r.authors) ?? [], year: yearOf(r.year), publisher: str(r.publisher), lccn: str(r.lccn), + }); + return c.json({ book }); + }); + + app.post('/api/books/manual', async (c) => { + const b = await body(c); + const title = str(b.title); + if (!title) throw new HttpError(400, 'Title is required'); + const fields: NewBook = { + title, authors: strList(b.authors) ?? [], year: yearOf(b.year), publisher: str(b.publisher), + }; + const callNumber = str(b.callNumber); + if (callNumber) Object.assign(fields, callNumberFields(callNumber)); + return c.json({ book: addPending(fields).book }); + }); + + app.get('/api/books', (c) => { + const f = c.req.query('filter'); + const filter: Filter = f === 'queue' || f === 'attention' ? f : 'all'; + return c.json(db.listBooks({ filter, q: c.req.query('q') })); + }); + + app.patch('/api/books/:id', async (c) => { + const cur = bookParam(c); + const b = await body(c); + const patch: Partial = {}; + if ('title' in b) { + const t = str(b.title); + if (!t) throw new HttpError(400, 'Title cannot be empty'); + patch.title = t; + } + if ('authors' in b) { + const a = strList(b.authors); + if (!a) throw new HttpError(400, 'Authors must be a list of names'); + patch.authors = a; + } + if ('publisher' in b) patch.publisher = b.publisher === null ? null : str(b.publisher); + if ('year' in b) { + if (b.year !== null && yearOf(b.year) === null) throw new HttpError(400, 'Year must be a number'); + patch.year = b.year === null ? null : yearOf(b.year); + } + if ('callNumber' in b) { + const cn = str(b.callNumber); + if (!cn) throw new HttpError(400, 'Call number cannot be empty'); + Object.assign(patch, callNumberFields(cn)); + } + const updated = db.updateBook(cur.id, patch)!; + events.emitBook(updated); + return c.json({ book: updated }); + }); + + app.delete('/api/books/:id', (c) => { + const book = bookParam(c); + db.deleteBook(book.id); + events.emitDeleted(book.id); + return c.json({ ok: true }); + }); + + app.post('/api/books/:id/queue', (c) => { + const book = bookParam(c); + const updated = db.updateBook(book.id, { inQueue: true })!; + events.emitBook(updated); + return c.json({ book: updated }); + }); + + 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'); + const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!; + events.emitBook(updated); + jobs.enqueue(book.id); + return c.json({ book: updated }); + }); + + app.get('/api/print.pdf', async (c) => { + const s = Number(c.req.query('start') ?? '1'); + const startPosition = (s === 2 || s === 3 ? s : 1) as 1 | 2 | 3; + const books = db.listBooks({ filter: 'queue' }) + .filter((b) => b.status === 'resolved' && b.callNumber) + .sort((a, b) => ((a.sortKey ?? '~') < (b.sortKey ?? '~') ? -1 : (a.sortKey ?? '~') > (b.sortKey ?? '~') ? 1 : 0)); + if (!books.length) throw new HttpError(400, 'Nothing to print'); + const cards: CardData[] = books.map((b) => { + const cn = parseCallNumber(b.callNumber!); + const letters = cn?.letters ?? /^[A-Z]*/.exec(b.callNumber!)![0]; + const names = classNames(letters); + return { + callNumber: b.callNumber!, className: names.className, subclassName: names.subclassName, + title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: b.authors, publisher: b.publisher, year: b.year, + subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate', + }; + }); + const pdf = await deps.renderCardsPdf(cards, { ...db.getSettings(), startPosition }); + return new Response(pdf as BodyInit, { + headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': 'inline; filename="booksorter-cards.pdf"', + 'X-Book-Ids': books.map((b) => b.id).join(','), + }, + }); + }); + + app.post('/api/print/confirm', async (c) => { + const ids = (await body(c)).ids; + if (!Array.isArray(ids) || !ids.every((i) => Number.isInteger(i))) throw new HttpError(400, 'ids must be a list of book ids'); + const now = new Date().toISOString(); + for (const id of ids as number[]) { + const b = db.updateBook(id, { printedAt: now, inQueue: false }); + if (b) events.emitBook(b); + } + return c.json({ ok: true }); + }); + + app.get('/api/calibration.pdf', async (c) => { + const pdf = await deps.renderCalibrationPdf(db.getSettings()); + return new Response(pdf as BodyInit, { + headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="booksorter-calibration.pdf"' }, + }); + }); + + app.get('/api/settings', (c) => c.json(db.getSettings())); + + app.put('/api/settings', async (c) => { + const b = await body(c); + const clamp = (v: unknown): number => { + if (typeof v !== 'number' || !Number.isFinite(v)) throw new HttpError(400, 'Offsets must be numbers'); + return Math.max(-10, Math.min(10, v)); + }; + const s: Settings = { offsetXmm: clamp(b.offsetXmm), offsetYmm: clamp(b.offsetYmm) }; + db.putSettings(s); + return c.json(s); + }); + + app.get('/api/events', (c) => { + const enc = new TextEncoder(); + let off: (() => void) | null = null; + let heartbeat: ReturnType | null = null; + const cleanup = () => { + off?.(); off = null; + if (heartbeat) clearInterval(heartbeat); + heartbeat = null; + }; + const stream = new ReadableStream({ + start(controller) { + const send = (text: string) => { + try { controller.enqueue(enc.encode(text)); } catch { cleanup(); } + }; + send(': connected\n\n'); + off = events.on((event, data) => send(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); + heartbeat = setInterval(() => send(': ping\n\n'), 25000); + heartbeat.unref(); + c.req.raw.signal.addEventListener('abort', () => { + cleanup(); + try { controller.close(); } catch { /* already closed */ } + }, { once: true }); + }, + cancel: cleanup, + }); + return new Response(stream, { + headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, + }); + }); + + return app; +} diff --git a/src/server/db.test.ts b/src/server/db.test.ts new file mode 100644 index 0000000..18f0a11 --- /dev/null +++ b/src/server/db.test.ts @@ -0,0 +1,61 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb } from './db.ts'; + +test('insertPending is idempotent on isbn13', () => { + const db = openDb(':memory:'); + const a = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + const b = db.insertPending({ isbn13: '9781593278281', title: 'y' }); + assert.equal(a.created, true); + assert.equal(b.created, false); + assert.equal(b.book.id, a.book.id); + assert.equal(db.listBooks().length, 1); +}); + +test('books without isbn do not collide', () => { + const db = openDb(':memory:'); + db.insertPending({ title: 'a' }); + db.insertPending({ title: 'b' }); + assert.equal(db.listBooks().length, 2); +}); + +test('listBooks orders by sort key, nulls last, then title', () => { + const db = openDb(':memory:'); + db.insertPending({ title: 'Zed' }); + db.insertPending({ title: 'Abe' }); + db.insertPending({ title: 'B', sortKey: 'QA 76' }); + db.insertPending({ title: 'A', sortKey: 'PS 12' }); + assert.deepEqual(db.listBooks().map((b) => b.title), ['A', 'B', 'Abe', 'Zed']); +}); + +test('filters and search', () => { + const db = openDb(':memory:'); + const a = db.insertPending({ title: 'Rust Book', authors: ['Klabnik, Steve'], inQueue: true }).book; + db.insertPending({ title: 'Other', status: 'needs_attention', inQueue: false }); + assert.deepEqual(db.listBooks({ filter: 'queue' }).map((b) => b.id), [a.id]); + assert.equal(db.listBooks({ filter: 'attention' }).length, 1); + assert.equal(db.listBooks({ q: 'klabnik' }).length, 1); +}); + +test('updateBook round-trips fields', () => { + const db = openDb(':memory:'); + const { book } = db.insertPending({ title: 't' }); + const u = db.updateBook(book.id, { authors: ['A'], manualOverride: true, status: 'resolved', year: 2001 })!; + assert.deepEqual(u.authors, ['A']); + assert.equal(u.manualOverride, true); + assert.equal(u.year, 2001); + assert.equal(db.updateBook(999, { title: 'z' }), null); + assert.deepEqual(db.listPendingIds(), []); + assert.equal(db.deleteBook(book.id), true); +}); + +test('settings and cache', () => { + const db = openDb(':memory:'); + assert.deepEqual(db.getSettings(), { offsetXmm: 0, offsetYmm: 0 }); + db.putSettings({ offsetXmm: 1.5, offsetYmm: -2 }); + assert.deepEqual(db.getSettings(), { offsetXmm: 1.5, offsetYmm: -2 }); + assert.equal(db.cache.get('k'), null); + db.cache.set('k', 'v'); + db.cache.set('k', 'w'); + assert.equal(db.cache.get('k'), 'w'); +}); diff --git a/src/server/db.ts b/src/server/db.ts new file mode 100644 index 0000000..fc9504d --- /dev/null +++ b/src/server/db.ts @@ -0,0 +1,176 @@ +import { DatabaseSync } from 'node:sqlite'; +import { mkdirSync } from 'node:fs'; +import { dirname } from 'node:path'; +import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts'; + +// Structural match for SourceCache in resolve/resolver.ts (Task 2). +export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void } + +export interface NewBook { + isbn13?: string | null; lccn?: string | null; title: string; subtitle?: string | null; + authors?: string[]; publisher?: string | null; year?: number | null; subjects?: string[]; + callNumber?: string | null; sortKey?: string | null; confidence?: Confidence | null; + source?: Source | null; dewey?: string | null; status?: Status; attentionReason?: string | null; + manualOverride?: boolean; inQueue?: boolean; +} +export type BookPatch = Partial>; +export type Filter = 'all' | 'queue' | 'attention'; + +export interface Db { + insertPending(fields: NewBook): { book: Book; created: boolean }; + getBook(id: number): Book | null; + findByIsbn(isbn13: string): Book | null; + listBooks(opts?: { filter?: Filter; q?: string }): Book[]; + updateBook(id: number, patch: BookPatch): Book | null; + deleteBook(id: number): boolean; + listPendingIds(): number[]; + getSettings(): Settings; + putSettings(s: Settings): void; + cache: SourceCache; + close(): void; +} + +type Row = Record; + +const COLUMNS: Record = { + isbn13: 'isbn13', lccn: 'lccn', title: 'title', subtitle: 'subtitle', authors: 'authors', + publisher: 'publisher', year: 'year', subjects: 'subjects', callNumber: 'call_number', + sortKey: 'sort_key', confidence: 'confidence', source: 'source', dewey: 'dewey', + status: 'status', attentionReason: 'attention_reason', manualOverride: 'manual_override', + inQueue: 'in_queue', printedAt: 'printed_at', +}; +const JSON_FIELDS = new Set(['authors', 'subjects']); +const BOOL_FIELDS = new Set(['manualOverride', 'inQueue']); + +function toRow(key: string, v: unknown): unknown { + if (JSON_FIELDS.has(key)) return JSON.stringify(v ?? []); + if (BOOL_FIELDS.has(key)) return v ? 1 : 0; + return v === undefined ? null : v; +} + +function toBook(r: Row): Book { + return { + id: r.id, isbn13: r.isbn13, lccn: r.lccn, title: r.title, subtitle: r.subtitle, + authors: JSON.parse(r.authors), publisher: r.publisher, year: r.year, + subjects: JSON.parse(r.subjects), callNumber: r.call_number, sortKey: r.sort_key, + confidence: r.confidence, source: r.source, dewey: r.dewey, status: r.status, + attentionReason: r.attention_reason, manualOverride: !!r.manual_override, + inQueue: !!r.in_queue, printedAt: r.printed_at, createdAt: r.created_at, updatedAt: r.updated_at, + }; +} + +const DEFAULT_SETTINGS: Settings = { offsetXmm: 0, offsetYmm: 0 }; + +export function openDb(path: string): Db { + if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true }); + const db = new DatabaseSync(path); + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE IF NOT EXISTS books ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + isbn13 TEXT UNIQUE, + lccn TEXT, + title TEXT NOT NULL, + subtitle TEXT, + authors TEXT NOT NULL DEFAULT '[]', + publisher TEXT, + year INTEGER, + subjects TEXT NOT NULL DEFAULT '[]', + call_number TEXT, + sort_key TEXT, + confidence TEXT, + source TEXT, + dewey TEXT, + status TEXT NOT NULL DEFAULT 'pending', + attention_reason TEXT, + manual_override INTEGER NOT NULL DEFAULT 0, + in_queue INTEGER NOT NULL DEFAULT 0, + printed_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS source_cache (key TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); + `); + + const getById = db.prepare('SELECT * FROM books WHERE id = ?'); + const getByIsbn = db.prepare('SELECT * FROM books WHERE isbn13 = ?'); + const insert = db.prepare(`INSERT INTO books (isbn13, lccn, title, subtitle, authors, publisher, year, + subjects, call_number, sort_key, confidence, source, dewey, status, attention_reason, + manual_override, in_queue, created_at, updated_at) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(isbn13) DO NOTHING`); + + const self: Db = { + insertPending(f) { + const now = new Date().toISOString(); + const r = insert.run( + f.isbn13 ?? null, f.lccn ?? null, f.title, f.subtitle ?? null, JSON.stringify(f.authors ?? []), + f.publisher ?? null, f.year ?? null, JSON.stringify(f.subjects ?? []), f.callNumber ?? null, + f.sortKey ?? null, f.confidence ?? null, f.source ?? null, f.dewey ?? null, + f.status ?? 'pending', f.attentionReason ?? null, f.manualOverride ? 1 : 0, + (f.inQueue ?? true) ? 1 : 0, now, now, + ); + if (r.changes === 0 && f.isbn13) return { book: self.findByIsbn(f.isbn13)!, created: false }; + return { book: self.getBook(Number(r.lastInsertRowid))!, created: true }; + }, + getBook(id) { + const r = getById.get(id) as Row | undefined; + return r ? toBook(r) : null; + }, + findByIsbn(isbn) { + const r = getByIsbn.get(isbn) as Row | undefined; + return r ? toBook(r) : null; + }, + listBooks({ filter = 'all', q } = {}) { + const where: string[] = []; + const params: string[] = []; + if (filter === 'queue') where.push('in_queue = 1'); + if (filter === 'attention') where.push("status = 'needs_attention'"); + const needle = q?.trim().toLowerCase(); + if (needle) { + where.push(`(instr(lower(title), ?) > 0 OR instr(lower(authors), ?) > 0 OR + instr(lower(coalesce(isbn13, '')), ?) > 0 OR instr(lower(coalesce(call_number, '')), ?) > 0)`); + params.push(needle, needle, needle, needle); + } + const sql = `SELECT * FROM books ${where.length ? 'WHERE ' + where.join(' AND ') : ''} + ORDER BY sort_key IS NULL, sort_key, title COLLATE NOCASE, id`; + return (db.prepare(sql).all(...params) as Row[]).map(toBook); + }, + updateBook(id, patch) { + const keys = Object.keys(patch).filter((k) => k in COLUMNS && (patch as Row)[k] !== undefined) as (keyof BookPatch)[]; + const sets = keys.map((k) => `${COLUMNS[k]} = ?`); + sets.push('updated_at = ?'); + const vals = keys.map((k) => toRow(k, (patch as Row)[k])); + const r = db.prepare(`UPDATE books SET ${sets.join(', ')} WHERE id = ?`) + .run(...(vals as any[]), new Date().toISOString(), id); + return r.changes ? self.getBook(id) : null; + }, + deleteBook(id) { + return db.prepare('DELETE FROM books WHERE id = ?').run(id).changes > 0; + }, + listPendingIds() { + return (db.prepare("SELECT id FROM books WHERE status = 'pending' ORDER BY id").all() as Row[]).map((r) => r.id); + }, + getSettings() { + const r = db.prepare("SELECT value FROM settings WHERE key = 'settings'").get() as Row | undefined; + return r ? { ...DEFAULT_SETTINGS, ...JSON.parse(r.value) } : { ...DEFAULT_SETTINGS }; + }, + putSettings(s) { + db.prepare("INSERT INTO settings (key, value) VALUES ('settings', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value") + .run(JSON.stringify(s)); + }, + cache: { + get(key) { + const r = db.prepare('SELECT body FROM source_cache WHERE key = ?').get(key) as Row | undefined; + return r ? r.body : null; + }, + set(key, body) { + db.prepare('INSERT INTO source_cache (key, body) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET body = excluded.body') + .run(key, body); + }, + }, + close() { db.close(); }, + }; + return self; +} diff --git a/src/server/jobs.test.ts b/src/server/jobs.test.ts new file mode 100644 index 0000000..55640bd --- /dev/null +++ b/src/server/jobs.test.ts @@ -0,0 +1,142 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb } from './db.ts'; +import { createJobs } from './jobs.ts'; +import type { ResolverLike } from './jobs.ts'; +import type { Book, Resolution } from '../shared/types.ts'; + +class TemporaryError extends Error {} + +const found: Resolution = { + meta: { title: 'The Rust Book', authors: ['Klabnik, Steve'], subjects: ['Rust'], year: 2018, publisher: 'No Starch' }, + callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: '005.1', + reason: null, +}; + +function setup(resolve: ResolverLike['resolve']) { + const db = openDb(':memory:'); + const changes: Book[] = []; + const resolver: ResolverLike = { resolve, search: async () => [] }; + const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0, 0, 0] }); + return { db, jobs, changes }; +} + +test('success resolves the book and emits changes', async () => { + const { db, jobs, changes } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); + jobs.enqueue(book.id); + await jobs.idle(); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'resolved'); + assert.equal(b.title, 'The Rust Book'); + assert.equal(b.callNumber, 'QA76.73.R87 K53 2018'); + assert.equal(b.confidence, 'exact'); + assert.equal(b.dewey, '005.1'); + assert.ok(changes.length >= 2); +}); + +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' }); + jobs.enqueue(book.id); + await jobs.idle(); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'needs_attention'); + assert.equal(b.attentionReason, 'No Library of Congress number found'); + assert.equal(b.title, 'The Rust Book'); +}); + +test('no metadata -> needs_attention', async () => { + const reason = 'Not found in Open Library or the Library of Congress'; + const { db, jobs } = setup(async () => ({ meta: null, callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, reason })); + const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(db.getBook(book.id)!.attentionReason, reason); + assert.equal(db.getBook(book.id)!.title, '9781593278281'); +}); + +test('temporary failures retry then succeed', async () => { + let calls = 0; + const { db, jobs } = setup(async () => { + if (++calls < 3) throw new TemporaryError('blocked'); + return found; + }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(calls, 3); + assert.equal(db.getBook(book.id)!.status, 'resolved'); +}); + +test('failure after all retries -> needs_attention', async () => { + let calls = 0; + const { db, jobs } = setup(async () => { calls++; throw new TemporaryError('blocked'); }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(calls, 4); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'needs_attention'); + assert.equal(b.attentionReason, 'Lookup failed: blocked'); +}); + +test('a non-temporary error never loses the book or stops the queue', async () => { + let n = 0; + const { db, jobs } = setup(async () => { if (n++ === 0) throw new Error('boom'); return found; }); + 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.equal(db.getBook(a.id)!.attentionReason, 'Lookup failed: boom'); + assert.equal(db.getBook(b.id)!.status, 'resolved'); +}); + +test('manual override keeps its call number', async () => { + const { db, jobs } = setup(async () => found); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'Mine', callNumber: 'PS3558.E63 D8 2005', + sortKey: 'PS', confidence: 'manual', source: 'manual', manualOverride: true }); + jobs.enqueue(book.id); + await jobs.idle(); + const b = db.getBook(book.id)!; + assert.equal(b.callNumber, 'PS3558.E63 D8 2005'); + assert.equal(b.confidence, 'manual'); + assert.equal(b.title, 'Mine'); +}); + +test('manual override set while pending is not clobbered', async () => { + const { db, jobs } = setup(async () => found); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + db.updateBook(book.id, { manualOverride: true, callNumber: 'PS3558', status: 'resolved', confidence: 'manual' }); + await jobs.idle(); + const b = db.getBook(book.id)!; + assert.equal(b.callNumber, 'PS3558'); + assert.equal(b.status, 'resolved'); +}); + +test('one job at a time, and resume() picks up pending rows', async () => { + let active = 0, peak = 0; + const { db, jobs } = setup(async () => { + peak = Math.max(peak, ++active); + await new Promise((r) => setImmediate(r)); + active--; + return found; + }); + const ids = ['9781593278281', '9780201835953', '9780441172719'].map((i) => db.insertPending({ isbn13: i, title: i }).book.id); + db.updateBook(ids[2]!, { status: 'resolved' }); + jobs.resume(); + await jobs.idle(); + assert.equal(peak, 1); + assert.equal(db.getBook(ids[0]!)!.status, 'resolved'); + assert.equal(db.getBook(ids[1]!)!.status, 'resolved'); +}); + +test('deleting a book mid-queue is harmless', async () => { + const { db, jobs } = setup(async () => found); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + db.deleteBook(book.id); + await jobs.idle(); + assert.equal(db.getBook(book.id), null); +}); diff --git a/src/server/jobs.ts b/src/server/jobs.ts new file mode 100644 index 0000000..41d90df --- /dev/null +++ b/src/server/jobs.ts @@ -0,0 +1,128 @@ +import type { Book, BookMeta, ResolveInput, Resolution, SearchResult } from '../shared/types.ts'; +import type { Db } from './db.ts'; + +// Structural match for Resolver in resolve/resolver.ts (Task 2). +export interface ResolverLike { + resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise; + search(title: string, author: string): Promise; +} + +export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise } + +// TemporaryError lives in resolve/resolver.ts; match by class name unless the caller injects a test. +function defaultIsTemporary(e: unknown): boolean { + for (let p = e != null && typeof e === 'object' ? Object.getPrototypeOf(e) : null; p; p = Object.getPrototypeOf(p)) { + if (p.constructor?.name === 'TemporaryError') return true; + } + return false; +} + +function sleep(ms: number): Promise { + if (ms <= 0) return Promise.resolve(); + return new Promise((resolve) => { setTimeout(resolve, ms).unref(); }); +} + +export function createJobs(deps: { + db: Db; resolver: ResolverLike; onChange: (book: Book) => void; + retryDelaysMs?: number[]; isTemporary?: (e: unknown) => boolean; +}): Jobs { + const { db, resolver, onChange } = deps; + const delays = deps.retryDelaysMs ?? [30000, 120000, 600000]; + const isTemporary = deps.isTemporary ?? defaultIsTemporary; + const queue: number[] = []; + const queued = new Set(); + let running: Promise | null = null; + + function emit(id: number, patch: Parameters[1]): void { + const b = db.updateBook(id, patch); + if (b) onChange(b); + } + + function applyMeta(id: number, meta: BookMeta): void { + const cur = db.getBook(id); + if (!cur) return; + const patch: Parameters[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); + } + + async function lookup(id: number): Promise { + 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]; + } + 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 }); + } + return; + } + } + } + + async function drain(): Promise { + 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 */ } + } + } + + function start(): void { + if (running) return; + running = drain().finally(() => { running = null; if (queue.length) start(); }); + } + + return { + enqueue(id) { + if (queued.has(id)) return; + queued.add(id); + queue.push(id); + start(); + }, + resume() { for (const id of db.listPendingIds()) this.enqueue(id); }, + async idle() { + while (running || queue.length) await running; + }, + }; +} diff --git a/src/server/main.ts b/src/server/main.ts new file mode 100644 index 0000000..3a3754b --- /dev/null +++ b/src/server/main.ts @@ -0,0 +1,47 @@ +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { extname, join, normalize, resolve as resolvePath } from 'node:path'; +import { serve } from '@hono/node-server'; +import { openDb } from './db.ts'; +import { createJobs } from './jobs.ts'; +import { createApp, createEventBus } from './app.ts'; +import { createResolver, TemporaryError } from './resolve/resolver.ts'; +import { renderCalibrationPdf, renderCardsPdf } from './pdf/render.ts'; +import { classNames } from '../shared/lcc-outline.ts'; + +const port = Number(process.env.PORT ?? 4321); +const dbPath = process.env.BOOKSORTER_DB ?? 'data/booksorter.db'; +const webRoot = resolvePath(import.meta.dirname, '../../dist/web'); + +const MIME: Record = { + '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', + '.wasm': 'application/wasm', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', + '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json', '.map': 'application/json', +}; + +const db = openDb(dbPath); +const events = createEventBus(); +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 }); + +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); + return c.body(readFileSync(file), 200, { 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream' }); +}); + +const server = serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => { + console.log(`Booksorter running at http://localhost:${port}`); + jobs.resume(); +}); +server.on('error', (err: NodeJS.ErrnoException) => { + if (err.code === 'EADDRINUSE') console.error(`Port ${port} is already in use. Is Booksorter already running?`); + else console.error(err.message); + process.exit(1); +}); diff --git a/src/server/pdf/card.test.ts b/src/server/pdf/card.test.ts new file mode 100644 index 0000000..50fc9df --- /dev/null +++ b/src/server/pdf/card.test.ts @@ -0,0 +1,76 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { layoutCard, wrap } from './card.ts'; +import type { CardData } from '../../shared/types.ts'; + +const measure = (t: string, size: number, _b: boolean) => Array.from(t).length * size * 0.55; +const base: CardData = { + callNumber: 'QA76.73.R87 K53 2018', className: 'Science', subclassName: 'Mathematics', + title: 'The Rust Programming Language', authors: ['Steve Klabnik', 'Carol Nichols'], + publisher: 'No Starch Press', year: 2018, subjects: ['Rust (Computer program language)'], + isbn13: '9781593278281', approximate: true, +}; +const widthOf = (r: { text: string; size: number; bold: boolean }) => measure(r.text, r.size, r.bold); + +function checkBounds(runs: ReturnType) { + for (const r of runs) { + assert.ok(r.x >= 14, `x ${r.text}`); + assert.ok(r.x + widthOf(r) <= 202 + 1e-9, `right edge ${r.text}`); + assert.ok(r.y >= 10 && r.y <= 350, `y ${r.text}`); + } +} + +test('call number in top inch; everything inside margins', () => { + const runs = layoutCard(base, measure); + checkBounds(runs); + assert.ok(runs[0]!.y >= 288 && runs[1]!.y >= 288); + assert.equal(runs[0]!.text, 'QA76.73.R87'); + assert.equal(runs[1]!.text, 'K53 2018'); +}); + +test('300 character title takes at most 3 runs and ends with an ellipsis', () => { + const title = Array.from({ length: 50 }, (_, i) => `word${i}`).join(' ').slice(0, 300); + const runs = layoutCard({ ...base, title }, measure); + checkBounds(runs); + const t = runs.filter((r) => r.bold && r.size <= 13 && r.size >= 11 && r.y < 288 && r.y > 100 && r.text !== '~'); + assert.ok(t.length <= 3 && t.length >= 1); + assert.ok(t[t.length - 1]!.text.endsWith('…')); +}); + +test('twelve authors end with et al.', () => { + const authors = Array.from({ length: 12 }, (_, i) => `Author${i}`); + const runs = layoutCard({ ...base, authors }, measure); + checkBounds(runs); + const a = runs.filter((r) => r.size === 10); + assert.ok(a[a.length - 1]!.text.endsWith('et al.')); +}); + +test('three-cutter call number shrinks and fits', () => { + const runs = layoutCard({ ...base, callNumber: 'QA76.73.C153 S77 K47 2013' }, measure); + checkBounds(runs); + assert.ok(runs[0]!.size < 26 || runs[0]!.text.length > 0); + assert.ok(widthOf(runs[0]!) <= 188); + const long = layoutCard({ ...base, callNumber: 'QA76.73.C153999999 S77' }, measure); + assert.ok(long[0]!.size < 26); + assert.ok(widthOf(long[0]!) <= 188); +}); + +test('unparseable call number prints whole on line 1', () => { + const runs = layoutCard({ ...base, callNumber: 'garbage' }, measure); + assert.equal(runs[0]!.text, 'garbage'); + assert.ok(!runs.some((r) => r.y === 300)); +}); + +test('wrap breaks a word wider than the line and terminates', () => { + const lines = wrap('x'.repeat(500), 10, false, measure); + assert.ok(lines.length > 1); + for (const l of lines) assert.ok(measure(l, 10, false) <= 188); + assert.equal(lines.join('').length, 500); + assert.deepEqual(wrap('', 10, false, measure), []); +}); + +test('omitted pieces: no subclass duplicate, no isbn, no tilde', () => { + const runs = layoutCard({ ...base, subclassName: 'Science', isbn13: null, approximate: false }, measure); + assert.equal(runs.filter((r) => r.text === 'Science').length, 1); + assert.ok(!runs.some((r) => r.text.startsWith('ISBN') || r.text === '~')); +}); diff --git a/src/server/pdf/card.ts b/src/server/pdf/card.ts new file mode 100644 index 0000000..206de0b --- /dev/null +++ b/src/server/pdf/card.ts @@ -0,0 +1,134 @@ +import { parseCallNumber, cardLines } from '../../shared/callnumber.ts'; +import type { CardData } from '../../shared/types.ts'; + +export interface TextRun { text: string; x: number; y: number; size: number; bold: boolean; gray: number } +export type Measure = (text: string, size: number, bold: boolean) => number; + +export const MARGIN_X = 14; +export const TEXT_WIDTH = 188; +export const RULE_Y = 286; +const GRAY = 0.35; +const BLOCK_START = 268; +const BLOCK_GAP = 8; +const BLOCK_FLOOR = 30; +const ELLIPSIS = '…'; + +/** Largest size (1 pt steps, down to min) at which text fits; text is truncated if min still overflows. */ +function fitLine(text: string, start: number, min: number, bold: boolean, m: Measure): { text: string; size: number } { + let size = start; + while (size > min && m(text, size, bold) > TEXT_WIDTH) size--; + return { text: truncate(text, size, bold, m), size }; +} + +/** Shorten text until text + ellipsis fits; unchanged if it already fits. */ +function truncate(text: string, size: number, bold: boolean, m: Measure): string { + if (m(text, size, bold) <= TEXT_WIDTH) return text; + const chars = Array.from(text); + while (chars.length > 0) { + chars.pop(); + const t = chars.join('').trimEnd() + ELLIPSIS; + if (m(t, size, bold) <= TEXT_WIDTH) return t; + } + return ELLIPSIS; +} + +/** Break one over-long word into pieces that each fit. Always consumes at least one character per piece. */ +function breakWord(word: string, size: number, bold: boolean, m: Measure): string[] { + const out: string[] = []; + let cur = ''; + for (const ch of Array.from(word)) { + if (cur && m(cur + ch, size, bold) > TEXT_WIDTH) { out.push(cur); cur = ch; } else cur += ch; + } + if (cur) out.push(cur); + return out; +} + +export function wrap(text: string, size: number, bold: boolean, m: Measure): string[] { + const words = text.split(/\s+/).filter(Boolean); + const lines: string[] = []; + let cur = ''; + for (const word of words) { + const joined = cur ? cur + ' ' + word : word; + if (m(joined, size, bold) <= TEXT_WIDTH) { cur = joined; continue; } + if (cur) { lines.push(cur); cur = ''; } + if (m(word, size, bold) <= TEXT_WIDTH) { cur = word; continue; } + const pieces = breakWord(word, size, bold, m); + cur = pieces.pop() ?? ''; + lines.push(...pieces); + } + if (cur) lines.push(cur); + return lines; +} + +/** Wrap to at most maxLines; overflow is folded into the last line and truncated with an ellipsis. */ +function wrapLimited(text: string, size: number, bold: boolean, maxLines: number, m: Measure): { lines: string[]; overflow: boolean } { + const all = wrap(text, size, bold, m); + if (all.length <= maxLines) return { lines: all, overflow: false }; + const lines = all.slice(0, maxLines - 1); + const last = all.slice(maxLines - 1).join(' '); + lines.push(truncate(last + ELLIPSIS, size, bold, m)); // forces an ellipsis even if the folded text fits + return { lines, overflow: true }; +} + +interface Block { size: number; bold: boolean; gray: number; lines: string[] } + +const LEADING = 1.2; + +export function layoutCard(card: CardData, measure: Measure): TextRun[] { + const runs: TextRun[] = []; + const cn = parseCallNumber(card.callNumber); + const [l1, l2] = cn ? cardLines(cn) : [card.callNumber, '']; + const a = fitLine(l1, 26, 12, true, measure); + runs.push({ text: a.text, x: MARGIN_X, y: 326, size: a.size, bold: true, gray: 0 }); + if (l2) { + const b = fitLine(l2, 20, 11, true, measure); + runs.push({ text: b.text, x: MARGIN_X, y: 300, size: b.size, bold: true, gray: 0 }); + } + + const blocks: Block[] = []; + const names: string[] = []; + if (card.className) names.push(card.className); + if (card.subclassName && card.subclassName !== card.className) names.push(card.subclassName); + if (names.length) { + blocks.push({ size: 9, bold: false, gray: GRAY, lines: names.map((n) => truncate(n, 9, false, measure)) }); + } + + if (card.title.trim()) { + let t = wrapLimited(card.title, 13, true, 3, measure); + let size = 13; + if (t.overflow) { size = 11; t = wrapLimited(card.title, 11, true, 3, measure); } + blocks.push({ size, bold: true, gray: 0, lines: t.lines }); + } + + if (card.authors.length) { + const list = card.authors.length > 3 ? card.authors.slice(0, 3).join(', ') + ' et al.' : card.authors.join(', '); + blocks.push({ size: 10, bold: false, gray: 0, lines: wrapLimited(list, 10, false, 2, measure).lines }); + } + + const pub = [card.publisher, card.year != null ? String(card.year) : null].filter(Boolean).join(', '); + if (pub) blocks.push({ size: 9, bold: false, gray: 0, lines: [truncate(pub, 9, false, measure)] }); + + for (const s of card.subjects.slice(0, 2)) { + if (s.trim()) blocks.push({ size: 9, bold: false, gray: GRAY, lines: wrapLimited(s, 9, false, 2, measure).lines }); + } + + let top = BLOCK_START; + for (const b of blocks) { + const lh = b.size * LEADING; + const bottom = top - b.lines.length * lh; + if (bottom < BLOCK_FLOOR) continue; // dropped whole; later (shorter) blocks may still fit + b.lines.forEach((text, i) => { + runs.push({ text, x: MARGIN_X, y: top - i * lh - b.size * 0.85, size: b.size, bold: b.bold, gray: b.gray }); + }); + top = bottom - BLOCK_GAP; + } + + if (card.isbn13) { + runs.push({ text: `ISBN ${card.isbn13}`, x: MARGIN_X, y: 16, size: 8, bold: false, gray: 0 }); + } + if (card.approximate) { + const w = measure('~', 12, true); + runs.push({ text: '~', x: MARGIN_X + TEXT_WIDTH - w, y: 16, size: 12, bold: true, gray: 0 }); + } + return runs; +} diff --git a/src/server/pdf/layout.test.ts b/src/server/pdf/layout.test.ts new file mode 100644 index 0000000..1e5a226 --- /dev/null +++ b/src/server/pdf/layout.test.ts @@ -0,0 +1,28 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { cardMatrix, CARD } from './layout.ts'; + +const zero = { offsetXmm: 0, offsetYmm: 0 }; +const mm = 72 / 25.4; + +test('matrix values and offsets', () => { + assert.deepEqual(cardMatrix(1, zero), [0, 1, -1, 0, 486, 504]); + assert.equal(cardMatrix(3, zero)[5], 72); + assert.ok(Math.abs(cardMatrix(1, { offsetXmm: 1, offsetYmm: 0 })[4] - (486 + mm)) < 1e-9); + assert.ok(Math.abs(cardMatrix(1, { offsetXmm: 0, offsetYmm: 1 })[5] - (504 - mm)) < 1e-9); +}); + +test('corners map to the sheet rectangles', () => { + const ys = { 1: 504, 2: 288, 3: 72 } as const; + for (const p of [1, 2, 3] as const) { + const [a, b, c, d, e, f] = cardMatrix(p, zero); + const pts = [[0, 0], [CARD.width, 0], [0, CARD.height], [CARD.width, CARD.height]] + .map(([x, y]) => [a * x + c * y + e, b * x + d * y + f]); + assert.equal(Math.min(...pts.map((q) => q[0]!)), 126); + assert.equal(Math.max(...pts.map((q) => q[0]!)), 486); + assert.equal(Math.min(...pts.map((q) => q[1]!)), ys[p]); + assert.equal(Math.max(...pts.map((q) => q[1]!)), ys[p] + 216); + // card top (y = 360) lands on the left edge (x = 126) + assert.equal(a * 0 + c * CARD.height + e, 126); + } +}); diff --git a/src/server/pdf/layout.ts b/src/server/pdf/layout.ts new file mode 100644 index 0000000..84cdac8 --- /dev/null +++ b/src/server/pdf/layout.ts @@ -0,0 +1,16 @@ +import type { Settings } from '../../shared/types.ts'; + +export const SHEET = { width: 612, height: 792 }; +export const CARD = { width: 216, height: 360 }; // card-local, upright + +const Y_BOTTOM = { 1: 504, 2: 288, 3: 72 } as const; +const PT_PER_MM = 72 / 25.4; + +export type Matrix = [number, number, number, number, number, number]; + +/** Quarter turn anticlockwise: card-local (x, y) maps to sheet (486 + dx - y, yBottom - dy + x). */ +export function cardMatrix(position: 1 | 2 | 3, s: Settings): Matrix { + const dx = s.offsetXmm * PT_PER_MM; + const dy = s.offsetYmm * PT_PER_MM; + return [0, 1, -1, 0, 486 + dx, Y_BOTTOM[position] - dy]; +} diff --git a/src/server/pdf/render.test.ts b/src/server/pdf/render.test.ts new file mode 100644 index 0000000..ab4725d --- /dev/null +++ b/src/server/pdf/render.test.ts @@ -0,0 +1,31 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { PDFDocument } from 'pdf-lib'; +import { renderCardsPdf, renderCalibrationPdf } from './render.ts'; +import type { CardData } from '../../shared/types.ts'; + +const zero = { offsetXmm: 0, offsetYmm: 0 }; +const card: CardData = { + callNumber: 'QA76.73.R87 K53 2018', className: 'Science', subclassName: 'Mathematics', + title: 'The Rust Programming Language', authors: ['Steve Klabnik'], publisher: 'No Starch Press', + year: 2018, subjects: [], isbn13: null, approximate: false, +}; + +test('4 cards starting at position 3 make 2 pages', async () => { + const bytes = await renderCardsPdf([card, card, card, card], { ...zero, startPosition: 3 }); + assert.equal((await PDFDocument.load(bytes)).getPageCount(), 2); +}); + +test('no cards rejects', async () => { + await assert.rejects(renderCardsPdf([], { ...zero, startPosition: 1 })); +}); + +test('unsupported characters render without throwing', async () => { + const bytes = await renderCardsPdf([{ ...card, title: '日本語のタイトル 🙂', authors: ['日本'] }], { ...zero, startPosition: 1 }); + assert.ok(bytes.length > 1000); +}); + +test('calibration page renders one page', async () => { + const bytes = await renderCalibrationPdf({ offsetXmm: 0.5, offsetYmm: -0.3 }); + assert.equal((await PDFDocument.load(bytes)).getPageCount(), 1); +}); diff --git a/src/server/pdf/render.ts b/src/server/pdf/render.ts new file mode 100644 index 0000000..6f33147 --- /dev/null +++ b/src/server/pdf/render.ts @@ -0,0 +1,115 @@ +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { PDFDocument, rgb, pushGraphicsState, popGraphicsState, concatTransformationMatrix } from 'pdf-lib'; +import type { PDFFont, PDFPage } from 'pdf-lib'; +import fontkit from '@pdf-lib/fontkit'; +import type { CardData, Settings } from '../../shared/types.ts'; +import { layoutCard, MARGIN_X, TEXT_WIDTH, RULE_Y } from './card.ts'; +import { SHEET, CARD, cardMatrix } from './layout.ts'; + +interface Fonts { regular: PDFFont; bold: PDFFont; has: (cp: number) => boolean } + +let fontBytes: Promise<{ regular: Uint8Array; bold: Uint8Array }> | undefined; +function loadFontBytes() { + fontBytes ??= (async () => { + const dir = path.join(path.dirname(createRequire(import.meta.url).resolve('dejavu-fonts-ttf/package.json')), 'ttf'); + const [regular, bold] = await Promise.all([ + readFile(path.join(dir, 'DejaVuSans.ttf')), + readFile(path.join(dir, 'DejaVuSans-Bold.ttf')), + ]); + return { regular: new Uint8Array(regular), bold: new Uint8Array(bold) }; + })(); + return fontBytes; +} + +async function setup(): Promise<{ doc: PDFDocument; fonts: Fonts }> { + const bytes = await loadFontBytes(); + const doc = await PDFDocument.create(); + doc.registerFontkit(fontkit); + const regular = await doc.embedFont(bytes.regular, { subset: false }); + const bold = await doc.embedFont(bytes.bold, { subset: false }); + const kit = fontkit.create(bytes.regular); + return { doc, fonts: { regular, bold, has: (cp) => kit.hasGlyphForCodePoint(cp) } }; +} + +/** Replace characters the font cannot draw with '?'; control characters and runs of whitespace become one space. */ +function clean(text: string, fonts: Fonts): string { + let out = ''; + for (const ch of text.replace(/\s+/g, ' ')) out += fonts.has(ch.codePointAt(0)!) ? ch : '?'; + return out; +} + +function cleanCard(c: CardData, f: Fonts): CardData { + const n = (s: string | null) => (s == null ? null : clean(s, f)); + return { + ...c, + callNumber: clean(c.callNumber, f), className: n(c.className), subclassName: n(c.subclassName), + title: clean(c.title, f), authors: c.authors.map((s) => clean(s, f)), publisher: n(c.publisher), + subjects: c.subjects.map((s) => clean(s, f)), isbn13: n(c.isbn13), + }; +} + +function inCardSpace(page: PDFPage, m: ReturnType, draw: () => void) { + page.pushOperators(pushGraphicsState(), concatTransformationMatrix(...m)); + draw(); + page.pushOperators(popGraphicsState()); +} + +function drawCard(page: PDFPage, card: CardData, fonts: Fonts) { + const measure = (t: string, size: number, bold: boolean) => + (bold ? fonts.bold : fonts.regular).widthOfTextAtSize(clean(t, fonts), size); + for (const r of layoutCard(cleanCard(card, fonts), measure)) { + page.drawText(clean(r.text, fonts), { + x: r.x, y: r.y, size: r.size, font: r.bold ? fonts.bold : fonts.regular, color: rgb(r.gray, r.gray, r.gray), + }); + } + page.drawLine({ + start: { x: MARGIN_X, y: RULE_Y }, end: { x: MARGIN_X + TEXT_WIDTH, y: RULE_Y }, + thickness: 0.75, color: rgb(0, 0, 0), + }); +} + +export async function renderCardsPdf( + cards: CardData[], opts: Settings & { startPosition: 1 | 2 | 3 }, +): Promise { + if (cards.length === 0) throw new Error('no cards to render'); + const { doc, fonts } = await setup(); + let page: PDFPage | undefined; + cards.forEach((card, i) => { + const slot = opts.startPosition - 1 + i; + const pos = ((slot % 3) + 1) as 1 | 2 | 3; + if (!page || pos === 1) page = doc.addPage([SHEET.width, SHEET.height]); + inCardSpace(page, cardMatrix(pos, opts), () => drawCard(page!, card, fonts)); + }); + return doc.save(); +} + +export async function renderCalibrationPdf(s: Settings): Promise { + const { doc, fonts } = await setup(); + const page = doc.addPage([SHEET.width, SHEET.height]); + for (const pos of [1, 2, 3] as const) { + inCardSpace(page, cardMatrix(pos, s), () => { + page.drawRectangle({ + x: 0, y: 0, width: CARD.width, height: CARD.height, borderWidth: 0.5, borderColor: rgb(0, 0, 0), + }); + const cx = CARD.width / 2, cy = CARD.height / 2; + page.drawLine({ start: { x: cx - 8, y: cy }, end: { x: cx + 8, y: cy }, thickness: 0.5, color: rgb(0, 0, 0) }); + page.drawLine({ start: { x: cx, y: cy - 8 }, end: { x: cx, y: cy + 8 }, thickness: 0.5, color: rgb(0, 0, 0) }); + if (pos === 1) { + // Wrapped to fit the 188 pt text width; the message text itself is unchanged. + const msg = `Calibration: hold against an Avery 5388 sheet. Offset X ${s.offsetXmm} mm, Y ${s.offsetYmm} mm.`; + const words = msg.split(' '); + let line = '', y = CARD.height - 30; + for (const w of words) { + const next = line ? line + ' ' + w : w; + if (fonts.regular.widthOfTextAtSize(next, 8) > TEXT_WIDTH && line) { + page.drawText(line, { x: MARGIN_X, y, size: 8, font: fonts.regular }); y -= 10; line = w; + } else line = next; + } + page.drawText(line, { x: MARGIN_X, y, size: 8, font: fonts.regular }); + } + }); + } + return doc.save(); +} diff --git a/src/server/resolve/choose.test.ts b/src/server/resolve/choose.test.ts new file mode 100644 index 0000000..e115606 --- /dev/null +++ b/src/server/resolve/choose.test.ts @@ -0,0 +1,70 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { chooseCallNumber } from './choose.ts'; +import type { Tiers } from './choose.ts'; + +const none: Tiers = { locExact: [], olEdition: [], locTitle: [], olWork: [] }; +const raws = (...r: string[]) => r.map((raw) => ({ raw })); +const m = { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language' }; + +test('LoC exact complete', () => { + const r = chooseCallNumber({ ...none, locExact: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, m); + assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018'); + assert.equal(r?.confidence, 'exact'); + assert.equal(r?.source, 'loc-isbn'); +}); + +test('exact source is passed through', () => { + const r = chooseCallNumber({ ...none, locExact: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, m, 'loc-lccn'); + assert.equal(r?.source, 'loc-lccn'); +}); + +test('OL edition most frequent after normalizing', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.C15 K47 1988', 'QA76.73.C15 .K4718 1991', 'QA76.73.C15K47 1988') }, m); + assert.equal(r?.callNumber, 'QA76.73.C15 K47 1988'); + assert.equal(r?.confidence, 'exact'); + assert.equal(r?.source, 'ol-edition'); +}); + +test('legacy PZ3 dropped when literature class present', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('PZ3.H4186 Du', 'PS3558.E63 D8 2005') }, m); + assert.equal(r?.callNumber, 'PS3558.E63 D8 2005'); +}); + +test('PZ kept when it is the only class', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('PZ3.H4186 Du 1990') }, m); + assert.match(r!.callNumber, /^PZ3/); +}); + +test('LoC title: approximate, year replaced', () => { + const r = chooseCallNumber({ ...none, locTitle: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, { ...m, year: 2023 }); + assert.equal(r?.callNumber, 'QA76.73.R87 K53 2023'); + assert.equal(r?.confidence, 'approximate'); + assert.equal(r?.source, 'loc-title'); +}); + +test('OL work: padded class gets cutter and year', () => { + const r = chooseCallNumber({ ...none, olWork: raws('QA-0076.76000000.A65') }, { ...m, year: 2018 }); + assert.equal(r?.callNumber, 'QA76.76.A65 K53 2018'); + assert.equal(r?.confidence, 'approximate'); + assert.equal(r?.source, 'ol-work'); +}); + +test('incomplete exact candidate with unknown year gets cutter only', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, m); + assert.equal(r?.callNumber, 'QA76.73.R87 K53'); +}); + +test('tie goes to the longest first line', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('QA76.A1 2000', 'QA76.73.R87 K53 2018') }, m); + assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018'); +}); + +test('earlier tier wins over later tiers', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87 K53 2018'), olWork: raws('PS3558.E63 D8 2005') }, m); + assert.equal(r?.source, 'ol-edition'); +}); + +test('unparseable only -> null', () => { + assert.equal(chooseCallNumber({ ...none, olEdition: raws('[E]', 'Fic') }, m), null); +}); diff --git a/src/server/resolve/choose.ts b/src/server/resolve/choose.ts new file mode 100644 index 0000000..0a6c0c4 --- /dev/null +++ b/src/server/resolve/choose.ts @@ -0,0 +1,75 @@ +import type { Candidate, Source } from '../../shared/types.ts'; +import type { CallNumber } from '../../shared/callnumber.ts'; +import { cardLines, formatCallNumber, hasYear, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts'; +import { cutterFor, mainEntry } from '../../shared/cutter.ts'; + +export interface Tiers { locExact: Candidate[]; olEdition: Candidate[]; locTitle: Candidate[]; olWork: Candidate[] } + +interface Parsed { cn: CallNumber; complete: boolean | undefined; formatted: string } + +function parseAll(cands: Candidate[]): Parsed[] { + const out: Parsed[] = []; + for (const c of cands) { + const cn = parseCallNumber(c.raw); + if (cn) out.push({ cn, complete: c.complete, formatted: formatCallNumber(cn) }); + } + return out; +} + +function dropLegacyFiction(ps: Parsed[]): Parsed[] { + const legacy = (p: Parsed) => p.cn.letters === 'PZ' && (p.cn.number === '3' || p.cn.number === '4'); + const literature = (p: Parsed) => /^P[A-Y]$/.test(p.cn.letters); + return ps.some(legacy) && ps.some(literature) ? ps.filter((p) => !legacy(p)) : ps; +} + +function pickMostFrequent(ps: Parsed[]): { cn: CallNumber; complete: boolean } { + const groups = new Map(); + for (const p of ps) { + const g = groups.get(p.formatted); + if (g) g.push(p); else groups.set(p.formatted, [p]); + } + const ranked = [...groups.values()].sort((a, b) => { + if (a.length !== b.length) return b.length - a.length; + const la = cardLines(a[0]!.cn)[0].length; + const lb = cardLines(b[0]!.cn)[0].length; + if (la !== lb) return lb - la; + const ka = sortKey(a[0]!.cn); + const kb = sortKey(b[0]!.cn); + return ka < kb ? -1 : ka > kb ? 1 : 0; + }); + const g = ranked[0]!; + const cn = g[0]!.cn; + const explicit = g.find((p) => p.complete !== undefined)?.complete; + return { cn, complete: explicit ?? (hasYear(cn) || cn.cutters.length >= 2) }; +} + +const TIER_SOURCE: Record = { + locExact: 'loc-isbn', olEdition: 'ol-edition', locTitle: 'loc-title', olWork: 'ol-work', +}; + +export function chooseCallNumber( + tiers: Tiers, + meta: { authors: string[]; title: string; year?: number }, + exactSource?: 'loc-isbn' | 'loc-lccn', +): { callNumber: string; sortKey: string; confidence: 'exact' | 'approximate'; source: Source } | null { + const order: (keyof Tiers)[] = ['locExact', 'olEdition', 'locTitle', 'olWork']; + for (const tier of order) { + const ps = dropLegacyFiction(parseAll(tiers[tier])); + if (ps.length === 0) continue; + 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)); + cn = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }] }; + if (meta.year) cn = withYear(cn, meta.year); + } + if (approximate && meta.year) cn = withYear(cn, meta.year); + return { + callNumber: formatCallNumber(cn), + sortKey: sortKey(cn), + confidence: approximate ? 'approximate' : 'exact', + source: tier === 'locExact' ? (exactSource ?? 'loc-isbn') : TIER_SOURCE[tier], + }; + } + return null; +} diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts new file mode 100644 index 0000000..c04db66 --- /dev/null +++ b/src/server/resolve/resolver.test.ts @@ -0,0 +1,156 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createResolver, TemporaryError } from './resolver.ts'; +import type { SourceCache } from './resolver.ts'; +import { fixtureFetch } from '../sources/fixture-fetch.ts'; + +function memCache(): SourceCache & { map: Map } { + const map = new Map(); + return { map, get: (k) => map.get(k) ?? null, set: (k, v) => { map.set(k, v); } }; +} +const noSleep = async () => {}; + +test('Rust book: exact via LoC, onMeta fires before LoC is called', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }); + let locCallsAtMeta = -1; + let metaTitle = ''; + const res = await r.resolve({ isbn13: '9781593278281' }, { + onMeta: (m) => { locCallsAtMeta = f.locCalls().length; metaTitle = m.title; }, + }); + assert.equal(res.confidence, 'exact'); + assert.ok(res.callNumber!.startsWith('QA76.73.R87')); + assert.match(res.meta!.title, /Rust/); + assert.equal(locCallsAtMeta, 0); + assert.match(metaTitle, /Rust/); + assert.ok(res.sortKey); +}); + +test('Mythical Man-Month resolves', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780201835953' }); + assert.ok(res.callNumber, res.reason ?? ''); + assert.equal(res.confidence, 'exact'); + assert.match(res.callNumber!, /^QA76/); +}); + +test('Dune (not in LoC by ISBN) resolves with a literature class', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780441172719' }); + assert.ok(res.callNumber, res.reason ?? ''); + assert.match(res.callNumber!, /^PS3558/); +}); + +test('unknown ISBN', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780999999998' }); + assert.equal(res.meta, null); + assert.equal(res.callNumber, null); + assert.equal(res.reason, 'Not found in Open Library or the Library of Congress'); +}); + +test('LoC block page -> TemporaryError, and nothing cached for it', async () => { + const f = fixtureFetch(); + f.locOverride = 'loc-block.html'; + const cache = memCache(); + const r = createResolver({ fetch: f.fetch, cache, sleep: noSleep }); + await assert.rejects(r.resolve({ isbn13: '9781593278281' }), TemporaryError); + assert.equal([...cache.map.keys()].some((k) => k.startsWith('loc-')), false); +}); + +test('block page doubles the interval for later calls, capped at 60s', async () => { + const f = fixtureFetch(); + f.locOverride = 'loc-block.html'; + const sleeps: number[] = []; + const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 20_000, sleep: async (ms) => { sleeps.push(ms); } }); + await assert.rejects(r.resolve({ isbn13: '9781593278281' }), TemporaryError); + await assert.rejects(r.resolve({ isbn13: '9780201835953' }), TemporaryError); + await assert.rejects(r.resolve({ isbn13: '9780441172719' }), TemporaryError); + assert.ok(sleeps.length >= 2); + assert.ok(sleeps.every((s) => s <= 60_000)); + assert.ok(sleeps[0]! > 20_000 - 500, 'second request waits at least the doubled interval measured from the block'); +}); + +test('network error -> TemporaryError', async () => { + const r = createResolver({ fetch: (async () => { throw new TypeError('fetch failed'); }) as typeof fetch, cache: memCache(), sleep: noSleep }); + await assert.rejects(r.resolve({ isbn13: '9781593278281' }), TemporaryError); +}); + +test('5xx -> TemporaryError', async () => { + const r = createResolver({ fetch: (async () => new Response('x', { status: 503 })) as typeof fetch, cache: memCache(), sleep: noSleep }); + await assert.rejects(r.resolve({ isbn13: '9781593278281' }), TemporaryError); +}); + +test('second resolve of the same ISBN makes zero fetch calls', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }); + const a = await r.resolve({ isbn13: '9781593278281' }); + const n = f.calls.length; + assert.ok(n > 0); + const b = await r.resolve({ isbn13: '9781593278281' }); + assert.equal(f.calls.length, n); + assert.equal(b.callNumber, a.callNumber); +}); + +test('cache hits are not delayed by the throttle', async () => { + const f = fixtureFetch(); + const sleeps: number[] = []; + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: async (ms) => { sleeps.push(ms); } }); + await r.resolve({ isbn13: '9781593278281' }); + const before = sleeps.length; + await r.resolve({ isbn13: '9781593278281' }); + assert.equal(sleeps.length, before); +}); + +test('two uncached ISBNs are spaced by locIntervalMs', async () => { + const f = fixtureFetch(); + 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' }); + 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(); + 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); +}); + +test('LCCN only', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ lccn: '88005934' }); + assert.ok(res.callNumber); + assert.equal(res.source, 'loc-lccn'); + assert.equal(res.confidence, 'exact'); +}); + +test('title and author only uses the LoC title tier', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }) + .resolve({ title: 'The Mythical Man-Month', author: 'Brooks, Frederick P.', year: 1995 }); + assert.equal(res.source, 'loc-title'); + assert.equal(res.confidence, 'approximate'); + assert.match(res.callNumber!, /1995$/); + assert.ok(res.meta); +}); + +test('falls back to the HTTPS SRU endpoint when the first refuses', async () => { + const f = fixtureFetch(); + const wrapped = (async (input: string | URL | Request, init?: RequestInit) => { + if (String(input).includes(':210')) 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' }); + assert.ok(res.callNumber!.startsWith('QA76.73.R87')); +}); + +test('search by title and author', async () => { + const f = fixtureFetch(); + const out = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).search('mythical man-month', 'brooks'); + assert.ok(out.length > 0); + assert.ok(out[0]!.title); +}); diff --git a/src/server/resolve/resolver.ts b/src/server/resolve/resolver.ts new file mode 100644 index 0000000..24157d3 --- /dev/null +++ b/src/server/resolve/resolver.ts @@ -0,0 +1,151 @@ +import type { BookMeta, Candidate, ResolveInput, Resolution, SearchResult } from '../../shared/types.ts'; +import { normalizeIsbn } from '../../shared/isbn.ts'; +import { chooseCallNumber } from './choose.ts'; +import { createLoc } from '../sources/loc.ts'; +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 type { SourceCache } from '../sources/http.ts'; + +export { TemporaryError }; +export type { SourceCache }; + +export interface Resolver { + resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise; + search(title: string, author: string): Promise; +} + +type Partials = (Partial | null | undefined)[]; + +function mergeMeta(parts: Partials): BookMeta | null { + const first = (k: K): BookMeta[K] | undefined => { + for (const p of parts) { + const v = p?.[k]; + if (Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null && v !== '') return v as BookMeta[K]; + } + return undefined; + }; + const title = first('title'); + if (!title) return null; + const meta: BookMeta = { title, authors: first('authors') ?? [], subjects: first('subjects') ?? [] }; + const subtitle = first('subtitle'); if (subtitle) meta.subtitle = subtitle; + const publisher = first('publisher'); if (publisher) meta.publisher = publisher; + const year = first('year'); if (year) meta.year = year; + const lccn = first('lccn'); if (lccn) meta.lccn = lccn; + return meta; +} + +const lccOf = (recs: MarcFields[]): Candidate[] => recs.flatMap((r) => r.lcc); + +export function createResolver(deps: { + fetch: typeof fetch; cache: SourceCache; + locIntervalMs?: number; + sleep?: (ms: number) => Promise; +}): Resolver { + const ol = createOpenLibrary({ fetch: deps.fetch, cache: deps.cache }); + const loc = createLoc({ + fetch: deps.fetch, cache: deps.cache, + intervalMs: deps.locIntervalMs ?? 6000, + sleep: deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))), + }); + + async function resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise { + const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined; + let notified = false; + const notify = (m: BookMeta | null) => { + if (m && !notified) { notified = true; opts?.onMeta?.(m); } + }; + + // Open Library: edition first; the work search runs alongside and is awaited only when needed. + let edition: OlInfo | null = null; + let work: OlInfo | null = null; + let workP: Promise<{ v: OlInfo | null } | { e: unknown }> | null = null; + const getWork = async (required: boolean): Promise => { + if (!workP) return null; + const r = await workP; + if ('e' in r) { + if (required) throw r.e; + return null; + } + return r.v; + }; + if (isbn) { + workP = ol.work(isbn).then((v) => ({ v }), (e: unknown) => ({ e })); + edition = await ol.edition(isbn); + if (edition) notify(mergeMeta([edition.meta])); + else { work = await getWork(true); notify(mergeMeta([work?.meta])); } + } + + // Library of Congress: by LCCN when known, else by ISBN. + const lccn = input.lccn ?? edition?.meta.lccn; + let locRecs: MarcFields[] = []; + let exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn'; + if (lccn) { + locRecs = await loc.byLccn(lccn); + if (locRecs.length > 0) exactSource = 'loc-lccn'; + } + if (isbn && lccOf(locRecs).length === 0) { + const recs = await loc.byIsbn(isbn); + if (recs.length > 0) { locRecs = recs; exactSource = 'loc-isbn'; } + } + + const olEditionCands: Candidate[] = edition?.lcc ?? []; + const metaOf = (extra: Partials = []): BookMeta | null => + mergeMeta([edition?.meta, locRecs[0]?.meta, ...extra, input.title ? { title: input.title } : null]); + const forChoose = (m: BookMeta | null) => ({ + authors: m?.authors.length ? m.authors : input.author ? [input.author] : [], + title: m?.title ?? input.title ?? '', + year: m?.year ?? input.year, + }); + notify(metaOf()); + + // Tiers 1 and 2. + let chosen = chooseCallNumber( + { locExact: lccOf(locRecs), olEdition: olEditionCands, locTitle: [], olWork: [] }, + forChoose(metaOf()), exactSource, + ); + + // Tier 3: LoC by title and author. + let locTitleRecs: MarcFields[] = []; + if (!chosen) { + 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 ?? ''); + chosen = chooseCallNumber( + { locExact: [], olEdition: [], locTitle: lccOf(locTitleRecs), olWork: [] }, + forChoose(m), exactSource, + ); + } + } + + // Tier 4, and the work-level part of the metadata merge. + work ??= await getWork(!chosen); + // Without an ISBN or LCCN, the best title hit also supplies metadata. + const hitMeta = !isbn && !input.lccn ? locTitleRecs[0]?.meta : undefined; + const meta = metaOf([hitMeta, work?.meta]); + notify(meta); + chosen ??= chooseCallNumber( + { locExact: [], olEdition: [], locTitle: [], olWork: work?.lcc ?? [] }, + forChoose(meta), exactSource, + ); + + const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey + ?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null; + + if (chosen) { + return { + meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey, + confidence: chosen.confidence, source: chosen.source, dewey, reason: null, + }; + } + 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', + }; + } + + return { resolve, search: (title, author) => ol.search(title, author) }; +} diff --git a/src/server/sources/fixture-fetch.ts b/src/server/sources/fixture-fetch.ts new file mode 100644 index 0000000..7f20159 --- /dev/null +++ b/src/server/sources/fixture-fetch.ts @@ -0,0 +1,48 @@ +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; + +const DIR = join(import.meta.dirname, 'fixtures'); + +export interface FixtureFetch { + fetch: typeof fetch; + calls: string[]; + /** Calls whose host is a Library of Congress host. */ + locCalls(): string[]; + /** Serve this fixture for every LoC request instead of the matching one. */ + locOverride: string | null; +} + +function pick(u: URL, locOverride: string | null): string | null { + if (u.hostname === 'openlibrary.org') { + if (u.pathname === '/api/books') return `ol-data-${u.searchParams.get('bibkeys')!.replace('ISBN:', '')}.json`; + const isbn = u.searchParams.get('isbn'); + if (isbn) return `ol-search-${isbn}.json`; + return 'ol-title-search.json'; + } + if (locOverride) return locOverride; + if (u.hostname === 'lccn.loc.gov') return `loc-lccn-${u.pathname.split('/')[1]}.xml`; + const q = u.searchParams.get('query') ?? ''; + const m = /^bath\.isbn=(\d+)$/.exec(q); + if (m) return `loc-isbn-${m[1]}.xml`; + if (q.startsWith('bath.title=')) { + return /mythical/i.test(q) ? 'loc-title-mythical-brooks.xml' : 'loc-isbn-9780999999998.xml'; // zero records + } + return null; +} + +/** A fetch stub serving recorded fixtures and counting calls. Missing fixture -> 404. */ +export function fixtureFetch(): FixtureFetch { + const state: FixtureFetch = { + calls: [], locOverride: null, + locCalls() { return this.calls.filter((c) => /loc\.gov/.test(c)); }, + fetch: (async (input: string | URL | Request) => { + const url = String(input instanceof Request ? input.url : input); + state.calls.push(url); + const name = pick(new URL(url), state.locOverride); + const file = name ? join(DIR, name) : null; + if (!file || !existsSync(file)) return new Response('not found', { status: 404 }); + return new Response(readFileSync(file, 'utf8'), { status: 200 }); + }) as typeof fetch, + }; + return state; +} diff --git a/src/server/sources/fixtures/loc-block.html b/src/server/sources/fixtures/loc-block.html new file mode 100644 index 0000000..55faf0f --- /dev/null +++ b/src/server/sources/fixtures/loc-block.html @@ -0,0 +1,5 @@ + +Request Rejected +

Access Denied

+

Your client has made too many requests. Please slow down and try again later.

+ diff --git a/src/server/sources/fixtures/loc-isbn-9780201835953.xml b/src/server/sources/fixtures/loc-isbn-9780201835953.xml new file mode 100644 index 0000000..10e9866 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9780201835953.xml @@ -0,0 +1,104 @@ + +1.11marcxmlxml + 01291cam a2200337 a 4500 + 4434515 + 20250607165433.5 + 940906s1995 maua b 001 0 eng + + 4434515 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + pc19 to ja00 09-06-94; jf06 to subj 09-07-94; jf11 to sl 09-07-94; jf12 09-07-94 to ddc; CIP ver. pv08 08-25-95 + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150 + + + 94036653 + + + 0201835959 + + + 9780201835953 + + + (DLC) 94036653 + + + DLC + DLC + DLC + + + QA76.758 + .B75 1995 + + + 005.1/068 + 20 + + + Brooks, Frederick P. + (Frederick Phillips) + + + The mythical man-month : + essays on software engineering / + Frederick P. Brooks, Jr. + + + Anniversary ed. + + + Reading, Mass. : + Addison-Wesley Pub. Co., + 1995. + + + xiii, 322 p. : + ill. ; + 24 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Anniversary ed. has four new chapters. + + + Includes bibliographical references (p. 293-308) and index. + + + Software engineering. + + + c-GenColl + QA76.758 + .B75 1995 + 00014313394 + Copy 1 + BOOKS + +11.1bath.isbn=97802018359531xmlmarcxml diff --git a/src/server/sources/fixtures/loc-isbn-9780441172719.xml b/src/server/sources/fixtures/loc-isbn-9780441172719.xml new file mode 100644 index 0000000..1d7b5b6 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9780441172719.xml @@ -0,0 +1,2 @@ + +1.101.1bath.isbn=97804411727191xmlmarcxml diff --git a/src/server/sources/fixtures/loc-isbn-9780999999998.xml b/src/server/sources/fixtures/loc-isbn-9780999999998.xml new file mode 100644 index 0000000..cff7f11 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9780999999998.xml @@ -0,0 +1,2 @@ + +1.101.1bath.isbn=97809999999981xmlmarcxml diff --git a/src/server/sources/fixtures/loc-isbn-9781593278281.xml b/src/server/sources/fixtures/loc-isbn-9781593278281.xml new file mode 100644 index 0000000..d495bd0 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9781593278281.xml @@ -0,0 +1,146 @@ + +1.12marcxmlxml + 04541cam a2200421 i 4500 + 20417920 + 20250607085613.7 + 180326s2018 cau 001 0 eng + + 20417920 + + + 7 + cbc + orignew + 1 + ecip + 20 + y-gencatlg + + + acquire + 1 shelf copy + policy default + + + cf25 2018-03-26 + cf25 2018-03-28 to PSD (class./subj.) + td04 2018-04-19 to Dewey + xm09 2018-04-21 + xn11 2018-09-11 1 copy rec'd., to CIP ver. + rk20 2018-09-18 book received in ART + rl06 2019-05-03 to BCCD + ma02 2021-12-10 TW Situational + + + 2018014097 + + + 9781593278281 + paperback + + + 1593278284 + paperback + + + 9781593278519 (epub) + + + DLC + eng + DLC + rda + DLC + + + pcc + + + QA76.73.R87 + K53 2018 + + + 005.13/3 + 23 + + + COM051390 + COM051010 + COM051000 + bisacsh + + + Klabnik, Steve, + author. + + + The Rust programming language / + by Steve Klabnik and Carol Nichols ; with contributions from the Rust Community. + + + San Francisco : + No Starch Press, + [2018] + + + xxvii, 519 pages ; + 24 cm + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes index. + + + Machine generated contents note: Introduction -- Chapter 1:Getting Started -- Chapter 2: A Quick Tutorial---Guessing Game -- Chapter 3: Common Programming Concepts -- Chapter 4: Understanding Ownership -- Chapter 5: Structs -- Chapter 6: Enums and Pattern Matching -- Chapter 7: Modules -- Chapter 8: Common Collections -- Chapter 9: Error Handling -- Chapter 10: Generic Types, Traits, and Lifetimes -- Chapter 11: Testing -- Chapter 12: An Input/Output Project -- Chapter 13: Functional Language Features in Rust--Iterators and Closures -- Chapter 14: More about Cargo and Crates io -- Chapter 15: Smart Pointers -- Chapter 16: Concurrency -- Chapter 17: Is Rust Object Oriented? -- Chapter 18: Patterns -- Chapter 19: More About Lifetimes -- Chapter 20: Advanced Type System Features -- Appendix A: Keywords -- Appendix B: Operators -- Appendix C: Derivable Traits -- Appendix D: Nightly Rust\ -- Nightly Rust -- Glossary. + + + "The Rust Programming Language is the official book on Rust; a community-developed, systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. Rust's memory safety guarantees, enforced at compile time, safeguard your programs against the many problems that pervade other systems languages. Rust offers the control and performance of a low-level language with the helpful abstractions of a high level one, and does this all without having a garbage collector. These characteristics make Rust useful for embedding in other languages, programs with specific space and time requirements, and writing low-level code, like device drivers and operating systems. The Rust Programming Language begins with a quick hands-on project to introduce the basics, then explores key concepts in depth, such as ownership, the type system, error handling, and fearless concurrency. Detailed explanations of Rust-oriented takes on topics like pattern matching, iterators, and smart pointers combine with examples and exercises to take you from theory to practice. In addition to its thorough coverage of more granular topics, The Rust Programming Language will show you how to: -Grasp important concepts unique to Rust like ownership, borrowing, and lifetimes -Use Cargo, Rust's built-in package manager, to build your code, including downloading and building dependencies -Effectively use Rust's zero-cost abstractions and learn to build your own Developed with help from the community, The Rust Programming Language is your official guide to becoming a productive Rust programmer"-- + Provided by publisher. + + + "The official guide to Rust, a community-developed, systems programming language. Begins with a hands-on project to introduce the basics, then explores key concepts in depth"-- + Provided by publisher. + + + Rust (Computer programming language) + + + COMPUTERS / Programming / Open Source. + bisacsh + + + COMPUTERS / Programming Languages / General. + bisacsh + + + COMPUTERS / Programming / General. + bisacsh + + + Nichols, Carol, + 1983- + author. + + + Online version: + Klabnik, Steve, author. + Rust programming language + San Francisco : No Starch Press, Inc., 2018 + 9781593278519 + (DLC) 2018019844 + +121.1bath.isbn=97815932782811xmlmarcxml diff --git a/src/server/sources/fixtures/loc-lccn-88005934.xml b/src/server/sources/fixtures/loc-lccn-88005934.xml new file mode 100644 index 0000000..9f135a7 --- /dev/null +++ b/src/server/sources/fixtures/loc-lccn-88005934.xml @@ -0,0 +1,106 @@ + + 01137pam a2200349 a 4500 + 1491800 + 20250607021246.8 + 880303s1988 nju 001 0 eng + + 1491800 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 88005934 + + + 0131103709 + + + 0131103628 + pbk. + + + 9780131103702 + + + 9780131103627 + (pbk.) + + + (DLC) 88005934 + + + DLC + DLC + DLC + + + QA76.73.C15 + K47 1988 + + + 005.13/3 + 19 + + + Kernighan, Brian W. + + + The C programming language / + Brian W. Kernighan, Dennis M. Ritchie. + + + 2nd ed. + + + Englewood Cliffs, N.J. : + Prentice Hall, + c1988. + + + xii, 272 p. ; + 25 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes index. + + + C (Computer program language) + + + Ritchie, Dennis M., + 1941-2011. + + + c-GenColl + QA76.73.C15 + K47 1988 + 00001105991 + Copy 1 + BOOKS + + diff --git a/src/server/sources/fixtures/loc-lccn-94036653.xml b/src/server/sources/fixtures/loc-lccn-94036653.xml new file mode 100644 index 0000000..640d225 --- /dev/null +++ b/src/server/sources/fixtures/loc-lccn-94036653.xml @@ -0,0 +1,103 @@ + + 01291cam a2200337 a 4500 + 4434515 + 20250607165433.5 + 940906s1995 maua b 001 0 eng + + 4434515 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + pc19 to ja00 09-06-94; jf06 to subj 09-07-94; jf11 to sl 09-07-94; jf12 09-07-94 to ddc; CIP ver. pv08 08-25-95 + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150 + + + 94036653 + + + 0201835959 + + + 9780201835953 + + + (DLC) 94036653 + + + DLC + DLC + DLC + + + QA76.758 + .B75 1995 + + + 005.1/068 + 20 + + + Brooks, Frederick P. + (Frederick Phillips) + + + The mythical man-month : + essays on software engineering / + Frederick P. Brooks, Jr. + + + Anniversary ed. + + + Reading, Mass. : + Addison-Wesley Pub. Co., + 1995. + + + xiii, 322 p. : + ill. ; + 24 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Anniversary ed. has four new chapters. + + + Includes bibliographical references (p. 293-308) and index. + + + Software engineering. + + + c-GenColl + QA76.758 + .B75 1995 + 00014313394 + Copy 1 + BOOKS + + diff --git a/src/server/sources/fixtures/loc-title-mythical-brooks.xml b/src/server/sources/fixtures/loc-title-mythical-brooks.xml new file mode 100644 index 0000000..f94f77e --- /dev/null +++ b/src/server/sources/fixtures/loc-title-mythical-brooks.xml @@ -0,0 +1,204 @@ + +1.12marcxmlxml + 01291cam a2200337 a 4500 + 4434515 + 20250607165433.5 + 940906s1995 maua b 001 0 eng + + 4434515 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + pc19 to ja00 09-06-94; jf06 to subj 09-07-94; jf11 to sl 09-07-94; jf12 09-07-94 to ddc; CIP ver. pv08 08-25-95 + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150 + + + 94036653 + + + 0201835959 + + + 9780201835953 + + + (DLC) 94036653 + + + DLC + DLC + DLC + + + QA76.758 + .B75 1995 + + + 005.1/068 + 20 + + + Brooks, Frederick P. + (Frederick Phillips) + + + The mythical man-month : + essays on software engineering / + Frederick P. Brooks, Jr. + + + Anniversary ed. + + + Reading, Mass. : + Addison-Wesley Pub. Co., + 1995. + + + xiii, 322 p. : + ill. ; + 24 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Anniversary ed. has four new chapters. + + + Includes bibliographical references (p. 293-308) and index. + + + Software engineering. + + + c-GenColl + QA76.758 + .B75 1995 + 00014313394 + Copy 1 + BOOKS + +1marcxmlxml + 01102cam a2200313 i 4500 + 1260235 + 20250606191429.1 + 750318s1975 maua b 001 0 eng + + 1260235 + + + 7 + cbc + orignew + 2 + ocip + 19 + y-gencatlg + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 74004714 + + + 0201006502 + + + 9780201006506 + + + (DLC) 74004714 + + + DLC + DLC + ICU + DLC + + + QA76.6 + .B75 + + + 001.6/425 + + + Brooks, Frederick P. + (Frederick Phillips) + + + The mythical man-month : + essays on software engineering / + Frederick P. Brooks, Jr. + + + Reading, Mass. : + Addison-Wesley Pub. Co., + [1975] + + + xi, 195 p. : + ill. ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes bibliographical references and index. + + + Software engineering. + + + c-GenColl + QA76.6 + .B75 + Copy 1 + BOOKS + + + c-GenColl + QA76.6 + .B75 + 00019520614 + Copy 2 + CCF + +21.1bath.title="mythical man-month" and bath.author="brooks"5xmlmarcxml diff --git a/src/server/sources/fixtures/ol-data-9780201835953.json b/src/server/sources/fixtures/ol-data-9780201835953.json new file mode 100644 index 0000000..0d038fa --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9780201835953.json @@ -0,0 +1 @@ +{"ISBN:9780201835953": {"url": "http://openlibrary.org/books/OL1110870M/The_Mythical_Man-Month", "key": "/books/OL1110870M", "title": "The Mythical Man-Month", "subtitle": "Essays on Software Engineering", "authors": [{"url": "http://openlibrary.org/authors/OL587176A/Frederick_P._Brooks", "name": "Frederick P. Brooks"}], "number_of_pages": 322, "pagination": "xiii, 322 p. :", "by_statement": "Frederick P. Brooks, Jr.", "identifiers": {"goodreads": ["13629"], "librarything": ["646897"], "isbn_10": ["0201835959"], "isbn_13": ["9780201835953"], "lccn": ["94036653"], "oclc": ["31166617"], "openlibrary": ["OL1110870M"]}, "classifications": {"lc_classifications": ["QA76.758 .B75 1995", "QA76.758.B75 1995"], "dewey_decimal_class": ["005.1/068"]}, "publishers": [{"name": "Addison-Wesley Professional"}], "publish_places": [{"name": "Reading, Mass"}], "publish_date": "1995", "subjects": [{"name": "Computer programming management", "url": "https://openlibrary.org/subjects/computer_programming_management"}, {"name": "Addresses, essays, lectures", "url": "https://openlibrary.org/subjects/addresses,_essays,_lectures"}, {"name": "Software engineering", "url": "https://openlibrary.org/subjects/software_engineering"}, {"name": "Electronic digital computers", "url": "https://openlibrary.org/subjects/electronic_digital_computers"}, {"name": "Programming", "url": "https://openlibrary.org/subjects/programming"}, {"name": "Computer programming", "url": "https://openlibrary.org/subjects/computer_programming"}, {"name": "MULTICS", "url": "https://openlibrary.org/subjects/multics"}, {"name": "Technologie logiciel", "url": "https://openlibrary.org/subjects/technologie_logiciel"}, {"name": "Gestion projet", "url": "https://openlibrary.org/subjects/gestion_projet"}, {"name": "Programmation (Informatique)", "url": "https://openlibrary.org/subjects/programmation_(informatique)"}, {"name": "Gestion", "url": "https://openlibrary.org/subjects/gestion"}, {"name": "Syst\u00e8me exploitation 360", "url": "https://openlibrary.org/subjects/syst\u00e8me_exploitation_360"}, {"name": "IBM 360", "url": "https://openlibrary.org/subjects/ibm_360"}, {"name": "Management", "url": "https://openlibrary.org/subjects/management"}, {"name": "Computer programming--management", "url": "https://openlibrary.org/subjects/computer_programming--management"}, {"name": "Information technology projects", "url": "https://openlibrary.org/subjects/information_technology_projects"}], "subject_places": [{"name": "La Brea", "url": "https://openlibrary.org/subjects/place:la_brea"}, {"name": "California", "url": "https://openlibrary.org/subjects/place:california"}], "subject_people": [{"name": "Frederick P. Brooks", "url": "https://openlibrary.org/subjects/person:frederick_p._brooks"}, {"name": "David Parnas", "url": "https://openlibrary.org/subjects/person:david_parnas"}], "subject_times": [{"name": "1960s", "url": "https://openlibrary.org/subjects/time:1960s"}, {"name": "1970s", "url": "https://openlibrary.org/subjects/time:1970s"}], "notes": "Includes bibliographical references (p. 293-308) and index.\r\nAnniversary ed. has four new chapters.", "ebooks": [{"preview_url": "https://archive.org/details/mythicalmonth00broo", "availability": "restricted", "formats": {}}], "cover": {"small": "https://covers.openlibrary.org/b/id/10653425-S.jpg", "medium": "https://covers.openlibrary.org/b/id/10653425-M.jpg", "large": "https://covers.openlibrary.org/b/id/10653425-L.jpg"}}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-data-9780441172719.json b/src/server/sources/fixtures/ol-data-9780441172719.json new file mode 100644 index 0000000..272e88e --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9780441172719.json @@ -0,0 +1 @@ +{"ISBN:9780441172719": {"url": "http://openlibrary.org/books/OL59726263M/Dune", "key": "/books/OL59726263M", "title": "Dune", "authors": [{"url": "http://openlibrary.org/authors/OL79034A/Frank_Herbert", "name": "Frank Herbert"}], "number_of_pages": 896, "pagination": "884p.", "weight": "479 grams", "identifiers": {"isbn_13": ["9780441172719"], "openlibrary": ["OL59726263M"]}, "publishers": [{"name": "Ace"}], "publish_places": [{"name": "New York, USA"}], "publish_date": "2020", "subjects": [{"name": "Dune (Imaginary place)", "url": "https://openlibrary.org/subjects/dune_(imaginary_place)"}, {"name": "Fiction", "url": "https://openlibrary.org/subjects/fiction"}, {"name": "Fiction, science fiction, general", "url": "https://openlibrary.org/subjects/fiction,_science_fiction,_general"}, {"name": "Dune (imaginary place), fiction", "url": "https://openlibrary.org/subjects/dune_(imaginary_place),_fiction"}, {"name": "New York Times reviewed", "url": "https://openlibrary.org/subjects/new_york_times_reviewed"}, {"name": "Science fiction", "url": "https://openlibrary.org/subjects/science_fiction"}, {"name": "Science-fiction", "url": "https://openlibrary.org/subjects/science-fiction"}, {"name": "American literature", "url": "https://openlibrary.org/subjects/american_literature"}, {"name": "nyt:mass-market-monthly=2021-11-07", "url": "https://openlibrary.org/subjects/nyt:mass-market-monthly=2021-11-07"}, {"name": "New York Times bestseller", "url": "https://openlibrary.org/subjects/new_york_times_bestseller"}, {"name": "award:nebula_award=novel", "url": "https://openlibrary.org/subjects/award:nebula_award=novel"}, {"name": "nyt:trade-fiction-paperback=2021-11-07", "url": "https://openlibrary.org/subjects/nyt:trade-fiction-paperback=2021-11-07"}, {"name": "Hugo Award Winner", "url": "https://openlibrary.org/subjects/hugo_award_winner"}, {"name": "award:hugo_award=1966", "url": "https://openlibrary.org/subjects/award:hugo_award=1966"}, {"name": "award:hugo_award=novel", "url": "https://openlibrary.org/subjects/award:hugo_award=novel"}, {"name": "American Science fiction", "url": "https://openlibrary.org/subjects/american_science_fiction"}, {"name": "Long Now Manual for Civilization", "url": "https://openlibrary.org/subjects/long_now_manual_for_civilization"}, {"name": "Ecology", "url": "https://openlibrary.org/subjects/ecology"}, {"name": "Fantasy fiction", "url": "https://openlibrary.org/subjects/fantasy_fiction"}, {"name": "Large type books", "url": "https://openlibrary.org/subjects/large_type_books"}], "excerpts": [{"text": "In the week before their departure to Arrakis, when all the final scurrying about had reached a nearly unbearable frenzy, an old crone came to visit the mother of the boy, Paul.", "comment": "", "first_sentence": true}], "table_of_contents": [{"level": 0, "label": "BOOK I Dune", "title": "1", "pagenum": ""}, {"level": 0, "label": "BOOK II MUAD'DIB", "title": "325", "pagenum": ""}, {"level": 0, "label": "BOOK III THE PROPHET", "title": "589", "pagenum": ""}, {"level": 0, "label": "APPENDIX I: The Ecology of Dune", "title": "797", "pagenum": ""}, {"level": 0, "label": "APPENDIX II: The Religion of Dune", "title": "811", "pagenum": ""}, {"level": 0, "label": "APPENDIX III: Report on Bene Gesserit Motives and Purposes", "title": "825", "pagenum": ""}, {"level": 0, "label": "APPENDIX IV: The Almanak en-Ashraf (Selected Excerpts of the Noble Houses)", "title": "829", "pagenum": ""}, {"level": 0, "label": "Terminology of the Imperium", "title": "833", "pagenum": ""}, {"level": 0, "label": "Cartographic Notes", "title": "865", "pagenum": ""}, {"level": 0, "label": "Map", "title": "866", "pagenum": ""}, {"level": 0, "label": "Afterword by Brian Herbert", "title": "868", "pagenum": ""}], "links": [{"title": "New York Times review", "url": "http://www.nytimes.com/1999/11/28/books/science-fiction.html"}, {"title": "New York Times review", "url": "https://www.nytimes.com/1985/01/06/books/paperback-best-sellers-jan-6-1985fiction-1.html"}, {"title": "Official page on brazilian publisher's website", "url": "https://aleph.com.br/collections/ficcao/products/duna-1"}, {"title": "\u041a\u043d\u0438\u0433\u0430 \u043d\u0430 \u0441\u0430\u0439\u0442\u0456 \u0432\u0438\u0434\u0430\u0432\u043d\u0438\u0446\u0442\u0432\u0430", "url": "https://bookclub.ua/catalog/books/fantastic_books/dyuna"}, {"title": "Official page on brazilian publisher's website", "url": "https://aleph.com.br/collections/ficcao/products/duna"}, {"title": "Official page on brazilian publisher's website", "url": "https://aleph.com.br/collections/ficcao/products/duna-com-sobrecapa-edicao-limitada"}], "cover": {"small": "https://covers.openlibrary.org/b/id/15110282-S.jpg", "medium": "https://covers.openlibrary.org/b/id/15110282-M.jpg", "large": "https://covers.openlibrary.org/b/id/15110282-L.jpg"}}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-data-9780999999998.json b/src/server/sources/fixtures/ol-data-9780999999998.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9780999999998.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-data-9781593278281.json b/src/server/sources/fixtures/ol-data-9781593278281.json new file mode 100644 index 0000000..b96703f --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9781593278281.json @@ -0,0 +1 @@ +{"ISBN:9781593278281": {"url": "http://openlibrary.org/books/OL26740375M/The_Rust_Programming_Language", "key": "/books/OL26740375M", "title": "The Rust Programming Language", "authors": [{"url": "http://openlibrary.org/authors/OL7467124A/Steve_Klabnik", "name": "Steve Klabnik"}, {"url": "http://openlibrary.org/authors/OL7467125A/Carol_Nichols", "name": "Carol Nichols"}, {"url": "http://openlibrary.org/authors/OL1438683A/Carol_Nichols", "name": "Carol Nichols"}], "identifiers": {"isbn_13": ["9781593278281"], "openlibrary": ["OL26740375M"]}, "classifications": {"lc_classifications": ["QA76.73"]}, "publishers": [{"name": "No Starch Press"}], "publish_date": "2018", "subjects": [{"name": "Rust (Computer programming language)", "url": "https://openlibrary.org/subjects/rust_(computer_programming_language)"}, {"name": "Computer programming", "url": "https://openlibrary.org/subjects/computer_programming"}, {"name": "Programming languages (electronic computers)", "url": "https://openlibrary.org/subjects/programming_languages_(electronic_computers)"}], "cover": {"small": "https://covers.openlibrary.org/b/id/8508621-S.jpg", "medium": "https://covers.openlibrary.org/b/id/8508621-M.jpg", "large": "https://covers.openlibrary.org/b/id/8508621-L.jpg"}}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9780201835953.json b/src/server/sources/fixtures/ol-search-9780201835953.json new file mode 100644 index 0000000..8fed829 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9780201835953.json @@ -0,0 +1 @@ +{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Frederick P. Brooks"],"ddc":["005.1068","001.6425"],"first_publish_year":1974,"key":"/works/OL3510570W","lcc":["QA-0076.75800000.B75 1995","QA-0076.60000000.B75"],"lccn":["94036653","74004714"],"publisher":["Addison-Wesley Pub. Co.","Addison-Wesley Pub. Co","Pearson Education, Limited","Ren min you dian chu ban she","Addison-Wesley Professional","Addison-Wesley","Addison Wesley","Dept. of Computer Science, University of North Carolina at Chapel Hill","Addison-Wesley Publishing Company"],"title":"The Mythical Man-Month","subject":["Computer programming management","Addresses, essays, lectures","Software engineering","Electronic digital computers","Programming","Computer programming","MULTICS","Technologie logiciel","Gestion projet","Programmation (Informatique)","Gestion","Système exploitation 360","IBM 360","Management","Computer programming--management","Information technology projects"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9780441172719.json b/src/server/sources/fixtures/ol-search-9780441172719.json new file mode 100644 index 0000000..ef0ed0a --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9780441172719.json @@ -0,0 +1 @@ +{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Frank Herbert"],"ddc":["813.54","813"],"first_publish_year":1965,"key":"/works/OL893414W","lcc":["PS-3558.00000000.E63 D8 1965","PS-3558.00000000.E63 D8 1977","PS-3558.00000000.E63 D8 2016","PS-3558.00000000.E63 D8 1978","PS-3558.00000000.E63D8 2005","PS-3558.00000000.E63 .D8 1984","PS-3558.00000000.E63D8 1984","PS-3558.00000000.E63D8 2016","PS-3558.00000000.E63","PS-3558.00000000.E63 D817 2003","PZ-0004.00000000.H538 Du","PS-3558.00000000.E63 D8 1984B","PS-3558.00000000.E63 D8 2005","PS-3558.00000000.E63 D8 1984","PZ-0004.00000000.H5356 Dt","PS-3558.00000000.E63 Dt","PS-3558.00000000.E63 D8 1999","PS-3558.00000000.E63 D8 2015"],"lccn":["2014044556","83016030","2006274831","2016030436","65022547","99462492"],"publisher":["Robert Laffont","Acervo","Wilhelm Heyne Verlag","AST","Putnam","Hodder & Stoughton Ltd","Клуб Сімейного Дозвілля","Penguin Classics","Heyne","NEL / New English Library","Orion Publishing Group, Limited","Heyne Verlag","Borders","Phantom Press International","Dom wydawniczy Rebis","Recorded Books Inc","P&J","Putnam Adult","Anubis","Books on Tape, Inc.","Penguin Random House Grupo Editorial","Perfection Learning","Penguin Publishing Group","Books onTape, inc.","Nha Nam - Hoi Nha Van","Editora Aleph","Hodder Paperback","DEBOLSILLO","Turtleback Books","Ace Books","Ace","Orion Pub Co","POCKET","Fanucci","Nova","Brand: Acervo","Hodder and Stoughton","Pocket","Meulenhoff","Penguin USA, Inc.","Hodder & Stoughton General Division","ROBERT LAFFONT","Chilton","Debolsillo","The Berkley Publishing Group","MAIMÉS","Hodder & Stoughton","Ace Books, Inc.","Nemira Publishing House","Paw Prints 2008-06-26","New English Library Ltd","Recorded Books","Kabalci Yayinevi","Brand: Turtleback","Chilton Book Company","Perigee Trade","Penguin Proprietary","Turtleback Books Distributed by Demco Media","Macmillan Audio","Εκδόσεις Anubis","Plaza & Janes Editores, S.A.","Berkley T2706","Barnes & Noble","ʻAm-ʻoved","Mai Més","Books on Tape, inc.","Ithaki Yayinlari","Littlehampton Book Services Ltd","Berkley","Sound Library","Brand: Books on Tape, Inc.","Rebis","Presse Poket","Gollancz","Tandem Library","Dom Wydawniczy REBIS Sp. z o.o.","Hodder","Raig Verd Editorial","Gollancz Paperback","Caedmon","New English Library","Hodder Paperbacks","Berkley Books","Berkley Trade","Chilton Books","Aleph","Audio Renaissance","Ace Trade","Penguin Random House Grupo Editorial (USA) LLC","Hodderscape","Thorndike Press","Recorded Books, LLC"],"title":"Dune","subject":["Dune (Imaginary place)","Fiction","Fiction, science fiction, general","Dune (imaginary place), fiction","New York Times reviewed","Science fiction","Science-fiction","American literature","nyt:mass-market-monthly=2021-11-07","New York Times bestseller","award:nebula_award=novel","nyt:trade-fiction-paperback=2021-11-07","Hugo Award Winner","award:hugo_award=1966","award:hugo_award=novel","American Science fiction","Long Now Manual for Civilization","Ecology","Fantasy fiction","Large type books"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9780999999998.json b/src/server/sources/fixtures/ol-search-9780999999998.json new file mode 100644 index 0000000..4b6de02 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9780999999998.json @@ -0,0 +1 @@ +{"numFound":0,"start":0,"numFoundExact":true,"num_found":0,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9781593278281.json b/src/server/sources/fixtures/ol-search-9781593278281.json new file mode 100644 index 0000000..2bfe7a4 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9781593278281.json @@ -0,0 +1 @@ +{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Steve Klabnik","Carol Nichols","Carol Nichols"],"first_publish_year":2018,"key":"/works/OL19080231W","lcc":["QA-0076.73000000"],"publisher":["No Starch Press, Incorporated","No Starch Press"],"title":"The Rust Programming Language","subject":["Rust (Computer programming language)","Computer programming","Programming languages (electronic computers)"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-title-search.json b/src/server/sources/fixtures/ol-title-search.json new file mode 100644 index 0000000..8fed829 --- /dev/null +++ b/src/server/sources/fixtures/ol-title-search.json @@ -0,0 +1 @@ +{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Frederick P. Brooks"],"ddc":["005.1068","001.6425"],"first_publish_year":1974,"key":"/works/OL3510570W","lcc":["QA-0076.75800000.B75 1995","QA-0076.60000000.B75"],"lccn":["94036653","74004714"],"publisher":["Addison-Wesley Pub. Co.","Addison-Wesley Pub. Co","Pearson Education, Limited","Ren min you dian chu ban she","Addison-Wesley Professional","Addison-Wesley","Addison Wesley","Dept. of Computer Science, University of North Carolina at Chapel Hill","Addison-Wesley Publishing Company"],"title":"The Mythical Man-Month","subject":["Computer programming management","Addresses, essays, lectures","Software engineering","Electronic digital computers","Programming","Computer programming","MULTICS","Technologie logiciel","Gestion projet","Programmation (Informatique)","Gestion","Système exploitation 360","IBM 360","Management","Computer programming--management","Information technology projects"]}]} \ No newline at end of file diff --git a/src/server/sources/http.ts b/src/server/sources/http.ts new file mode 100644 index 0000000..7ae7e8d --- /dev/null +++ b/src/server/sources/http.ts @@ -0,0 +1,29 @@ +export class TemporaryError extends Error {} + +export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void } + +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 { + let res: Response; + try { + res = await f(url, { headers: { 'User-Agent': USER_AGENT } }); + } catch (e) { + 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}`); + let body: string; + try { + body = await res.text(); + } catch (e) { + throw new TemporaryError(`Network error reading ${url}: ${(e as Error).message}`); + } + return { status: res.status, body }; +} + +export function trimPunct(s: string): string { + return s.replace(/[\s\/,:;.]+$/, '').trim(); +} diff --git a/src/server/sources/loc.ts b/src/server/sources/loc.ts new file mode 100644 index 0000000..07b922b --- /dev/null +++ b/src/server/sources/loc.ts @@ -0,0 +1,91 @@ +import { mainEntry } from '../../shared/cutter.ts'; +import { getText, TemporaryError } from './http.ts'; +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']; +const MAX_INTERVAL_MS = 60_000; + +export function isLocXml(body: string): boolean { + return body.includes('searchRetrieveResponse') || body.includes('; + byLccn(lccn: string): Promise; + byTitle(title: string, author: string): Promise; +} + +export function createLoc(deps: { + fetch: typeof fetch; cache: SourceCache; intervalMs: number; sleep: (ms: number) => Promise; +}): Loc { + const baseInterval = deps.intervalMs; + let interval = baseInterval; + let lastSlot: number | null = null; + + /** Reserve the next request slot synchronously so concurrent callers are spaced too. */ + async function throttle(): Promise { + const now = Date.now(); + const slot = lastSlot === null ? now : Math.max(now, lastSlot + interval); + lastSlot = slot; + if (slot > now) await deps.sleep(slot - now); + } + + function blocked(): never { + interval = Math.min(interval * 2, MAX_INTERVAL_MS); + lastSlot = Date.now(); + throw new TemporaryError('Library of Congress returned a block page'); + } + + function ok(): void { + if (interval > baseInterval) interval = Math.max(baseInterval, interval / 2); + } + + async function sru(cacheKey: string, query: string, max: number): Promise { + const hit = deps.cache.get(cacheKey); + if (hit !== null) return parseMarcXml(hit); + const qs = new URLSearchParams({ + version: '1.1', operation: 'searchRetrieve', query, + maximumRecords: String(max), recordSchema: 'marcxml', + }); + let body: string | null = null; + let lastErr: unknown; + for (const base of SRU_URLS) { + await throttle(); + try { + body = (await getText(deps.fetch, `${base}?${qs}`)).body; + break; + } catch (e) { + lastErr = e; + } + } + if (body === null) throw lastErr; + if (!isLocXml(body)) blocked(); + ok(); + deps.cache.set(cacheKey, body); + return parseMarcXml(body); + } + + return { + byIsbn: (isbn) => sru(`loc-isbn:${isbn}`, `bath.isbn=${isbn}`, 1), + async byLccn(lccn) { + const key = `loc-lccn:${lccn}`; + const hit = deps.cache.get(key); + if (hit !== null) return parseMarcXml(hit); + await throttle(); + const res = await getText(deps.fetch, `https://lccn.loc.gov/${encodeURIComponent(lccn)}/marcxml`); + if (res.status === 404) return []; + if (res.status >= 400 || !isLocXml(res.body)) blocked(); + ok(); + deps.cache.set(key, res.body); + return parseMarcXml(res.body); + }, + byTitle(title, author) { + const t = title.replace(/"/g, ' ').trim(); + const surname = author ? mainEntry([author], title).replace(/"/g, ' ').trim() : ''; + const query = surname ? `bath.title="${t}" and bath.author="${surname}"` : `bath.title="${t}"`; + return sru(`loc-title:${title}|${author}`, query, 5); + }, + }; +} diff --git a/src/server/sources/marc.test.ts b/src/server/sources/marc.test.ts new file mode 100644 index 0000000..7ee87ec --- /dev/null +++ b/src/server/sources/marc.test.ts @@ -0,0 +1,46 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseMarcXml } from './marc.ts'; + +const fx = (n: string) => readFileSync(join(import.meta.dirname, 'fixtures', n), 'utf8'); + +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.equal(r!.meta.year, 2018); + assert.ok(r!.lccn); +}); + +test('bare permalink record', () => { + const [r] = parseMarcXml(fx('loc-lccn-88005934.xml')); + assert.deepEqual(r!.lcc, [{ raw: 'QA76.73.C15 K47 1988', complete: true }]); + assert.equal(r!.lccn, '88005934'); +}); + +test('zero records', () => { + assert.deepEqual(parseMarcXml(fx('loc-isbn-9780999999998.xml')), []); +}); + +test('single datafield/subfield objects, several 050s, other prefixes, 082, 264', () => { + const xml = ` + PS3558.E63 + PZ3.H4186Du + 813/.54 + Dune / + Ace,2005. + `; + const [r] = parseMarcXml(xml); + assert.deepEqual(r!.lcc, [{ raw: 'PS3558.E63', complete: false }, { raw: 'PZ3.H4186 Du', complete: true }]); + assert.equal(r!.dewey, '813.54'); + assert.equal(r!.meta.title, 'Dune'); + assert.equal(r!.meta.publisher, 'Ace'); + assert.equal(r!.meta.year, 2005); +}); + +test('garbage is no records', () => { + assert.deepEqual(parseMarcXml('nope'), []); +}); diff --git a/src/server/sources/marc.ts b/src/server/sources/marc.ts new file mode 100644 index 0000000..40fb1ff --- /dev/null +++ b/src/server/sources/marc.ts @@ -0,0 +1,110 @@ +import { XMLParser } from 'fast-xml-parser'; +import type { BookMeta, Candidate } from '../../shared/types.ts'; +import { trimPunct } from './http.ts'; + +export interface MarcFields { + lccn: string | null; + lcc: Candidate[]; + dewey: string | null; + meta: Partial; +} + +type Node = Record; + +const ARRAYS = new Set(['record', 'datafield', 'subfield', 'controlfield']); + +const parser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + removeNSPrefix: true, + parseTagValue: false, + parseAttributeValue: false, + trimValues: true, + isArray: (name) => ARRAYS.has(name), +}); + +function isNode(v: unknown): v is Node { return typeof v === 'object' && v !== null; } +function asArray(v: T | T[] | undefined | null): T[] { return v == null ? [] : Array.isArray(v) ? v : [v]; } + +/** Find MARC records anywhere in the tree: SRU wrapper, bare record, or collection. */ +function findRecords(node: unknown, out: Node[]): void { + if (Array.isArray(node)) { for (const n of node) findRecords(n, out); return; } + if (!isNode(node)) return; + if ('datafield' in node || 'leader' in node) { out.push(node); return; } + for (const k of Object.keys(node)) if (!k.startsWith('@_')) findRecords(node[k], out); +} + +function text(v: unknown): string { + if (typeof v === 'string') return v; + if (typeof v === 'number') return String(v); + if (isNode(v)) return typeof v['#text'] === 'string' ? (v['#text'] as string) : ''; + return ''; +} + +interface Field { tag: string; ind2: string; subs: { code: string; value: string }[] } + +function fieldsOf(rec: Node): Field[] { + return asArray(rec['datafield'] as Node | Node[] | undefined).filter(isNode).map((d) => ({ + tag: String(d['@_tag'] ?? ''), + ind2: String(d['@_ind2'] ?? ' '), + subs: asArray(d['subfield'] as unknown).map((s) => ({ + code: isNode(s) ? String(s['@_code'] ?? '') : '', + value: text(s).trim(), + })), + })); +} + +function sub(f: Field, code: string): string { + return f.subs.find((s) => s.code === code && s.value)?.value ?? ''; +} + +function uniq(a: string[]): string[] { return [...new Set(a)]; } + +export function parseMarcRecord(rec: Node): MarcFields { + const fields = fieldsOf(rec); + const all = (tag: string) => fields.filter((f) => f.tag === tag); + + const lcc: Candidate[] = []; + for (const f of all('050')) { + const a = sub(f, 'a'); + if (!a) continue; + const b = sub(f, 'b'); + lcc.push(b ? { raw: `${a} ${b}`, complete: true } : { raw: a, complete: false }); + } + + const d082 = all('082')[0]; + const dewey = d082 && sub(d082, 'a') ? sub(d082, 'a').replace(/\//g, '') : null; + + const f245 = all('245')[0]; + 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 pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0]; + const publisher = pub ? trimPunct(sub(pub, 'b')) : ''; + const ym = pub ? /\b(1[0-9]\d\d|20\d\d)\b/.exec(sub(pub, 'c')) : null; + + const subjects = uniq(all('650').map((f) => trimPunct(sub(f, 'a'))).filter(Boolean)); + const f010 = all('010')[0]; + const lccn = f010 && sub(f010, 'a') ? sub(f010, 'a').replace(/\s+/g, '') : null; + + const meta: Partial = { authors, subjects }; + if (title) meta.title = title; + if (subtitle) meta.subtitle = subtitle; + if (publisher) meta.publisher = publisher; + if (ym) meta.year = Number(ym[1]); + if (lccn) meta.lccn = lccn; + return { lccn, lcc, dewey, meta }; +} + +/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */ +export function parseMarcXml(xml: string): MarcFields[] { + let tree: unknown; + try { tree = parser.parse(xml); } catch { return []; } + const recs: Node[] = []; + findRecords(tree, recs); + return recs.map(parseMarcRecord); +} diff --git a/src/server/sources/openlibrary.ts b/src/server/sources/openlibrary.ts new file mode 100644 index 0000000..f9ccc82 --- /dev/null +++ b/src/server/sources/openlibrary.ts @@ -0,0 +1,135 @@ +import type { BookMeta, Candidate, SearchResult } from '../../shared/types.ts'; +import { formatCallNumber, parseCallNumber } from '../../shared/callnumber.ts'; +import { getText, trimPunct, TemporaryError } from './http.ts'; +import type { SourceCache } from './http.ts'; + +export interface OlInfo { + meta: Partial; + lcc: Candidate[]; + dewey: string | null; +} + +const FIELDS = 'key,title,author_name,first_publish_year,publisher,ddc,lcc,lccn,subject'; + +function obj(v: unknown): Record | null { + return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record) : null; +} +function strs(v: unknown): string[] { + return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && x.trim() !== '').map((s) => s.trim()) : []; +} +function names(v: unknown): string[] { + return Array.isArray(v) + ? v.map((x) => (obj(x)?.['name'])).filter((x): x is string => typeof x === 'string' && x.trim() !== '').map((s) => s.trim()) + : []; +} +function uniq(a: string[]): string[] { return [...new Set(a)]; } +function yearOf(s: unknown): number | undefined { + const m = typeof s === 'string' ? /\b(1[0-9]\d\d|20\d\d)\b/.exec(s) : null; + return m ? Number(m[1]) : undefined; +} + +function parseJson(body: string): unknown { + try { return JSON.parse(body); } catch { throw new TemporaryError('Open Library returned invalid JSON'); } +} + +/** Parse the api/books response; null when the ISBN is unknown ({}). */ +export function parseEdition(body: string, isbn: string): OlInfo | null { + const root = obj(parseJson(body)); + const rec = obj(root?.[`ISBN:${isbn}`]); + if (!rec) return null; + const cls = obj(rec['classifications']); + const ids = obj(rec['identifiers']); + const meta: Partial = { + authors: uniq(names(rec['authors'])), + subjects: uniq(names(rec['subjects'])), + }; + if (typeof rec['title'] === 'string' && rec['title'].trim()) meta.title = rec['title'].trim(); + if (typeof rec['subtitle'] === 'string' && rec['subtitle'].trim()) meta.subtitle = rec['subtitle'].trim(); + const pub = names(rec['publishers'])[0]; + if (pub) meta.publisher = trimPunct(pub); + const y = yearOf(rec['publish_date']); + if (y) meta.year = y; + const lccn = strs(ids?.['lccn'])[0]; + if (lccn) meta.lccn = lccn.replace(/\s+/g, ''); + return { + meta, + lcc: strs(cls?.['lc_classifications']).map((raw) => ({ raw })), + dewey: strs(cls?.['dewey_decimal_class'])[0] ?? null, + }; +} + +function docs(body: string): Record[] { + const root = obj(parseJson(body)); + const d = root?.['docs']; + return Array.isArray(d) ? d.map(obj).filter((x): x is Record => x !== null) : []; +} + +/** Parse the work-level search by ISBN; null when no doc. */ +export function parseWork(body: string): OlInfo | null { + const d = docs(body)[0]; + if (!d) return null; + const meta: Partial = { authors: uniq(strs(d['author_name'])), subjects: uniq(strs(d['subject'])) }; + if (typeof d['title'] === 'string' && d['title'].trim()) meta.title = d['title'].trim(); + const pub = strs(d['publisher'])[0]; + if (pub) meta.publisher = trimPunct(pub); + if (typeof d['first_publish_year'] === 'number') meta.year = d['first_publish_year']; + const lccn = strs(d['lccn'])[0]; + if (lccn) meta.lccn = lccn.replace(/\s+/g, ''); + return { meta, lcc: strs(d['lcc']).map((raw) => ({ raw })), dewey: strs(d['ddc'])[0] ?? null }; +} + +export function parseSearch(body: string): SearchResult[] { + return docs(body).flatMap((d) => { + if (typeof d['title'] !== 'string' || !d['title'].trim()) return []; + const r: SearchResult = { + title: d['title'].trim(), + authors: uniq(strs(d['author_name'])), + lcc: uniq(strs(d['lcc']).map((raw) => { const cn = parseCallNumber(raw); return cn ? formatCallNumber(cn) : raw; })), + }; + if (typeof d['first_publish_year'] === 'number') r.year = d['first_publish_year']; + const pub = strs(d['publisher'])[0]; + if (pub) r.publisher = trimPunct(pub); + const lccn = strs(d['lccn'])[0]; + if (lccn) r.lccn = lccn.replace(/\s+/g, ''); + return [r]; + }); +} + +export interface OpenLibrary { + edition(isbn: string): Promise; + work(isbn: string): Promise; + search(title: string, author: string): Promise; +} + +export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCache }): OpenLibrary { + async function body(key: string | null, url: string): Promise { + if (key) { + const hit = deps.cache.get(key); + if (hit !== null) return hit; + } + const res = await getText(deps.fetch, url); + // 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); + 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); + }, + async work(isbn) { + const url = `https://openlibrary.org/search.json?isbn=${isbn}&fields=${FIELDS}`; + return parseWork(await body(`ol-search:${isbn}`, url)); + }, + async search(title, author) { + const q = new URLSearchParams(); + if (title) q.set('title', title); + if (author) q.set('author', author); + q.set('limit', '10'); + q.set('fields', FIELDS); + return parseSearch(await body(null, `https://openlibrary.org/search.json?${q}`)); + }, + }; +} diff --git a/src/web/api.ts b/src/web/api.ts new file mode 100644 index 0000000..90c8e65 --- /dev/null +++ b/src/web/api.ts @@ -0,0 +1,64 @@ +import type { Book, SearchResult, Settings } from '../shared/types.ts'; + +export class ApiError extends Error {} + +async function request(method: string, url: string, body?: unknown): Promise { + let res: Response; + try { + res = await fetch(url, { + method, + headers: body === undefined ? undefined : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch { + throw new ApiError('Cannot reach the Booksorter server'); + } + if (!res.ok) { + let msg = `Request failed (${res.status})`; + try { const j = await res.json(); if (j && typeof j.error === 'string') msg = j.error; } catch { /* keep default */ } + throw new ApiError(msg); + } + if (res.status === 204) return undefined as T; + const text = await res.text(); + return (text ? JSON.parse(text) : undefined) as T; +} + +/** Some creation routes may answer with the Book itself or with {book}; accept both. */ +function toBook(r: unknown): Book { + const o = r as { book?: Book }; + return (o && typeof o === 'object' && 'book' in o && o.book ? o.book : r) as Book; +} + +export interface ManualInput { title: string; authors: string[]; year?: number; publisher?: string; callNumber?: string } +export interface BookPatch { title?: string; authors?: string[]; publisher?: string | null; year?: number | null; callNumber?: string } + +export const api = { + scan: (isbn: string) => request<{ book: Book; duplicate: boolean }>('POST', '/api/scan', { isbn }), + addLccn: async (lccn: string) => toBook(await request('POST', '/api/books/lccn', { lccn })), + search: (title: string, author: string) => + request('GET', `/api/search?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`), + fromSearch: async (result: SearchResult) => toBook(await request('POST', '/api/books/from-search', { result })), + addManual: async (input: ManualInput) => toBook(await request('POST', '/api/books/manual', input)), + listBooks: (filter: 'all' | 'queue' | 'attention' = 'all', q = '') => + request('GET', `/api/books?filter=${filter}&q=${encodeURIComponent(q)}`), + patchBook: async (id: number, patch: BookPatch) => toBook(await request('PATCH', `/api/books/${id}`, patch)), + deleteBook: (id: number) => request('DELETE', `/api/books/${id}`), + queueBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/queue`)), + retryBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/retry`)), + confirmPrint: (ids: number[]) => request('POST', '/api/print/confirm', { ids }), + getSettings: () => request('GET', '/api/settings'), + putSettings: (s: Settings) => request('PUT', '/api/settings', s), + /** Fetch the PDF as a blob so the X-Book-Ids header can be read. */ + async fetchPdf(start: number): Promise<{ blob: Blob; ids: number[] }> { + let res: Response; + try { res = await fetch(`/api/print.pdf?start=${start}`); } + catch { throw new ApiError('Cannot reach the Booksorter server'); } + if (!res.ok) { + let msg = `Request failed (${res.status})`; + try { const j = await res.json(); if (j && typeof j.error === 'string') msg = j.error; } catch { /* default */ } + throw new ApiError(msg); + } + const ids = (res.headers.get('X-Book-Ids') ?? '').split(',').map(s => Number(s.trim())).filter(n => Number.isInteger(n) && n > 0); + return { blob: await res.blob(), ids }; + }, +}; diff --git a/src/web/components/BookEditor.tsx b/src/web/components/BookEditor.tsx new file mode 100644 index 0000000..3d7ce82 --- /dev/null +++ b/src/web/components/BookEditor.tsx @@ -0,0 +1,61 @@ +import { useState } from 'preact/hooks'; +import type { Book } from '../../shared/types.ts'; +import { api } from '../api.ts'; +import { upsertBook, dispatch } from '../live.ts'; + +export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) { + const [title, setTitle] = useState(book.title); + const [authors, setAuthors] = useState(book.authors.join('; ')); + const [publisher, setPublisher] = useState(book.publisher ?? ''); + const [year, setYear] = useState(book.year?.toString() ?? ''); + const [callNumber, setCallNumber] = useState(book.callNumber ?? ''); + const [msg, setMsg] = useState(''); + const [busy, setBusy] = useState(false); + + async function run(fn: () => Promise) { + setBusy(true); setMsg(''); + try { await fn(); } catch (e) { setMsg((e as Error).message); } + setBusy(false); + } + + const save = (ev: Event) => { ev.preventDefault(); void run(async () => { + const patch: Record = { + title: title.trim(), + authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean), + publisher: publisher.trim() || null, + year: year.trim() ? Number(year) : null, + }; + if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim(); + upsertBook(await api.patchBook(book.id, patch)); + onClose(); + }); }; + + return ( +
+ + +
+ + +
+ + {book.attentionReason ?

{book.attentionReason}

: null} + {msg ? : null} +
+ + + + + +
+
+ ); +} diff --git a/src/web/components/CallNo.tsx b/src/web/components/CallNo.tsx new file mode 100644 index 0000000..f1a2831 --- /dev/null +++ b/src/web/components/CallNo.tsx @@ -0,0 +1,13 @@ +import { cardLines, parseCallNumber } from '../../shared/callnumber.ts'; + +export function CallNo({ value, approximate }: { value: string | null; approximate?: boolean }) { + if (!value) return No call number; + const cn = parseCallNumber(value); + const lines = cn ? cardLines(cn) : [value, '']; + return ( + + {lines[0]}{approximate ? ~ : null} + {lines[1] || ' '} + + ); +} diff --git a/src/web/index.html b/src/web/index.html new file mode 100644 index 0000000..b741165 --- /dev/null +++ b/src/web/index.html @@ -0,0 +1,13 @@ + + + + + + Booksorter + + + +
+ + + diff --git a/src/web/live.ts b/src/web/live.ts new file mode 100644 index 0000000..32071c1 --- /dev/null +++ b/src/web/live.ts @@ -0,0 +1,42 @@ +import { useEffect, useState } from 'preact/hooks'; +import type { Book } from '../shared/types.ts'; +import { api } from './api.ts'; +import { emptyState, reduce, shelfOrder } from './store.ts'; +import type { BookAction, BookState } from './store.ts'; + +let state: BookState = emptyState; +const listeners = new Set<() => void>(); + +export function dispatch(action: BookAction): void { + state = reduce(state, action); + listeners.forEach(l => l()); +} +export const upsertBook = (book: Book) => dispatch({ type: 'upsert', book }); + +export function useBooks(): Book[] { + const [, force] = useState(0); + useEffect(() => { + const l = () => force(n => n + 1); + listeners.add(l); + return () => { listeners.delete(l); }; + }, []); + return shelfOrder(state); +} + +export function getBook(id: number): Book | undefined { return state.byId[id]; } + +async function refetch(): Promise { + try { dispatch({ type: 'replace', books: await api.listBooks('all') }); } catch { /* retried on next open */ } +} + +/** One EventSource for the whole app. Every (re)connect refetches the full list. */ +export function startLive(): void { + const es = new EventSource('/api/events'); + es.onopen = () => { void refetch(); }; + es.addEventListener('book', e => { + try { upsertBook(JSON.parse((e as MessageEvent).data) as Book); } catch { /* ignore */ } + }); + es.addEventListener('deleted', e => { + try { dispatch({ type: 'delete', id: (JSON.parse((e as MessageEvent).data) as { id: number }).id }); } catch { /* ignore */ } + }); +} diff --git a/src/web/main.tsx b/src/web/main.tsx new file mode 100644 index 0000000..020027f --- /dev/null +++ b/src/web/main.tsx @@ -0,0 +1,33 @@ +import { render } from 'preact'; +import { useState } from 'preact/hooks'; +import { startLive, useBooks } from './live.ts'; +import { Scan } from './views/Scan.tsx'; +import { Queue } from './views/Queue.tsx'; +import { Catalog } from './views/Catalog.tsx'; + +type Tab = 'scan' | 'queue' | 'catalog'; + +function App() { + const [tab, setTab] = useState('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']]; + return ( + <> +
+

Booksorter

+ +
+
+ {tab === 'scan' ? : tab === 'queue' ? : } +
+ + ); +} + +startLive(); +render(, document.getElementById('app')!); diff --git a/src/web/readstate.test.ts b/src/web/readstate.test.ts new file mode 100644 index 0000000..93ed0bb --- /dev/null +++ b/src/web/readstate.test.ts @@ -0,0 +1,52 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { acceptRead, endRound, 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); + assert.equal(r.emit, ISBN); + assert.equal(r.reject, false); +}); + +test('a gap between reads resets the streak', () => { + let r = acceptRead(newReadState(), ISBN, 0); + const s = endRound(r.state, []); + r = acceptRead(s, ISBN, 150); + assert.equal(r.emit, null); +}); + +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 UPC 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); + assert.equal(r.reject, true); +}); diff --git a/src/web/readstate.ts b/src/web/readstate.ts new file mode 100644 index 0000000..99d447b --- /dev/null +++ b/src/web/readstate.ts @@ -0,0 +1,39 @@ +import { normalizeIsbn } from '../shared/isbn.ts'; + +export const REPEAT_MS = 5000; + +export interface ReadState { + streak: Record; + emittedAt: Record; + rejectedAt: Record; +} + +export function newReadState(): ReadState { + return { streak: {}, emittedAt: {}, rejectedAt: {} }; +} + +/** Call once per detected code in a detection round. */ +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); + 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 }; + } + 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 }; +} + +/** 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 = {}; + for (const c of seen) if (state.streak[c] !== undefined) streak[c] = state.streak[c]; + return { ...state, streak }; +} diff --git a/src/web/scanner.ts b/src/web/scanner.ts new file mode 100644 index 0000000..b862746 --- /dev/null +++ b/src/web/scanner.ts @@ -0,0 +1,85 @@ +import { BarcodeDetector, prepareZXingModule } from 'barcode-detector/ponyfill'; +import { acceptRead, endRound, newReadState } from './readstate.ts'; + +export { acceptRead } from './readstate.ts'; +export type { ReadState } from './readstate.ts'; + +/** The reader wasm is served by our own server (copied there by scripts/build-web.ts), never a CDN. */ +export const WASM_PATH = '/zxing_reader.wasm'; + +let prepared = false; +function prepare(): void { + if (prepared) return; + prepared = true; + prepareZXingModule({ + overrides: { + locateFile: (path: string, prefix: string) => + path.endsWith('.wasm') ? WASM_PATH : prefix + path, + }, + fireImmediately: true, + }); +} + +const INTERVAL_MS = 150; + +export async function startScanner( + video: HTMLVideoElement, + deviceId: string | undefined, + onIsbn: (isbn13: string) => void, + onReject: (code: string) => void, +): Promise<() => void> { + prepare(); + const stream = await navigator.mediaDevices.getUserMedia({ + video: { + ...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'environment' }), + width: { ideal: 1920 }, height: { ideal: 1080 }, + }, + audio: false, + }); + let stopped = false; + let timer: ReturnType | undefined; + const stop = () => { + stopped = true; + if (timer !== undefined) clearTimeout(timer); + stream.getTracks().forEach(t => t.stop()); + if (video.srcObject === stream) video.srcObject = null; + }; + + try { + video.srcObject = stream; + video.muted = true; + await video.play(); + } catch (e) { + stop(); + throw e; + } + + const detector = new BarcodeDetector({ formats: ['ean_13'] }); + let state = newReadState(); + + // Sequential loop: the next round is scheduled only after the previous detection finished, + // so two detections never overlap. + const tick = async () => { + if (stopped) return; + const began = performance.now(); + if (video.readyState >= 2 && video.videoWidth > 0) { + try { + const found = await detector.detect(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); + state = r.state; + if (r.emit) onIsbn(r.emit); + else if (r.reject) onReject(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; +} diff --git a/src/web/sheets.test.ts b/src/web/sheets.test.ts new file mode 100644 index 0000000..b66b2d8 --- /dev/null +++ b/src/web/sheets.test.ts @@ -0,0 +1,15 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { sheetCount } from './sheets.ts'; + +test('sheet counts', () => { + assert.equal(sheetCount(0, 1), 0); + assert.equal(sheetCount(1, 1), 1); + assert.equal(sheetCount(3, 1), 1); + assert.equal(sheetCount(4, 1), 2); + assert.equal(sheetCount(3, 3), 2); + assert.equal(sheetCount(1, 3), 1); + assert.equal(sheetCount(2, 3), 2); + assert.equal(sheetCount(2, 2), 1); + assert.equal(sheetCount(3, 2), 2); +}); diff --git a/src/web/sheets.ts b/src/web/sheets.ts new file mode 100644 index 0000000..1db913f --- /dev/null +++ b/src/web/sheets.ts @@ -0,0 +1,5 @@ +/** Number of sheets needed for `count` cards when the first card goes in slot `start` (1 to 3). */ +export function sheetCount(count: number, start: number): number { + if (count <= 0) return 0; + return Math.ceil((count + (start - 1)) / 3); +} diff --git a/src/web/sound.ts b/src/web/sound.ts new file mode 100644 index 0000000..7a9e6b0 --- /dev/null +++ b/src/web/sound.ts @@ -0,0 +1,26 @@ +let ctx: AudioContext | null = null; + +/** Create or resume the audio context. Call from a user gesture (the Start camera click). */ +export function unlockAudio(): void { + try { + ctx ??= new AudioContext(); + if (ctx.state === 'suspended') void ctx.resume(); + } catch { /* audio unavailable; stay silent */ } +} + +function tone(freq: number, ms: number): void { + if (!ctx) return; + try { + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.frequency.value = freq; + gain.gain.setValueAtTime(0.2, ctx.currentTime); + gain.gain.setValueAtTime(0.0001, ctx.currentTime + ms / 1000); + osc.connect(gain).connect(ctx.destination); + osc.start(); + osc.stop(ctx.currentTime + ms / 1000); + } catch { /* ignore */ } +} + +export const beepAccept = () => tone(880, 120); +export const beepLow = () => tone(220, 200); diff --git a/src/web/store.test.ts b/src/web/store.test.ts new file mode 100644 index 0000000..65a441e --- /dev/null +++ b/src/web/store.test.ts @@ -0,0 +1,40 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { emptyState, reduce, shelfOrder } from './store.ts'; +import type { Book } from '../shared/types.ts'; + +function book(id: number, title: string, sortKey: string | null): Book { + return { + id, isbn13: null, lccn: null, title, subtitle: null, authors: [], publisher: null, year: null, + subjects: [], callNumber: null, sortKey, confidence: null, source: null, dewey: null, + status: 'resolved', attentionReason: null, manualOverride: false, inQueue: true, + printedAt: null, createdAt: '', updatedAt: '', + }; +} + +test('upsert adds then replaces', () => { + let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') }); + s = reduce(s, { type: 'upsert', book: book(1, 'A2', 'x') }); + assert.equal(shelfOrder(s).length, 1); + assert.equal(shelfOrder(s)[0].title, 'A2'); +}); + +test('delete removes', () => { + let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') }); + s = reduce(s, { type: 'delete', id: 1 }); + assert.equal(shelfOrder(s).length, 0); + assert.equal(shelfOrder(reduce(s, { type: 'delete', id: 99 })).length, 0); +}); + +test('replace swaps the whole set', () => { + let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') }); + s = reduce(s, { type: 'replace', books: [book(2, 'B', 'y')] }); + assert.deepEqual(shelfOrder(s).map(b => b.id), [2]); +}); + +test('shelf order: sort key, unparseable last, then title', () => { + let s = emptyState; + for (const b of [book(1, 'Zed', null), book(2, 'Beta', 'QA0002'), book(3, 'Alpha', null), book(4, 'Gamma', 'QA0001'), book(5, 'Delta', 'QA0002')]) + s = reduce(s, { type: 'upsert', book: b }); + assert.deepEqual(shelfOrder(s).map(b => b.id), [4, 2, 5, 3, 1]); +}); diff --git a/src/web/store.ts b/src/web/store.ts new file mode 100644 index 0000000..607ac76 --- /dev/null +++ b/src/web/store.ts @@ -0,0 +1,40 @@ +import type { Book } from '../shared/types.ts'; + +export interface BookState { byId: Record } +export type BookAction = + | { type: 'upsert'; book: Book } + | { type: 'delete'; id: number } + | { type: 'replace'; books: Book[] }; + +export const emptyState: BookState = { byId: {} }; + +export function reduce(state: BookState, action: BookAction): BookState { + switch (action.type) { + case 'upsert': + return { byId: { ...state.byId, [action.book.id]: action.book } }; + case 'delete': { + const byId = { ...state.byId }; + delete byId[action.id]; + return { byId }; + } + case 'replace': { + const byId: Record = {}; + for (const b of action.books) byId[b.id] = b; + return { byId }; + } + } +} + +/** Shelf order: by sortKey, books without one last, then title. */ +export function compareShelf(a: Book, b: Book): number { + if (a.sortKey !== b.sortKey) { + if (a.sortKey === null) return 1; + if (b.sortKey === null) return -1; + return a.sortKey < b.sortKey ? -1 : 1; + } + return a.title.localeCompare(b.title); +} + +export function shelfOrder(state: BookState): Book[] { + return Object.values(state.byId).sort(compareShelf); +} diff --git a/src/web/styles.css b/src/web/styles.css new file mode 100644 index 0000000..ed4d7a3 --- /dev/null +++ b/src/web/styles.css @@ -0,0 +1,77 @@ +:root { + color-scheme: light dark; + --bg: #f7f6f3; --panel: #fff; --text: #1d1d1b; --muted: #6a6a64; --line: #dcdad3; + --accent: #1f5fbf; --accent-text: #fff; --ok: #1d7a46; --warn: #a15c00; --bad: #b3261e; --flash: #2fa35d; +} +@media (prefers-color-scheme: dark) { + :root { --bg: #16171a; --panel: #1f2125; --text: #ecebe6; --muted: #9a9a94; --line: #33363b; + --accent: #6ea3f2; --accent-text: #0b1b33; --ok: #52c586; --warn: #e0a24a; --bad: #f08a82; --flash: #52c586; } +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--bg); color: var(--text); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; } +header { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; padding: 14px 20px; border-bottom: 1px solid var(--line); background: var(--panel); } +h1 { font-size: 1.15rem; margin: 0; } +h2 { font-size: 1.05rem; margin: 0 0 8px; } +nav { display: flex; gap: 6px; flex-wrap: wrap; } +nav button { border: 0; background: none; padding: 6px 12px; border-radius: 8px; color: var(--muted); } +nav button.on { background: var(--bg); color: var(--text); font-weight: 600; } +main { max-width: 1100px; margin: 0 auto; padding: 20px; } +button, .button, select, input { font: inherit; color: inherit; } +button, .button { display: inline-block; padding: 8px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); cursor: pointer; text-decoration: none; } +button:hover:not(:disabled), .button:hover { border-color: var(--muted); } +button:disabled { opacity: .5; cursor: default; } +button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); } +button.danger { color: var(--bad); } +button.quiet { border-color: transparent; background: none; color: var(--muted); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +input, select { padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); width: 100%; } +input[type=checkbox] { width: auto; } +label { display: block; font-size: .9rem; color: var(--muted); } +label > input, label > select { margin-top: 4px; color: var(--text); } +label small { display: block; margin-top: 4px; } +.row { display: flex; gap: 10px; align-items: flex-end; margin: 10px 0; } +.row.wrap { flex-wrap: wrap; align-items: center; } +.grow { flex: 1 1 200px; } .year { width: 110px; } +.stack { display: grid; gap: 10px; margin: 10px 0; } +.muted { color: var(--muted); } .mono { font-family: ui-monospace, "SF Mono", Menlo, monospace; } +.error { color: var(--bad); } .warn, .warn-text { color: var(--warn); } +.check { display: flex; gap: 6px; align-items: center; } + +.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 { 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; } +.isbn-form input { font-size: 1.1rem; } + +.list { list-style: none; margin: 0; padding: 0; } +.item { display: flex; gap: 14px; justify-content: space-between; align-items: flex-start; padding: 12px 0; border-bottom: 1px solid var(--line); } +.item.column { flex-direction: column; align-items: stretch; gap: 8px; } +.item-btn { display: flex; gap: 14px; align-items: flex-start; width: 100%; text-align: left; border: 0; padding: 0; background: none; } +.item-main { display: flex; flex-direction: column; min-width: 0; flex: 1; } +.item-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; } +.title { overflow-wrap: anywhere; } +.callno { display: inline-flex; flex-direction: column; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-variant-numeric: tabular-nums; white-space: pre; min-width: 9.5em; font-size: .92rem; line-height: 1.35; } +.item-main .callno { margin-top: 4px; } +.approx { color: var(--warn); } +.chip { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: .8rem; border: 1px solid var(--line); white-space: nowrap; } +.chip.ok { color: var(--ok); border-color: var(--ok); } .chip.warn { color: var(--warn); border-color: var(--warn); } +.chip.dup { color: var(--accent); border-color: var(--accent); } .chip.pending { color: var(--muted); } +.error-item { color: var(--bad); } +details { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 10px 14px; margin: 8px 0; } +summary { cursor: pointer; font-weight: 600; } +.results .result { width: 100%; text-align: left; display: flex; flex-direction: column; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: none; } +.card { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 14px; margin: 10px 0; } +.editor { display: grid; gap: 10px; } +.editor .row { margin: 0; } +.queue section { margin-bottom: 28px; } +fieldset.start { border: 0; padding: 0; margin: 16px 0 8px; } +legend { color: var(--muted); font-size: .9rem; padding: 0; margin-bottom: 6px; } +.sheet { display: inline-flex; flex-direction: column; gap: 4px; padding: 8px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); } +.slot { width: 150px; height: 40px; padding: 0; border-radius: 4px; } +.slot.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); } +.slot.used { opacity: .45; } +.confirm { border-color: var(--accent); } diff --git a/src/web/views/Catalog.tsx b/src/web/views/Catalog.tsx new file mode 100644 index 0000000..18609ab --- /dev/null +++ b/src/web/views/Catalog.tsx @@ -0,0 +1,42 @@ +import { useState } from 'preact/hooks'; +import { useBooks } from '../live.ts'; +import { CallNo } from '../components/CallNo.tsx'; +import { BookEditor } from '../components/BookEditor.tsx'; + +export function Catalog() { + const books = useBooks(); + const [q, setQ] = useState(''); + const [attentionOnly, setAttentionOnly] = useState(false); + const [openId, setOpenId] = useState(null); + const needle = q.trim().toLowerCase(); + const shown = books.filter(b => { + if (attentionOnly && b.status !== 'needs_attention') return false; + if (!needle) return true; + return [b.title, b.authors.join(' '), b.isbn13 ?? '', b.callNumber ?? ''].some(s => s.toLowerCase().includes(needle)); + }); + return ( +
+
+ setQ(e.currentTarget.value)} /> + +
+

{shown.length} of {books.length} books

+ {shown.length === 0 ?

Nothing to show.

: null} +
    + {shown.map(b => ( +
  • + + {openId === b.id ? setOpenId(null)} /> : null} +
  • + ))} +
+
+ ); +} diff --git a/src/web/views/Queue.tsx b/src/web/views/Queue.tsx new file mode 100644 index 0000000..edd0a7c --- /dev/null +++ b/src/web/views/Queue.tsx @@ -0,0 +1,143 @@ +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 { 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 attention = books.filter(b => b.status === 'needs_attention'); + const [start, setStart] = useState(1); + const [msg, setMsg] = useState(''); + const [busy, setBusy] = useState(false); + const [pending, setPending] = useState<{ ids: number[]; url: string } | null>(null); + const [editId, setEditId] = useState(null); + const sheets = sheetCount(queued.length, start); + + async function makePdf() { + setMsg(''); setBusy(true); + // Open the tab inside the click so the popup blocker allows it, then point it at the PDF. + const tab = window.open('', '_blank'); + try { + const { blob, ids } = await api.fetchPdf(start); + const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' })); + if (tab) tab.location.href = url; + setPending({ ids, url }); + } catch (e) { + tab?.close(); + setMsg((e as Error).message); + } + setBusy(false); + } + async function confirmPrinted() { + if (!pending) return; + try { + await api.confirmPrint(pending.ids); + URL.revokeObjectURL(pending.url); + setPending(null); + setMsg(''); + // Live events will update the books; refresh the local copies too. + for (const b of await api.listBooks('all')) upsertBook(b); + } catch (e) { setMsg((e as Error).message); } + } + + return ( +
+
+

Print queue

+

{queued.length} {queued.length === 1 ? 'card' : 'cards'} ready, {sheets} {sheets === 1 ? 'sheet' : 'sheets'}

+ {queued.length === 0 ?

Nothing is waiting to print.

: null} +
    + {queued.map(b => ( +
  • + + {b.title}{b.authors.join(', ')} +
  • + ))} +
+ +
+ First card goes in position +
+ {[1, 2, 3].map(n => ( + + ))} +
+
+

Print at actual size (100%), single-sided, from the manual feed slot.

+ + {msg ? : null} + {pending ? ( + + ) : null} +
+ +
+

Needs attention

+ {attention.length === 0 ?

Every book has a call number.

: null} +
    + {attention.map(b => ( +
  • +
    + {b.title} + {b.authors.join(', ')} + {b.attentionReason} +
    +
    + + + +
    + {editId === b.id ? setEditId(null)} /> : null} +
  • + ))} +
+
+ + +
+ ); +} + +function Alignment() { + const [x, setX] = useState('0'); const [y, setY] = useState('0'); + const [msg, setMsg] = useState(''); + const loaded = useRef(false); + useEffect(() => { + api.getSettings().then(s => { setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); loaded.current = true; }).catch(() => {}); + }, []); + const save = async () => { + setMsg(''); + try { + const s = await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0 }); + setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setMsg('Saved'); + } catch (e) { setMsg((e as Error).message); } + }; + return ( +
+

Printer alignment

+
+ + +
+
+ + Print calibration page +
+ {msg ?

{msg}

: null} +
+ ); +} diff --git a/src/web/views/Scan.tsx b/src/web/views/Scan.tsx new file mode 100644 index 0000000..ce5883e --- /dev/null +++ b/src/web/views/Scan.tsx @@ -0,0 +1,256 @@ +import { useEffect, useRef, useState } from 'preact/hooks'; +import type { Book, SearchResult } from '../../shared/types.ts'; +import { normalizeIsbn } from '../../shared/isbn.ts'; +import { api } from '../api.ts'; +import { getBook, upsertBook, useBooks } from '../live.ts'; +import { startScanner } from '../scanner.ts'; +import { beepAccept, beepLow, unlockAudio } from '../sound.ts'; +import { CallNo } from '../components/CallNo.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; + +function cameraMessage(e: unknown): string { + const name = (e as { name?: string })?.name; + if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was blocked. Allow it in the browser, or type the ISBN below.'; + if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera was found. You can still type or scan the ISBN below.'; + if (name === 'NotReadableError') return 'The camera is busy in another program.'; + return 'The camera could not be started. You can still 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(null); + const isbnBox = useRef(null); + const stopRef = useRef<(() => void) | null>(null); + const [running, setRunning] = useState(false); + const [camError, setCamError] = useState(''); + const [devices, setDevices] = useState([]); + const [deviceId, setDeviceId] = useState(() => { try { return localStorage.getItem('camera') ?? ''; } catch { return ''; } }); + const [flash, setFlash] = useState(false); + const [typed, setTyped] = useState(''); + const [typedError, setTypedError] = useState(''); + + const addEntry = (e: Omit) => { entries = [{ key: nextKey++, ...e }, ...entries]; refresh(); }; + + 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 }); + } + } + 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 }); }; + + function stopCamera() { + stopRef.current?.(); stopRef.current = null; setRunning(false); + } + async function startCamera() { + unlockAudio(); // needs the user gesture + setCamError(''); + stopCamera(); + 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')); + } catch (e) { + setCamError(cameraMessage(e)); + } + isbnBox.current?.focus(); + } + useEffect(() => stopCamera, []); // stop on leaving the view + + // Keep the ISBN box focused unless the user is typing in another field. + useEffect(() => { + const focusBox = () => { + const a = document.activeElement; + if (!a || a === document.body) isbnBox.current?.focus(); + }; + focusBox(); + const onOut = () => setTimeout(focusBox, 0); + const onKey = (e: KeyboardEvent) => { + if (e.ctrlKey || e.metaKey || e.altKey) return; + const a = document.activeElement; + 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); }; + }, []); + + const onSubmit = (ev: Event) => { + ev.preventDefault(); + const raw = typed.trim(); + if (!raw) return; + const isbn = normalizeIsbn(raw); + if (!isbn) { beepLow(); setTypedError('Not a valid ISBN'); return; } + setTypedError(''); setTyped(''); + beepAccept(); + void submitIsbn(isbn); + }; + + return ( +
+
+
+
+
+ + {devices.length > 1 ? ( + + ) : null} +
+ {camError ? : null} +
+ + {typedError ? : null} +
+
+ +
+

This session

+ {entries.length === 0 ?

Scanned books appear here.

: null} +
    + {entries.map(e => )} +
+
+ +
+ addEntry({ bookId: b.id })} /> + addEntry({ bookId: b.id })} /> + addEntry({ bookId: b.id })} /> +
+
+ ); +} + +function EntryRow({ entry }: { entry: Entry }) { + const [queuing, setQueuing] = useState(false); + if (entry.bookId === undefined) return
  • {entry.note}
  • ; + const book = getBook(entry.bookId); + if (!book) return
  • Removed
  • ; + let chip; + if (entry.duplicate) chip = Already in catalog; + else if (book.status === 'pending') chip = Looking up; + else if (book.status === 'resolved') chip = Ready; + else chip = Needs attention; + return ( +
  • +
    + {book.title} + {book.authors.length ? {book.authors.join(', ')} : null} + +
    +
    + {chip} + {!entry.duplicate && book.status === 'needs_attention' && book.attentionReason ? {book.attentionReason} : null} + {entry.duplicate ? (book.inQueue + ? In the print queue + : ) : null} +
    +
  • + ); +} + +function SearchForm({ onAdded }: { onAdded: (b: Book) => void }) { + const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); + const [results, setResults] = useState(null); + const [msg, setMsg] = useState(''); const [busy, setBusy] = useState(false); + const go = async (ev: Event) => { + ev.preventDefault(); setBusy(true); setMsg(''); + try { setResults(await api.search(title.trim(), author.trim())); } catch (e) { setMsg((e as Error).message); } + setBusy(false); + }; + return ( +
    + Search by title and author +
    + + + +
    + {msg ? : null} + {results && results.length === 0 ?

    No results.

    : null} +
      + {results?.map(r => ( +
    • + ))} +
    +
    + ); +} + +function LccnForm({ onAdded }: { onAdded: (b: Book) => void }) { + const [lccn, setLccn] = useState(''); const [msg, setMsg] = useState(''); + return ( +
    + Enter LCCN +
    { + ev.preventDefault(); setMsg(''); + try { const b = await api.addLccn(lccn.trim()); upsertBook(b); onAdded(b); setLccn(''); } catch (e) { setMsg((e as Error).message); } + }}> + + + {msg ? : null} +
    +
    + ); +} + +function ManualForm({ onAdded }: { onAdded: (b: Book) => void }) { + const [title, setTitle] = useState(''); const [authors, setAuthors] = useState(''); + const [year, setYear] = useState(''); const [cn, setCn] = useState(''); const [msg, setMsg] = useState(''); + return ( +
    + Enter by hand +
    { + ev.preventDefault(); setMsg(''); + 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() } : {}), + }); + upsertBook(b); onAdded(b); setTitle(''); setAuthors(''); setYear(''); setCn(''); + } catch (e) { setMsg((e as Error).message); } + }}> + + + + + + {msg ? : null} +
    +
    + ); +}