Add resolver, server, PDF rendering and web app
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6a7fcdc4b8
commit
bdfdf581f3
59 files changed
+4088
No files matched your search
@@ -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<Uint8Array>;
|
||||
export type RenderCalibrationPdf = (s: Settings) => Promise<Uint8Array>;
|
||||
// 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<Book> {
|
||||
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<Record<string, unknown>> {
|
||||
try {
|
||||
const v = await c.req.json();
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record<string, unknown>;
|
||||
} 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<string, unknown> | 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<Book> = {};
|
||||
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<typeof setInterval> | null = null;
|
||||
const cleanup = () => {
|
||||
off?.(); off = null;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
heartbeat = null;
|
||||
};
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user