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,178 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { openDb } from './db.ts';
|
||||
import { createJobs } from './jobs.ts';
|
||||
import { createApp, createEventBus } from './app.ts';
|
||||
import type { CardData, Resolution, Settings } from '../shared/types.ts';
|
||||
|
||||
const found: Resolution = {
|
||||
meta: { title: 'Rust', authors: ['Klabnik, Steve'], subjects: [] },
|
||||
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
|
||||
};
|
||||
|
||||
function setup(resolve = async () => found) {
|
||||
const db = openDb(':memory:');
|
||||
const events = createEventBus();
|
||||
const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0] });
|
||||
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
|
||||
const app = createApp({
|
||||
db, jobs, resolver, events,
|
||||
renderCardsPdf: async (cards, opts) => { pdfCalls.push({ cards, opts }); return new TextEncoder().encode('%PDF-stub'); },
|
||||
renderCalibrationPdf: async () => new TextEncoder().encode('%PDF-cal'),
|
||||
classNames: (l) => ({ className: 'Class ' + l[0], subclassName: 'Sub ' + l }),
|
||||
});
|
||||
const req = (method: string, path: string, json?: unknown) =>
|
||||
app.request(path, { method, ...(json === undefined ? {} : { body: JSON.stringify(json), headers: { 'content-type': 'application/json' } }) });
|
||||
return { db, jobs, app, req, pdfCalls, events };
|
||||
}
|
||||
|
||||
test('scan: valid, invalid, duplicate', async () => {
|
||||
const { req, jobs, db } = setup();
|
||||
const bad = await req('POST', '/api/scan', { isbn: '123' });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.deepEqual(await bad.json(), { error: 'Not a valid ISBN' });
|
||||
const ok = await req('POST', '/api/scan', { isbn: '978-1-59327-828-1' });
|
||||
const j = await ok.json() as any;
|
||||
assert.equal(j.duplicate, false);
|
||||
assert.equal(j.book.isbn13, '9781593278281');
|
||||
assert.equal(j.book.inQueue, true);
|
||||
assert.equal(j.book.title, '9781593278281');
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(j.book.id)!.status, 'resolved');
|
||||
const dup = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
|
||||
assert.equal(dup.duplicate, true);
|
||||
assert.equal(dup.book.id, j.book.id);
|
||||
assert.equal(dup.book.status, 'resolved');
|
||||
});
|
||||
|
||||
test('two simultaneous scans of one ISBN yield one row', async () => {
|
||||
const { req, db } = setup();
|
||||
const rs = await Promise.all([1, 2, 3].map(() => req('POST', '/api/scan', { isbn: '9781593278281' })));
|
||||
const js = await Promise.all(rs.map((r) => r.json() as Promise<any>));
|
||||
assert.equal(db.listBooks().length, 1);
|
||||
assert.equal(js.filter((j) => !j.duplicate).length, 1);
|
||||
});
|
||||
|
||||
test('PATCH call number that parses, and one that does not', async () => {
|
||||
const { req, db } = setup();
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 't' });
|
||||
const a = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'QA76.73.R87 K53 2018' })).json() as any;
|
||||
assert.equal(a.book.callNumber, 'QA76.73.R87 K53 2018');
|
||||
assert.equal(a.book.status, 'resolved');
|
||||
assert.equal(a.book.manualOverride, true);
|
||||
assert.equal(a.book.confidence, 'manual');
|
||||
const b = await (await req('PATCH', `/api/books/${book.id}`, { callNumber: 'shelf by the window' })).json() as any;
|
||||
assert.equal(b.book.callNumber, 'shelf by the window');
|
||||
assert.equal(b.book.status, 'needs_attention');
|
||||
assert.equal(b.book.attentionReason, 'Call number not recognised');
|
||||
assert.equal(b.book.manualOverride, true);
|
||||
assert.equal((await req('PATCH', '/api/books/999', { title: 'x' })).status, 404);
|
||||
});
|
||||
|
||||
test('list order follows sort key with unparseable last; filters', async () => {
|
||||
const { req } = setup();
|
||||
const mk = async (title: string, callNumber: string) =>
|
||||
req('POST', '/api/books/manual', { title, authors: ['A'], callNumber });
|
||||
await mk('Window', 'shelf by the window');
|
||||
await mk('Second', 'QA76.73.R87 K53 2018');
|
||||
await mk('First', 'PS3558.E63 D8 2005');
|
||||
const all = await (await req('GET', '/api/books')).json() as any[];
|
||||
assert.deepEqual(all.map((b) => b.title), ['First', 'Second', 'Window']);
|
||||
assert.equal(((await (await req('GET', '/api/books?filter=attention')).json()) as any[]).length, 1);
|
||||
assert.equal(((await (await req('GET', '/api/books?q=second')).json()) as any[]).length, 1);
|
||||
});
|
||||
|
||||
test('manual without call number enqueues a lookup; retry refused for override', async () => {
|
||||
const { req, jobs, db } = setup();
|
||||
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', authors: ['Bar'] })).json() as any;
|
||||
assert.equal(m.book.status, 'pending');
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(m.book.id)!.status, 'resolved');
|
||||
const r = await req('POST', `/api/books/${m.book.id}/retry`);
|
||||
assert.equal(r.status, 200);
|
||||
await jobs.idle();
|
||||
await req('PATCH', `/api/books/${m.book.id}`, { callNumber: 'QA76' });
|
||||
assert.equal((await req('POST', `/api/books/${m.book.id}/retry`)).status, 400);
|
||||
});
|
||||
|
||||
test('lccn, from-search, search, delete, queue', async () => {
|
||||
const { req, jobs, db } = setup();
|
||||
const l = await (await req('POST', '/api/books/lccn', { lccn: '88005934' })).json() as any;
|
||||
assert.equal(l.book.lccn, '88005934');
|
||||
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], year: 1999, lccn: '1', lcc: [] } })).json() as any;
|
||||
assert.equal(f.book.year, 1999);
|
||||
assert.equal(((await (await req('GET', '/api/search?title=a&author=b')).json()) as any[])[0].title, 'Hit');
|
||||
await jobs.idle();
|
||||
db.updateBook(l.book.id, { inQueue: false });
|
||||
assert.equal(((await (await req('POST', `/api/books/${l.book.id}/queue`)).json()) as any).book.inQueue, true);
|
||||
assert.equal((await req('DELETE', `/api/books/${l.book.id}`)).status, 200);
|
||||
assert.equal(db.getBook(l.book.id), null);
|
||||
});
|
||||
|
||||
test('print with empty queue -> 400', async () => {
|
||||
const { req } = setup();
|
||||
const r = await req('GET', '/api/print.pdf');
|
||||
assert.equal(r.status, 400);
|
||||
assert.deepEqual(await r.json(), { error: 'Nothing to print' });
|
||||
});
|
||||
|
||||
test('print passes cards in shelf order and honours start; confirm clears queue', async () => {
|
||||
const { req, pdfCalls, db } = setup();
|
||||
await req('POST', '/api/books/manual', { title: 'Second', callNumber: 'QA76.73.R87 K53 2018' });
|
||||
await req('POST', '/api/books/manual', { title: 'First', callNumber: 'PS3558.E63 D8 2005' });
|
||||
await req('POST', '/api/books/manual', { title: 'Odd', callNumber: 'shelf by the window' });
|
||||
const approx = db.insertPending({ title: 'Approx', callNumber: 'B1 .A1 2000', sortKey: 'B 1', status: 'resolved', confidence: 'approximate', inQueue: true }).book;
|
||||
const r = await req('GET', '/api/print.pdf?start=2');
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.headers.get('content-type'), 'application/pdf');
|
||||
assert.equal(await r.text(), '%PDF-stub');
|
||||
const call = pdfCalls[0]!;
|
||||
assert.deepEqual(call.cards.map((c) => c.title), ['Approx', 'First', 'Second']);
|
||||
assert.equal(call.opts.startPosition, 2);
|
||||
assert.equal(call.cards[1]!.className, 'Class P');
|
||||
assert.equal(call.cards[1]!.subclassName, 'Sub PS');
|
||||
assert.equal(call.cards[0]!.approximate, true);
|
||||
assert.equal(call.cards[1]!.approximate, false);
|
||||
const ids = r.headers.get('x-book-ids')!.split(',').map(Number);
|
||||
assert.equal(ids.length, 3);
|
||||
assert.equal(ids[0], approx.id);
|
||||
await req('POST', '/api/print/confirm', { ids });
|
||||
assert.equal((await req('GET', '/api/print.pdf')).status, 400);
|
||||
assert.ok(db.getBook(ids[0]!)!.printedAt);
|
||||
assert.equal(((await (await req('GET', '/api/books?filter=queue')).json()) as any[]).length, 1);
|
||||
});
|
||||
|
||||
test('settings clamp and calibration pdf', async () => {
|
||||
const { req } = setup();
|
||||
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 0, offsetYmm: 0 });
|
||||
const s = await (await req('PUT', '/api/settings', { offsetXmm: 50, offsetYmm: -50 })).json();
|
||||
assert.deepEqual(s, { offsetXmm: 10, offsetYmm: -10 });
|
||||
assert.deepEqual(await (await req('GET', '/api/settings')).json(), { offsetXmm: 10, offsetYmm: -10 });
|
||||
assert.equal((await req('PUT', '/api/settings', { offsetXmm: 'a', offsetYmm: 1 })).status, 400);
|
||||
assert.equal(await (await req('GET', '/api/calibration.pdf')).text(), '%PDF-cal');
|
||||
});
|
||||
|
||||
test('events stream delivers changes and cleans up on disconnect', async () => {
|
||||
const { app, req, events, db } = setup();
|
||||
const ac = new AbortController();
|
||||
const res = await app.request('/api/events', { signal: ac.signal });
|
||||
assert.equal(res.headers.get('content-type'), 'text/event-stream');
|
||||
assert.equal(events.listenerCount(), 1);
|
||||
const reader = res.body!.getReader();
|
||||
const dec = new TextDecoder();
|
||||
await reader.read(); // initial comment
|
||||
const { book } = db.insertPending({ title: 'x' });
|
||||
await req('PATCH', `/api/books/${book.id}`, { title: 'y' });
|
||||
const chunk = dec.decode((await reader.read()).value);
|
||||
assert.match(chunk, /^event: book\ndata: .*"title":"y"/);
|
||||
await req('DELETE', `/api/books/${book.id}`);
|
||||
assert.match(dec.decode((await reader.read()).value), /^event: deleted\ndata: \{"id":\d+\}/);
|
||||
ac.abort();
|
||||
assert.equal(events.listenerCount(), 0);
|
||||
|
||||
const res2 = await app.request('/api/events');
|
||||
assert.equal(events.listenerCount(), 1);
|
||||
await res2.body!.cancel();
|
||||
assert.equal(events.listenerCount(), 0);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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<Omit<Book, 'id' | 'createdAt' | 'updatedAt'>>;
|
||||
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<string, any>;
|
||||
|
||||
const COLUMNS: Record<keyof BookPatch, string> = {
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<Resolution>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
|
||||
export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise<void> }
|
||||
|
||||
// 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<void> {
|
||||
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<number>();
|
||||
let running: Promise<void> | null = null;
|
||||
|
||||
function emit(id: number, patch: Parameters<Db['updateBook']>[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<Db['updateBook']>[1] = {
|
||||
subtitle: meta.subtitle ?? cur.subtitle ?? undefined,
|
||||
publisher: meta.publisher ?? cur.publisher ?? undefined,
|
||||
year: meta.year ?? cur.year ?? undefined,
|
||||
subjects: meta.subjects.length ? meta.subjects : cur.subjects,
|
||||
lccn: meta.lccn ?? cur.lccn ?? undefined,
|
||||
};
|
||||
// A hand-edited book keeps the title and authors the user typed.
|
||||
if (!cur.manualOverride) {
|
||||
if (meta.title) patch.title = meta.title;
|
||||
if (meta.authors.length) patch.authors = meta.authors;
|
||||
}
|
||||
emit(id, patch);
|
||||
}
|
||||
|
||||
async function lookup(id: number): Promise<void> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.status !== 'pending') return;
|
||||
const input: ResolveInput = {};
|
||||
if (book.isbn13) input.isbn13 = book.isbn13;
|
||||
if (book.lccn) input.lccn = book.lccn;
|
||||
if (!book.isbn13) {
|
||||
input.title = book.title;
|
||||
if (book.authors[0]) input.author = book.authors[0];
|
||||
}
|
||||
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<void> {
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
'.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);
|
||||
});
|
||||
@@ -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<typeof layoutCard>) {
|
||||
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 === '~'));
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<typeof cardMatrix>, 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<Uint8Array> {
|
||||
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<Uint8Array> {
|
||||
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();
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<string, Parsed[]>();
|
||||
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<keyof Tiers, Source> = {
|
||||
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;
|
||||
}
|
||||
@@ -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<string, string> } {
|
||||
const map = new Map<string, string>();
|
||||
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);
|
||||
});
|
||||
@@ -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<Resolution>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
|
||||
type Partials = (Partial<BookMeta> | null | undefined)[];
|
||||
|
||||
function mergeMeta(parts: Partials): BookMeta | null {
|
||||
const first = <K extends keyof BookMeta>(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<void>;
|
||||
}): 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<Resolution> {
|
||||
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<OlInfo | null> => {
|
||||
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) };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html><head><title>Request Rejected</title></head>
|
||||
<body><h1>Access Denied</h1>
|
||||
<p>Your client has made too many requests. Please slow down and try again later.</p>
|
||||
</body></html>
|
||||
@@ -0,0 +1,104 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>1</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01291cam a2200337 a 4500</leader>
|
||||
<controlfield tag="001">4434515</controlfield>
|
||||
<controlfield tag="005">20250607165433.5</controlfield>
|
||||
<controlfield tag="008">940906s1995 maua b 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">4434515</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">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</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 94036653 </subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">0201835959</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9780201835953</subfield>
|
||||
</datafield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="9">(DLC) 94036653</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">QA76.758</subfield>
|
||||
<subfield code="b">.B75 1995</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">005.1/068</subfield>
|
||||
<subfield code="2">20</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Brooks, Frederick P.</subfield>
|
||||
<subfield code="q">(Frederick Phillips)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="4">
|
||||
<subfield code="a">The mythical man-month :</subfield>
|
||||
<subfield code="b">essays on software engineering /</subfield>
|
||||
<subfield code="c">Frederick P. Brooks, Jr.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">Anniversary ed.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">Reading, Mass. :</subfield>
|
||||
<subfield code="b">Addison-Wesley Pub. Co.,</subfield>
|
||||
<subfield code="c">1995.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">xiii, 322 p. :</subfield>
|
||||
<subfield code="b">ill. ;</subfield>
|
||||
<subfield code="c">24 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Anniversary ed. has four new chapters.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="504" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes bibliographical references (p. 293-308) and index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Software engineering.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="991" ind1=" " ind2=" ">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.758</subfield>
|
||||
<subfield code="i">.B75 1995</subfield>
|
||||
<subfield code="p">00014313394</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9780201835953</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9780441172719</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9780999999998</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,146 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>2</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>04541cam a2200421 i 4500</leader>
|
||||
<controlfield tag="001">20417920</controlfield>
|
||||
<controlfield tag="005">20250607085613.7</controlfield>
|
||||
<controlfield tag="008">180326s2018 cau 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">20417920</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ecip</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">cf25 2018-03-26</subfield>
|
||||
<subfield code="i">cf25 2018-03-28 to PSD (class./subj.)</subfield>
|
||||
<subfield code="a">td04 2018-04-19 to Dewey</subfield>
|
||||
<subfield code="w">xm09 2018-04-21</subfield>
|
||||
<subfield code="a">xn11 2018-09-11 1 copy rec'd., to CIP ver.</subfield>
|
||||
<subfield code="a">rk20 2018-09-18 book received in ART</subfield>
|
||||
<subfield code="f">rl06 2019-05-03 to BCCD</subfield>
|
||||
<subfield code="u">ma02 2021-12-10 TW Situational</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2018014097</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781593278281</subfield>
|
||||
<subfield code="q">paperback</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">1593278284</subfield>
|
||||
<subfield code="q">paperback</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9781593278519 (epub)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">QA76.73.R87</subfield>
|
||||
<subfield code="b">K53 2018</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">005.13/3</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="084" ind1=" " ind2=" ">
|
||||
<subfield code="a">COM051390</subfield>
|
||||
<subfield code="a">COM051010</subfield>
|
||||
<subfield code="a">COM051000</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Klabnik, Steve,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="4">
|
||||
<subfield code="a">The Rust programming language /</subfield>
|
||||
<subfield code="c">by Steve Klabnik and Carol Nichols ; with contributions from the Rust Community.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">San Francisco :</subfield>
|
||||
<subfield code="b">No Starch Press,</subfield>
|
||||
<subfield code="c">[2018]</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">xxvii, 519 pages ;</subfield>
|
||||
<subfield code="c">24 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="505" ind1="8" ind2=" ">
|
||||
<subfield code="a">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.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"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"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"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"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Rust (Computer programming language)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COMPUTERS / Programming / Open Source.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COMPUTERS / Programming Languages / General.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COMPUTERS / Programming / General.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">Nichols, Carol,</subfield>
|
||||
<subfield code="d">1983-</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="776" ind1="0" ind2="8">
|
||||
<subfield code="i">Online version:</subfield>
|
||||
<subfield code="a">Klabnik, Steve, author.</subfield>
|
||||
<subfield code="t">Rust programming language</subfield>
|
||||
<subfield code="d">San Francisco : No Starch Press, Inc., 2018</subfield>
|
||||
<subfield code="z">9781593278519</subfield>
|
||||
<subfield code="w">(DLC) 2018019844</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record></zs:records><zs:nextRecordPosition>2</zs:nextRecordPosition><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9781593278281</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,106 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><record xmlns="http://www.loc.gov/MARC21/slim" xmlns:zs="http://docs.oasis-open.org/ns/search-ws/sruResponse">
|
||||
<leader>01137pam a2200349 a 4500</leader>
|
||||
<controlfield tag="001">1491800</controlfield>
|
||||
<controlfield tag="005">20250607021246.8</controlfield>
|
||||
<controlfield tag="008">880303s1988 nju 001 0 eng </controlfield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="a">1491800</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="906">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="010">
|
||||
<subfield code="a"> 88005934 </subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">0131103709</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">0131103628</subfield>
|
||||
<subfield code="q">pbk.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">9780131103702</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">9780131103627</subfield>
|
||||
<subfield code="q">(pbk.)</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="9">(DLC) 88005934</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="040">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="050">
|
||||
<subfield code="a">QA76.73.C15</subfield>
|
||||
<subfield code="b">K47 1988</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="082">
|
||||
<subfield code="a">005.13/3</subfield>
|
||||
<subfield code="2">19</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2=" " tag="100">
|
||||
<subfield code="a">Kernighan, Brian W.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2="4" tag="245">
|
||||
<subfield code="a">The C programming language /</subfield>
|
||||
<subfield code="c">Brian W. Kernighan, Dennis M. Ritchie.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="250">
|
||||
<subfield code="a">2nd ed.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="260">
|
||||
<subfield code="a">Englewood Cliffs, N.J. :</subfield>
|
||||
<subfield code="b">Prentice Hall,</subfield>
|
||||
<subfield code="c">c1988.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="300">
|
||||
<subfield code="a">xii, 272 p. ;</subfield>
|
||||
<subfield code="c">25 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="336">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="337">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="338">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="500">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2="0" tag="650">
|
||||
<subfield code="a">C (Computer program language)</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2=" " tag="700">
|
||||
<subfield code="a">Ritchie, Dennis M.,</subfield>
|
||||
<subfield code="d">1941-2011.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="991">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.73.C15</subfield>
|
||||
<subfield code="i">K47 1988</subfield>
|
||||
<subfield code="p">00001105991</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record>
|
||||
@@ -0,0 +1,103 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><record xmlns="http://www.loc.gov/MARC21/slim" xmlns:zs="http://docs.oasis-open.org/ns/search-ws/sruResponse">
|
||||
<leader>01291cam a2200337 a 4500</leader>
|
||||
<controlfield tag="001">4434515</controlfield>
|
||||
<controlfield tag="005">20250607165433.5</controlfield>
|
||||
<controlfield tag="008">940906s1995 maua b 001 0 eng </controlfield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="a">4434515</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="906">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">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</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="010">
|
||||
<subfield code="a"> 94036653 </subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">0201835959</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">9780201835953</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="9">(DLC) 94036653</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="040">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="050">
|
||||
<subfield code="a">QA76.758</subfield>
|
||||
<subfield code="b">.B75 1995</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="082">
|
||||
<subfield code="a">005.1/068</subfield>
|
||||
<subfield code="2">20</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2=" " tag="100">
|
||||
<subfield code="a">Brooks, Frederick P.</subfield>
|
||||
<subfield code="q">(Frederick Phillips)</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2="4" tag="245">
|
||||
<subfield code="a">The mythical man-month :</subfield>
|
||||
<subfield code="b">essays on software engineering /</subfield>
|
||||
<subfield code="c">Frederick P. Brooks, Jr.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="250">
|
||||
<subfield code="a">Anniversary ed.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="260">
|
||||
<subfield code="a">Reading, Mass. :</subfield>
|
||||
<subfield code="b">Addison-Wesley Pub. Co.,</subfield>
|
||||
<subfield code="c">1995.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="300">
|
||||
<subfield code="a">xiii, 322 p. :</subfield>
|
||||
<subfield code="b">ill. ;</subfield>
|
||||
<subfield code="c">24 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="336">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="337">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="338">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="500">
|
||||
<subfield code="a">Anniversary ed. has four new chapters.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="504">
|
||||
<subfield code="a">Includes bibliographical references (p. 293-308) and index.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2="0" tag="650">
|
||||
<subfield code="a">Software engineering.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="991">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.758</subfield>
|
||||
<subfield code="i">.B75 1995</subfield>
|
||||
<subfield code="p">00014313394</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record>
|
||||
@@ -0,0 +1,204 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>2</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01291cam a2200337 a 4500</leader>
|
||||
<controlfield tag="001">4434515</controlfield>
|
||||
<controlfield tag="005">20250607165433.5</controlfield>
|
||||
<controlfield tag="008">940906s1995 maua b 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">4434515</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">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</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 94036653 </subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">0201835959</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9780201835953</subfield>
|
||||
</datafield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="9">(DLC) 94036653</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">QA76.758</subfield>
|
||||
<subfield code="b">.B75 1995</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">005.1/068</subfield>
|
||||
<subfield code="2">20</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Brooks, Frederick P.</subfield>
|
||||
<subfield code="q">(Frederick Phillips)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="4">
|
||||
<subfield code="a">The mythical man-month :</subfield>
|
||||
<subfield code="b">essays on software engineering /</subfield>
|
||||
<subfield code="c">Frederick P. Brooks, Jr.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">Anniversary ed.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">Reading, Mass. :</subfield>
|
||||
<subfield code="b">Addison-Wesley Pub. Co.,</subfield>
|
||||
<subfield code="c">1995.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">xiii, 322 p. :</subfield>
|
||||
<subfield code="b">ill. ;</subfield>
|
||||
<subfield code="c">24 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Anniversary ed. has four new chapters.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="504" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes bibliographical references (p. 293-308) and index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Software engineering.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="991" ind1=" " ind2=" ">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.758</subfield>
|
||||
<subfield code="i">.B75 1995</subfield>
|
||||
<subfield code="p">00014313394</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01102cam a2200313 i 4500</leader>
|
||||
<controlfield tag="001">1260235</controlfield>
|
||||
<controlfield tag="005">20250606191429.1</controlfield>
|
||||
<controlfield tag="008">750318s1975 maua b 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">1260235</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 74004714 </subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">0201006502</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9780201006506</subfield>
|
||||
</datafield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="9">(DLC) 74004714</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">ICU</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">QA76.6</subfield>
|
||||
<subfield code="b">.B75</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">001.6/425</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Brooks, Frederick P.</subfield>
|
||||
<subfield code="q">(Frederick Phillips)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="4">
|
||||
<subfield code="a">The mythical man-month :</subfield>
|
||||
<subfield code="b">essays on software engineering /</subfield>
|
||||
<subfield code="c">Frederick P. Brooks, Jr.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">Reading, Mass. :</subfield>
|
||||
<subfield code="b">Addison-Wesley Pub. Co.,</subfield>
|
||||
<subfield code="c">[1975]</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">xi, 195 p. :</subfield>
|
||||
<subfield code="b">ill. ;</subfield>
|
||||
<subfield code="c">23 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="504" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes bibliographical references and index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Software engineering.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="991" ind1=" " ind2=" ">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.6</subfield>
|
||||
<subfield code="i">.B75</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
<datafield tag="991" ind1=" " ind2=" ">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">QA76.6</subfield>
|
||||
<subfield code="i">.B75</subfield>
|
||||
<subfield code="p">00019520614</subfield>
|
||||
<subfield code="t">Copy 2</subfield>
|
||||
<subfield code="w">CCF</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>2</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.title="mythical man-month" and bath.author="brooks"</zs:query><zs:maximumRecords>5</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -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"}}}
|
||||
@@ -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"}}}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -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"}}}
|
||||
@@ -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"]}]}
|
||||
@@ -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"]}]}
|
||||
@@ -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":[]}
|
||||
@@ -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)"]}]}
|
||||
@@ -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"]}]}
|
||||
@@ -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<HttpResult> {
|
||||
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();
|
||||
}
|
||||
@@ -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('<record');
|
||||
}
|
||||
|
||||
export interface Loc {
|
||||
byIsbn(isbn: string): Promise<MarcFields[]>;
|
||||
byLccn(lccn: string): Promise<MarcFields[]>;
|
||||
byTitle(title: string, author: string): Promise<MarcFields[]>;
|
||||
}
|
||||
|
||||
export function createLoc(deps: {
|
||||
fetch: typeof fetch; cache: SourceCache; intervalMs: number; sleep: (ms: number) => Promise<void>;
|
||||
}): 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<void> {
|
||||
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<MarcFields[]> {
|
||||
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);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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 = `<m:collection xmlns:m="http://www.loc.gov/MARC21/slim"><m:record>
|
||||
<m:datafield tag="050" ind1=" " ind2="0"><m:subfield code="a">PS3558.E63</m:subfield></m:datafield>
|
||||
<m:datafield tag="050" ind1=" " ind2="4"><m:subfield code="a">PZ3.H4186</m:subfield><m:subfield code="b">Du</m:subfield></m:datafield>
|
||||
<m:datafield tag="082" ind1="0" ind2="0"><m:subfield code="a">813/.54</m:subfield></m:datafield>
|
||||
<m:datafield tag="245" ind1="1" ind2="0"><m:subfield code="a">Dune /</m:subfield></m:datafield>
|
||||
<m:datafield tag="264" ind1=" " ind2="1"><m:subfield code="b">Ace,</m:subfield><m:subfield code="c">2005.</m:subfield></m:datafield>
|
||||
</m:record></m:collection>`;
|
||||
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('<html><body>nope</body></html>'), []);
|
||||
});
|
||||
@@ -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<BookMeta>;
|
||||
}
|
||||
|
||||
type Node = Record<string, unknown>;
|
||||
|
||||
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<T>(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<BookMeta> = { 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);
|
||||
}
|
||||
@@ -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<BookMeta>;
|
||||
lcc: Candidate[];
|
||||
dewey: string | null;
|
||||
}
|
||||
|
||||
const FIELDS = 'key,title,author_name,first_publish_year,publisher,ddc,lcc,lccn,subject';
|
||||
|
||||
function obj(v: unknown): Record<string, unknown> | null {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : 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<BookMeta> = {
|
||||
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<string, unknown>[] {
|
||||
const root = obj(parseJson(body));
|
||||
const d = root?.['docs'];
|
||||
return Array.isArray(d) ? d.map(obj).filter((x): x is Record<string, unknown> => 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<BookMeta> = { 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<OlInfo | null>;
|
||||
work(isbn: string): Promise<OlInfo | null>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
|
||||
export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCache }): OpenLibrary {
|
||||
async function body(key: string | null, url: string): Promise<string> {
|
||||
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}`));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { Book, SearchResult, Settings } from '../shared/types.ts';
|
||||
|
||||
export class ApiError extends Error {}
|
||||
|
||||
async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
|
||||
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<SearchResult[]>('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<Book[]>('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<void>('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<unknown>('POST', '/api/print/confirm', { ids }),
|
||||
getSettings: () => request<Settings>('GET', '/api/settings'),
|
||||
putSettings: (s: Settings) => request<Settings>('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 };
|
||||
},
|
||||
};
|
||||
@@ -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<void>) {
|
||||
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<string, unknown> = {
|
||||
title: title.trim(),
|
||||
authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
|
||||
publisher: publisher.trim() || null,
|
||||
year: year.trim() ? Number(year) : null,
|
||||
};
|
||||
if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim();
|
||||
upsertBook(await api.patchBook(book.id, patch));
|
||||
onClose();
|
||||
}); };
|
||||
|
||||
return (
|
||||
<form class="card editor" onSubmit={save}>
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} required /></label>
|
||||
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
|
||||
<div class="row">
|
||||
<label class="grow">Publisher<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} /></label>
|
||||
<label class="year">Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
|
||||
</div>
|
||||
<label>Call number
|
||||
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
|
||||
<small>Changing this locks the number</small>
|
||||
</label>
|
||||
{book.attentionReason ? <p class="warn">{book.attentionReason}</p> : null}
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
<div class="row wrap">
|
||||
<button type="submit" class="primary" disabled={busy}>Save</button>
|
||||
<button type="button" disabled={busy} onClick={() => run(async () => { upsertBook(await api.queueBook(book.id)); })}>Queue reprint</button>
|
||||
<button type="button" disabled={busy || book.manualOverride}
|
||||
title={book.manualOverride ? 'This number was set by hand' : undefined}
|
||||
onClick={() => run(async () => { upsertBook(await api.retryBook(book.id)); })}>Look up again</button>
|
||||
<button type="button" class="danger" disabled={busy} onClick={() => {
|
||||
if (!confirm(`Delete "${book.title}"?`)) return;
|
||||
void run(async () => { await api.deleteBook(book.id); dispatch({ type: 'delete', id: book.id }); onClose(); });
|
||||
}}>Delete</button>
|
||||
<button type="button" class="quiet" onClick={onClose}>Close</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cardLines, parseCallNumber } from '../../shared/callnumber.ts';
|
||||
|
||||
export function CallNo({ value, approximate }: { value: string | null; approximate?: boolean }) {
|
||||
if (!value) return <span class="callno muted">No call number</span>;
|
||||
const cn = parseCallNumber(value);
|
||||
const lines = cn ? cardLines(cn) : [value, ''];
|
||||
return (
|
||||
<span class="callno">
|
||||
<span class="callno-line">{lines[0]}{approximate ? <span class="approx" title="Approximate number"> ~</span> : null}</span>
|
||||
<span class="callno-line">{lines[1] || ' '}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Booksorter</title>
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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<void> {
|
||||
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 */ }
|
||||
});
|
||||
}
|
||||
@@ -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<Tab>('scan');
|
||||
const books = useBooks();
|
||||
const ready = books.filter(b => b.inQueue && b.status === 'resolved' && b.callNumber).length;
|
||||
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', ready ? `Print queue (${ready})` : 'Print queue'], ['catalog', 'Catalog']];
|
||||
return (
|
||||
<>
|
||||
<header>
|
||||
<h1>Booksorter</h1>
|
||||
<nav role="tablist">
|
||||
{tabs.map(([id, label]) => (
|
||||
<button role="tab" aria-selected={tab === id} class={tab === id ? 'on' : ''} onClick={() => setTab(id)}>{label}</button>
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
{tab === 'scan' ? <Scan /> : tab === 'queue' ? <Queue /> : <Catalog />}
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
startLive();
|
||||
render(<App />, document.getElementById('app')!);
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
|
||||
export const REPEAT_MS = 5000;
|
||||
|
||||
export interface ReadState {
|
||||
streak: Record<string, number>;
|
||||
emittedAt: Record<string, number>;
|
||||
rejectedAt: Record<string, number>;
|
||||
}
|
||||
|
||||
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<string, number> = {};
|
||||
for (const c of seen) if (state.streak[c] !== undefined) streak[c] = state.streak[c];
|
||||
return { ...state, streak };
|
||||
}
|
||||
@@ -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<typeof setTimeout> | 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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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]);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
|
||||
export interface BookState { byId: Record<number, Book> }
|
||||
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<number, Book> = {};
|
||||
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);
|
||||
}
|
||||
@@ -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); }
|
||||
@@ -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<number | null>(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 (
|
||||
<div class="catalog">
|
||||
<div class="row wrap">
|
||||
<input class="grow" type="search" placeholder="Search title, author, ISBN or call number" aria-label="Search" value={q} onInput={e => setQ(e.currentTarget.value)} />
|
||||
<label class="check"><input type="checkbox" checked={attentionOnly} onChange={e => setAttentionOnly(e.currentTarget.checked)} /> Needs attention only</label>
|
||||
</div>
|
||||
<p class="muted">{shown.length} of {books.length} books</p>
|
||||
{shown.length === 0 ? <p class="muted">Nothing to show.</p> : null}
|
||||
<ul class="list">
|
||||
{shown.map(b => (
|
||||
<li class="item column" key={b.id}>
|
||||
<button class="item-btn" onClick={() => setOpenId(openId === b.id ? null : b.id)} aria-expanded={openId === b.id}>
|
||||
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
|
||||
<span class="item-main">
|
||||
<strong class="title">{b.title}</strong>
|
||||
<span class="muted">{[b.authors.join(', '), b.year].filter(Boolean).join(' · ')}</span>
|
||||
{b.status === 'needs_attention' ? <span class="chip warn">Needs attention</span> : null}
|
||||
</span>
|
||||
</button>
|
||||
{openId === b.id ? <BookEditor book={b} onClose={() => setOpenId(null)} /> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<number | null>(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 (
|
||||
<div class="queue">
|
||||
<section>
|
||||
<h2>Print queue</h2>
|
||||
<p>{queued.length} {queued.length === 1 ? 'card' : 'cards'} ready, {sheets} {sheets === 1 ? 'sheet' : 'sheets'}</p>
|
||||
{queued.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
|
||||
<ul class="list">
|
||||
{queued.map(b => (
|
||||
<li class="item" key={b.id}>
|
||||
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
|
||||
<span class="item-main"><strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span></span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<fieldset class="start">
|
||||
<legend>First card goes in position</legend>
|
||||
<div class="sheet" role="radiogroup" aria-label="Start position">
|
||||
{[1, 2, 3].map(n => (
|
||||
<button type="button" role="radio" aria-checked={start === n} class={'slot' + (start === n ? ' on' : '') + (n < start ? ' used' : '')}
|
||||
onClick={() => setStart(n)}>{n}</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<p class="muted">Print at actual size (100%), single-sided, from the manual feed slot.</p>
|
||||
<button class="primary" disabled={busy || queued.length === 0} onClick={makePdf}>{busy ? 'Making PDF' : 'Make PDF'}</button>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
{pending ? (
|
||||
<div class="card confirm" role="alert">
|
||||
<p><strong>Did the cards print correctly?</strong></p>
|
||||
<p class="muted"><a href={pending.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
|
||||
<div class="row wrap">
|
||||
<button class="primary" onClick={confirmPrinted}>Yes, clear these from the queue</button>
|
||||
<button onClick={() => { URL.revokeObjectURL(pending.url); setPending(null); }}>Not yet</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Needs attention</h2>
|
||||
{attention.length === 0 ? <p class="muted">Every book has a call number.</p> : null}
|
||||
<ul class="list">
|
||||
{attention.map(b => (
|
||||
<li class="item column" key={b.id}>
|
||||
<div class="item-main">
|
||||
<strong class="title">{b.title}</strong>
|
||||
<span class="muted">{b.authors.join(', ')}</span>
|
||||
<span class="warn-text">{b.attentionReason}</span>
|
||||
</div>
|
||||
<div class="row wrap">
|
||||
<button disabled={b.manualOverride} onClick={async () => { try { upsertBook(await api.retryBook(b.id)); } catch (e) { setMsg((e as Error).message); } }}>Retry</button>
|
||||
<button onClick={() => setEditId(editId === b.id ? null : b.id)}>Edit</button>
|
||||
<button class="danger" onClick={async () => {
|
||||
if (!confirm(`Delete "${b.title}"?`)) return;
|
||||
try { await api.deleteBook(b.id); dispatch({ type: 'delete', id: b.id }); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>Delete</button>
|
||||
</div>
|
||||
{editId === b.id ? <BookEditor book={b} onClose={() => setEditId(null)} /> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<Alignment />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<section>
|
||||
<h2>Printer alignment</h2>
|
||||
<div class="row wrap">
|
||||
<label>Offset X (mm)<input type="number" step="0.25" min="-10" max="10" value={x} onInput={e => setX(e.currentTarget.value)} /></label>
|
||||
<label>Offset Y (mm)<input type="number" step="0.25" min="-10" max="10" value={y} onInput={e => setY(e.currentTarget.value)} /></label>
|
||||
</div>
|
||||
<div class="row wrap">
|
||||
<button onClick={save}>Save offsets</button>
|
||||
<a class="button" href="/api/calibration.pdf" target="_blank" rel="noopener">Print calibration page</a>
|
||||
</div>
|
||||
{msg ? <p class="muted" role="status">{msg}</p> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLVideoElement>(null);
|
||||
const isbnBox = useRef<HTMLInputElement>(null);
|
||||
const stopRef = useRef<(() => void) | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [camError, setCamError] = useState('');
|
||||
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
|
||||
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<Entry, 'key'>) => { 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 (
|
||||
<div class="scan">
|
||||
<section class="left">
|
||||
<div class={'video-wrap' + (flash ? ' flash' : '')}>
|
||||
<video ref={video} playsInline muted class="mirror" />
|
||||
{!running ? <div class="video-empty">Camera is off</div> : null}
|
||||
</div>
|
||||
<div class="row wrap">
|
||||
<button class="primary" onClick={running ? stopCamera : startCamera}>{running ? 'Stop camera' : 'Start camera'}</button>
|
||||
{devices.length > 1 ? (
|
||||
<select aria-label="Camera" value={deviceId} onChange={e => {
|
||||
const v = e.currentTarget.value; setDeviceId(v);
|
||||
try { localStorage.setItem('camera', v); } catch { /* ignore */ }
|
||||
}}>
|
||||
<option value="">Default camera</option>
|
||||
{devices.map((d, i) => <option value={d.deviceId}>{d.label || `Camera ${i + 1}`}</option>)}
|
||||
</select>
|
||||
) : null}
|
||||
</div>
|
||||
{camError ? <p class="warn" role="alert">{camError}</p> : null}
|
||||
<form class="isbn-form" onSubmit={onSubmit}>
|
||||
<label>ISBN
|
||||
<input ref={isbnBox} class="mono" inputMode="numeric" autocomplete="off" placeholder="Type or scan an ISBN, then Enter"
|
||||
value={typed} onInput={e => { setTyped(e.currentTarget.value); setTypedError(''); }} />
|
||||
</label>
|
||||
{typedError ? <p class="error" role="alert">{typedError}</p> : null}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="right">
|
||||
<h2>This session</h2>
|
||||
{entries.length === 0 ? <p class="muted">Scanned books appear here.</p> : null}
|
||||
<ul class="list">
|
||||
{entries.map(e => <EntryRow key={e.key} entry={e} />)}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="forms">
|
||||
<SearchForm onAdded={b => addEntry({ bookId: b.id })} />
|
||||
<LccnForm onAdded={b => addEntry({ bookId: b.id })} />
|
||||
<ManualForm onAdded={b => addEntry({ bookId: b.id })} />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EntryRow({ entry }: { entry: Entry }) {
|
||||
const [queuing, setQueuing] = useState(false);
|
||||
if (entry.bookId === undefined) return <li class="item error-item"><span class="error">{entry.note}</span></li>;
|
||||
const book = getBook(entry.bookId);
|
||||
if (!book) return <li class="item"><span class="muted">Removed</span></li>;
|
||||
let chip;
|
||||
if (entry.duplicate) chip = <span class="chip dup">Already in catalog</span>;
|
||||
else if (book.status === 'pending') chip = <span class="chip pending">Looking up</span>;
|
||||
else if (book.status === 'resolved') chip = <span class="chip ok">Ready</span>;
|
||||
else chip = <span class="chip warn">Needs attention</span>;
|
||||
return (
|
||||
<li class="item">
|
||||
<div class="item-main">
|
||||
<strong class="title">{book.title}</strong>
|
||||
{book.authors.length ? <span class="muted"> {book.authors.join(', ')}</span> : null}
|
||||
<CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} />
|
||||
</div>
|
||||
<div class="item-side">
|
||||
{chip}
|
||||
{!entry.duplicate && book.status === 'needs_attention' && book.attentionReason ? <small class="muted">{book.attentionReason}</small> : null}
|
||||
{entry.duplicate ? (book.inQueue
|
||||
? <small class="muted">In the print queue</small>
|
||||
: <button disabled={queuing} onClick={async () => {
|
||||
setQueuing(true);
|
||||
try { upsertBook(await api.queueBook(book.id)); } catch { /* shown via chip staying */ }
|
||||
setQueuing(false);
|
||||
}}>Queue reprint</button>) : null}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function SearchForm({ onAdded }: { onAdded: (b: Book) => void }) {
|
||||
const [title, setTitle] = useState(''); const [author, setAuthor] = useState('');
|
||||
const [results, setResults] = useState<SearchResult[] | null>(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 (
|
||||
<details>
|
||||
<summary>Search by title and author</summary>
|
||||
<form onSubmit={go} class="stack">
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} /></label>
|
||||
<label>Author<input value={author} onInput={e => setAuthor(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={busy || (!title.trim() && !author.trim())}>{busy ? 'Searching' : 'Search'}</button>
|
||||
</form>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
{results && results.length === 0 ? <p class="muted">No results.</p> : null}
|
||||
<ul class="list results">
|
||||
{results?.map(r => (
|
||||
<li><button class="result" onClick={async () => {
|
||||
try { const b = await api.fromSearch(r); upsertBook(b); onAdded(b); setResults(null); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>
|
||||
<strong>{r.title}</strong>
|
||||
<span class="muted">{[r.authors.join(', '), r.year, r.publisher].filter(Boolean).join(' · ')}</span>
|
||||
</button></li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function LccnForm({ onAdded }: { onAdded: (b: Book) => void }) {
|
||||
const [lccn, setLccn] = useState(''); const [msg, setMsg] = useState('');
|
||||
return (
|
||||
<details>
|
||||
<summary>Enter LCCN</summary>
|
||||
<form class="stack" onSubmit={async ev => {
|
||||
ev.preventDefault(); setMsg('');
|
||||
try { const b = await api.addLccn(lccn.trim()); upsertBook(b); onAdded(b); setLccn(''); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>
|
||||
<label>LCCN<input class="mono" value={lccn} onInput={e => setLccn(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={!lccn.trim()}>Add</button>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<details>
|
||||
<summary>Enter by hand</summary>
|
||||
<form class="stack" onSubmit={async ev => {
|
||||
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); }
|
||||
}}>
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} required /></label>
|
||||
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
|
||||
<label>Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
|
||||
<label>Call number (optional)<input class="mono" value={cn} onInput={e => setCn(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={!title.trim()}>Add</button>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user