Add booksorter design and implementation plan
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
a2ea154cd8
2 files changed
+745
No files matched your search
@@ -0,0 +1,426 @@
|
||||
# Booksorter Implementation Plan
|
||||
|
||||
> **For agentic workers:** you implement exactly one task from this plan, named in your brief. Read the spec and this plan's header, then your task. Work test-first. Do not commit; the orchestrator commits.
|
||||
|
||||
**Goal:** A local web app that scans book barcodes with the laptop camera, finds each book's Library of Congress call number, and prints 3x5 cards (Avery 5388) in shelf order.
|
||||
|
||||
**Architecture:** One Node process serves a Preact single-page app at `http://localhost:4321`, resolves books against Open Library and the Library of Congress in a background job queue, and stores everything in one SQLite file. Pure logic (ISBN, call numbers, cutters) lives in `src/shared` and is used by both sides. PDFs are drawn server-side at exact coordinates.
|
||||
|
||||
**Tech Stack:** Node 26 running TypeScript directly (type stripping, no build for the server), `node:sqlite`, `node:test`, Hono + `@hono/node-server`, Preact bundled by esbuild, `barcode-detector` (zxing-wasm ponyfill), `pdf-lib` + `@pdf-lib/fontkit` + `dejavu-fonts-ttf`, `fast-xml-parser`.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-18-booksorter-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Runs on one laptop; server binds `127.0.0.1` only, port `4321` (env `PORT` overrides).
|
||||
- No paid services, no API keys, no CDN at runtime (the zxing wasm file is served locally).
|
||||
- No test calls a live service. Network code takes an injected `fetch`.
|
||||
- The user is never asked to pick a classification or choose among candidate numbers. The only user choice among candidates is the title/author search result list.
|
||||
- Node type stripping: erasable TypeScript only (no `enum`, no parameter properties, no namespaces); relative imports carry the `.ts`/`.tsx` extension; type-only imports use `import type`.
|
||||
- Tests are colocated: `foo.ts` → `foo.test.ts`, run with `node --test`.
|
||||
- All outbound requests send `User-Agent: booksorter/0.1 (personal library tool)`.
|
||||
- Database file: `data/booksorter.db` (env `BOOKSORTER_DB` overrides; `:memory:` in tests). `data/` and `dist/` are gitignored.
|
||||
- Card stock: Avery 5388, letter sheet 612 x 792 pt, three cards each 360 pt wide x 216 pt tall on the sheet, left edge x=126, top card's top edge 72 pt below the sheet top, no gaps.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. A title or author containing characters the PDF font lacks (CJK, emoji) must still print: each missing glyph becomes `?`. (Task 4)
|
||||
2. A non-book barcode (a UPC, or an EAN-13 not starting 978/979) or a bad check digit is rejected with a message and a low beep, never added. (Tasks 1, 5)
|
||||
3. An unknown ISBN (Open Library returns `{}`) or a Library of Congress HTML block page ends in "needs attention" or a retry, never a crash, and pending books resume after a restart. (Tasks 2, 3)
|
||||
4. A very long title, twelve authors, or a three-cutter call number must stay inside the card and never push the call number out of the top inch. (Task 4)
|
||||
5. The same ISBN posted twice at the same moment creates one book. (Task 3)
|
||||
6. Printing with an empty queue returns a clear error, and a hand-edited call number that does not parse is kept as typed, sorted last, and flagged. (Tasks 3, 1)
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
package.json tsconfig.json .gitignore README.md
|
||||
scripts/build-web.ts esbuild bundle + copy static files and wasm to dist/web
|
||||
src/shared/types.ts shared types (below)
|
||||
src/shared/isbn.ts validate, convert, normalize
|
||||
src/shared/callnumber.ts parse, display, sort key, card lines
|
||||
src/shared/cutter.ts LC cutter table
|
||||
src/shared/lcc-outline.ts class and subclass names
|
||||
src/server/sources/marc.ts MARCXML -> fields we need
|
||||
src/server/sources/openlibrary.ts
|
||||
src/server/sources/loc.ts SRU + LCCN permalink, throttle, block detection
|
||||
src/server/resolve/choose.ts pure: candidates -> call number
|
||||
src/server/resolve/resolver.ts orchestrates sources, cache
|
||||
src/server/pdf/layout.ts Avery 5388 geometry
|
||||
src/server/pdf/card.ts draw one card in card-local coordinates
|
||||
src/server/pdf/render.ts cards PDF, calibration PDF
|
||||
src/server/db.ts schema + queries
|
||||
src/server/jobs.ts background resolution queue with retries
|
||||
src/server/app.ts Hono routes + SSE
|
||||
src/server/main.ts wiring, static files, listen
|
||||
src/web/index.html styles.css main.tsx api.ts scanner.ts sound.ts
|
||||
src/web/views/Scan.tsx Queue.tsx Catalog.tsx
|
||||
src/web/components/*.tsx
|
||||
```
|
||||
|
||||
## Shared types (`src/shared/types.ts`), created in Task 1
|
||||
|
||||
```ts
|
||||
export type Confidence = 'exact' | 'approximate' | 'manual';
|
||||
export type Status = 'pending' | 'resolved' | 'needs_attention';
|
||||
export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'manual';
|
||||
export interface Book {
|
||||
id: number; 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; printedAt: string | null; createdAt: string; updatedAt: string;
|
||||
}
|
||||
export interface BookMeta {
|
||||
title: string; subtitle?: string; authors: string[]; publisher?: string;
|
||||
year?: number; subjects: string[]; lccn?: string;
|
||||
}
|
||||
export interface Candidate { raw: string; complete?: boolean }
|
||||
export interface SearchResult {
|
||||
title: string; authors: string[]; year?: number; publisher?: string;
|
||||
lccn?: string; lcc: string[];
|
||||
}
|
||||
export interface ResolveInput { isbn13?: string; lccn?: string; title?: string; author?: string; year?: number }
|
||||
export interface Resolution {
|
||||
meta: BookMeta | null;
|
||||
callNumber: string | null; sortKey: string | null;
|
||||
confidence: 'exact' | 'approximate' | null; source: Source | null;
|
||||
dewey: string | null;
|
||||
reason: string | null; // set when callNumber is null
|
||||
}
|
||||
export interface CardData {
|
||||
callNumber: string; className: string | null; subclassName: string | null;
|
||||
title: string; authors: string[]; publisher: string | null; year: number | null;
|
||||
subjects: string[]; isbn13: string | null; approximate: boolean;
|
||||
}
|
||||
export interface Settings { offsetXmm: number; offsetYmm: number }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Scaffold and shared logic
|
||||
|
||||
**Files:** `package.json`, `tsconfig.json`, `.gitignore`, `src/shared/{types,isbn,callnumber,cutter}.ts` and their tests.
|
||||
|
||||
Scaffold: `package.json` (`"type": "module"`, private) with every dependency in Tech Stack installed now, plus dev deps `typescript`, `@types/node`, `esbuild`. Scripts: `test` = `node --test "src/**/*.test.ts"`, `typecheck` = `tsc --noEmit`, `build` = `node scripts/build-web.ts`, `start` = `npm run build && node src/server/main.ts`. `tsconfig.json`: `noEmit`, `strict`, `module`/`moduleResolution` `nodenext`, `allowImportingTsExtensions`, `erasableSyntaxOnly`, `verbatimModuleSyntax`, `jsx: react-jsx`, `jsxImportSource: preact`, `lib` includes `DOM`. Confirm `node --test` runs a `.ts` test before writing more.
|
||||
|
||||
**Produces:**
|
||||
|
||||
```ts
|
||||
// isbn.ts
|
||||
export function normalizeIsbn(input: string): string | null; // -> valid ISBN-13 digits, or null
|
||||
// accepts ISBN-10 or ISBN-13, hyphens/spaces, lowercase x; verifies the check digit;
|
||||
// ISBN-13 must start 978 or 979; ISBN-10 converts with the 978 prefix.
|
||||
|
||||
// callnumber.ts
|
||||
export interface CallNumber {
|
||||
letters: string; number: string; decimal: string; // "QA", "76", "73"
|
||||
cutters: { letter: string; digits: string }[]; // up to 3
|
||||
suffix: string; // "2018", "Har 1998", ""
|
||||
}
|
||||
export function parseCallNumber(raw: string): CallNumber | null;
|
||||
export function formatCallNumber(cn: CallNumber): string;
|
||||
export function sortKey(cn: CallNumber): string;
|
||||
export function sortKeyOfRaw(raw: string): string; // parsed key, or "~" + raw.toUpperCase()
|
||||
export function cardLines(cn: CallNumber): [string, string];
|
||||
export function hasYear(cn: CallNumber): boolean; // suffix contains a 4-digit year 1400-2099
|
||||
export function withYear(cn: CallNumber, year: number): CallNumber; // replaces the year in suffix, or appends it
|
||||
|
||||
// cutter.ts
|
||||
export function cutterFor(name: string): string; // "Klabnik" -> "K53"
|
||||
export function mainEntry(authors: string[], title: string): string; // word to cutter
|
||||
```
|
||||
|
||||
**Call number rules.**
|
||||
- Parse: trim, collapse whitespace. First convert Open Library's padded form `^([A-Z]+)-(\d{4})\.(\d{8})(.*)$` to letters + integer without leading zeros + decimal with trailing zeros removed (dropped when all zero) + rest. Then `^([A-Za-z]{1,3})\s*(\d{1,4})(?:\.(\d+))?(.*)$`. From the rest, take up to three cutters, each `\s*\.?\s*([A-Za-z])(\d+)`; what remains, trimmed, is the suffix with its case preserved. Letters and cutter letters are uppercased. No match returns null.
|
||||
- Format: `letters+number` + `.decimal` when present + `.`+first cutter + each further cutter after a space + space + suffix when present.
|
||||
- Card lines: line 2 is the last cutter plus the suffix (just the suffix when there are no cutters); line 1 is everything before it.
|
||||
- Sort key: `letters.padEnd(3)` + `number.padStart(4,'0')` + `.` + decimal + space + cutter1 + space + cutter2 + space + cutter3 + space + suffix uppercased. A cutter is letter+digits, empty when absent. Digits compare as decimal fractions because each field ends in a space, which sorts below every digit.
|
||||
|
||||
**Cutter rules** (LC cutter table). Normalize the word: NFD, strip diacritics, uppercase, keep A-Z only. Cutter = first letter + a digit for the second letter + a digit for the third letter.
|
||||
- Second letter after an initial vowel: b 2, d 3, l-m 4, n 5, p 6, r 7, s-t 8, u-y 9.
|
||||
- After initial S: a 2, ch 3, e 4, h-i 5, m-p 6, t 7, u 8, w-z 9. (`ch` counts as one unit.)
|
||||
- After initial Qu: a 3, e 4, i 5, o 6, r 7, t 8, y 9. (`Qu` counts as the initial.)
|
||||
- After any other consonant: a 3, e 4, i 5, o 6, r 7, u 8, y 9.
|
||||
- Third letter (expansion): a-d 3, e-h 4, i-l 5, m-o 6, p-s 7, t-v 8, w-z 9.
|
||||
- A letter between two table entries takes the lower entry's digit; a letter before the first entry takes the first entry's digit. No second letter: digit `2`. No third letter: one digit only. A word starting with a digit, or empty: `A12`.
|
||||
- `mainEntry`: first author's surname (text before a comma, else the last word); with no authors, the title minus a leading `A`, `An` or `The`.
|
||||
|
||||
**Tests (exact values):**
|
||||
|
||||
```ts
|
||||
// isbn
|
||||
normalizeIsbn('978-1-59327-828-1') === '9781593278281'
|
||||
normalizeIsbn('0-201-83595-9') === '9780201835953'
|
||||
normalizeIsbn('080442957x') === '9780804429573'
|
||||
normalizeIsbn('9781593278282') === null // bad check digit
|
||||
normalizeIsbn('0123456789012') === null // not 978/979
|
||||
normalizeIsbn('hello') === null
|
||||
|
||||
// callnumber: formatCallNumber(parseCallNumber(x)!)
|
||||
'QA76.73.R87 K53 2018' -> 'QA76.73.R87 K53 2018' lines ['QA76.73.R87', 'K53 2018']
|
||||
'TX719 .C454 2001' -> 'TX719.C454 2001' lines ['TX719', 'C454 2001']
|
||||
'QA76.73.C15K47 1988' -> 'QA76.73.C15 K47 1988'
|
||||
'QA76.73.C15 .K4718 1991' -> 'QA76.73.C15 K4718 1991'
|
||||
'QA-0076.76000000.A65' -> 'QA76.76.A65' lines ['QA76.76', 'A65']
|
||||
'PS-3558.00000000.E63 D8 2005' -> 'PS3558.E63 D8 2005' lines ['PS3558.E63', 'D8 2005']
|
||||
'PZ7.R79835 Har 1998' -> 'PZ7.R79835 Har 1998' lines ['PZ7', 'R79835 Har 1998']
|
||||
'qa76.73.r87 k53 2018' -> 'QA76.73.R87 K53 2018'
|
||||
parseCallNumber('[E]'), ('Fic'), ('813.54'), ('') === null
|
||||
withYear(parse('QA76.73.R87 K53 2018'), 2023) formats 'QA76.73.R87 K53 2023'
|
||||
withYear(parse('QA76.76.A65'), 2018) formats 'QA76.76.A65 2018'
|
||||
|
||||
// sort: shuffling then sorting by sortKeyOfRaw yields exactly this order
|
||||
['PS3558.E63 D8 2005', 'Q175.K95 1996', 'QA9.A5 2001', 'QA76.7.B3 2010',
|
||||
'QA76.73.C15 K47 1988', 'QA76.73.R87 K53 2018', 'QA76.73.R87 K53 2023',
|
||||
'QA76.73.R9 A1 2000', 'QA76.76.A65', 'QA76.76.A65 K53 2018', 'QA76.9.D3 2015',
|
||||
'QA100.S5 1990', 'TX719.C454 2001', 'Fic Tolkien']
|
||||
|
||||
// cutter
|
||||
Klabnik K53, Smith S65, Adams A33, Schmidt S36, Quine Q56, Herbert H47,
|
||||
'Écrivain' E27, Li L5, "O'Brien" O27, '1984' A12, '' A12
|
||||
mainEntry(['Klabnik, Steve'], 'x') === 'Klabnik'
|
||||
mainEntry(['Steve Klabnik'], 'x') === 'Klabnik'
|
||||
mainEntry([], 'The Mythical Man-Month') === 'Mythical Man-Month'
|
||||
```
|
||||
|
||||
Done when `npm test` and `npm run typecheck` pass.
|
||||
|
||||
---
|
||||
|
||||
### Task 1b: Class outline table
|
||||
|
||||
**Files:** `src/shared/lcc-outline.ts`, `src/shared/lcc-outline.test.ts`. Needs nothing from Task 1.
|
||||
|
||||
**Produces:**
|
||||
|
||||
```ts
|
||||
export function classNames(letters: string): { className: string | null; subclassName: string | null };
|
||||
// 'QA' -> { className: 'Science', subclassName: 'Mathematics' }
|
||||
// 'Q' -> { className: 'Science', subclassName: 'Science (General)' }
|
||||
// 'ZZ' -> { className: 'Bibliography. Library science. Information resources (General)', subclassName: null }
|
||||
// 'I' -> { className: null, subclassName: null } (I, O, W, X, Y are unused)
|
||||
```
|
||||
|
||||
Data: all 21 main classes and every subclass in the Library of Congress Classification Outline (`https://www.loc.gov/catdir/cpso/lcco/`), names as LoC words them. Three-letter classes (`KFC`, `DAW`, ...) fall back to their two-letter subclass, then to the main class.
|
||||
|
||||
**Tests:** the four examples above, plus `PS` → American literature, `TX` → Home economics, `BX` → Christian denominations, `KF` → a non-null subclass under `Law`, `E` → `History of the Americas`, `DS` → `Asia`, `TK` → Electrical engineering. Electronics. Nuclear engineering, and a count check that at least 200 subclasses are present.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Sources and resolver
|
||||
|
||||
**Files:** `src/server/sources/{marc,openlibrary,loc}.ts`, `src/server/resolve/{choose,resolver}.ts`, tests, and `src/server/sources/fixtures/`.
|
||||
|
||||
**Consumes:** everything Task 1 produces.
|
||||
|
||||
**Produces:**
|
||||
|
||||
```ts
|
||||
// resolver.ts
|
||||
export class TemporaryError extends Error {}
|
||||
export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void }
|
||||
export interface Resolver {
|
||||
resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise<Resolution>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
export function createResolver(deps: {
|
||||
fetch: typeof fetch; cache: SourceCache;
|
||||
locIntervalMs?: number; // default 6000
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}): Resolver;
|
||||
|
||||
// choose.ts (pure)
|
||||
export interface Tiers { locExact: Candidate[]; olEdition: Candidate[]; locTitle: Candidate[]; olWork: Candidate[] }
|
||||
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;
|
||||
```
|
||||
|
||||
**Endpoints (proven working 2026-11-18):**
|
||||
- Open Library edition: `https://openlibrary.org/api/books?bibkeys=ISBN:{isbn}&jscmd=data&format=json`. Title, `authors[].name`, `publishers[].name`, `publish_date`, `subjects[].name`, `classifications.lc_classifications`, `classifications.dewey_decimal_class`, `identifiers.lccn`. An unknown ISBN returns `{}`.
|
||||
- Open Library work: `https://openlibrary.org/search.json?isbn={isbn}&fields=key,title,author_name,first_publish_year,publisher,ddc,lcc,lccn,subject`. `lcc` values are in the zero-padded form.
|
||||
- Open Library search (for the search form): `search.json?title=&author=&limit=10` with the same fields.
|
||||
- Library of Congress by ISBN: `http://lx2.loc.gov:210/lcdb?version=1.1&operation=searchRetrieve&query=bath.isbn={isbn}&maximumRecords=1&recordSchema=marcxml`. `https://lx2.loc.gov/sru/lcdb` with the same query is the fallback if the first refuses the connection.
|
||||
- Library of Congress by title and author: same, `query=bath.title="{title}" and bath.author="{surname}"`, `maximumRecords=5`.
|
||||
- Library of Congress by LCCN: `https://lccn.loc.gov/{lccn}/marcxml`.
|
||||
- MARC fields: 050 `$a`+`$b` (call number; `complete` is true when `$b` exists), 082 `$a` (Dewey; strip `/`), 245 `$a $b`, 100 `$a`, 700 `$a`, 260 or 264 `$b $c`, 650 `$a`, 010 `$a`. Trim trailing ` /`, `,`, `:`, `.` punctuation from text fields.
|
||||
|
||||
**Resolve order.** Open Library edition first (or work search when the edition is `{}`); call `onMeta` as soon as a title is known. Then Library of Congress by LCCN when one is known, else by ISBN. If no tier-1 or tier-2 candidate parses, query Library of Congress by title and author. Tiers map to the spec's steps 1-4. Metadata merges Open Library edition, then Library of Congress, then Open Library work, first non-empty value per field. Input without an ISBN (`lccn` only, or `title`+`author`) skips the steps that need one. Dewey: first found among LoC, Open Library edition, Open Library work.
|
||||
|
||||
**Choose rules** (within the first tier that has a parseable candidate):
|
||||
1. Parse all; drop unparseable. If any candidate's class is `PZ3` or `PZ4` and another's letters are `P` + a letter other than `Z`, drop the `PZ3`/`PZ4` ones.
|
||||
2. Most frequent formatted value wins; ties go to the longest `cardLines()[0]`, then the lowest sort key.
|
||||
3. Complete = `candidate.complete ?? (hasYear(cn) || cn.cutters.length >= 2)`. If not complete and fewer than 3 cutters: append `cutterFor(mainEntry(authors, title))` as a cutter, then `withYear` when the year is known.
|
||||
4. Tiers `locTitle` and `olWork` are `approximate`, and when the year is known the result gets `withYear(year)`. The other tiers are `exact`.
|
||||
|
||||
**Failure rules.** A Library of Congress response that is not XML containing `searchRetrieveResponse` or `<record` is a block page: throw `TemporaryError` and double the interval (cap 60 s) for later calls. Network errors and 5xx from any source throw `TemporaryError`. A 404 from the LCCN permalink is "not found", not an error. Raw response bodies are cached under `ol-data:{isbn}`, `ol-search:{isbn}`, `loc-isbn:{isbn}`, `loc-lccn:{lccn}`, `loc-title:{title}|{author}`; a cache hit skips the request and the throttle. `resolve` returns `reason` `"Not found in Open Library or the Library of Congress"` when there is no metadata, and `"No Library of Congress number found"` when there is metadata but no number.
|
||||
|
||||
**Fixtures.** Record real responses once with curl (1 s apart) into `fixtures/` for: 9781593278281, 9780201835953, 9780441172719, one ISBN that Open Library does not know, LCCN 88005934, and one title/author query. Hand-write `loc-block.html`.
|
||||
|
||||
**Tests:**
|
||||
|
||||
```ts
|
||||
// choose
|
||||
locExact [{raw:'QA76.73.R87 K53 2018', complete:true}] -> 'QA76.73.R87 K53 2018', exact, loc-isbn
|
||||
olEdition ['QA76.73.C15 K47 1988','QA76.73.C15 .K4718 1991','QA76.73.C15K47 1988'] -> 'QA76.73.C15 K47 1988', exact, ol-edition
|
||||
olEdition ['PZ3.H4186 Du','PS3558.E63 D8 2005'] -> 'PS3558.E63 D8 2005'
|
||||
locTitle ['QA76.73.R87 K53 2018'], year 2023 -> 'QA76.73.R87 K53 2023', approximate, loc-title
|
||||
olWork ['QA-0076.76000000.A65'], authors ['Klabnik, Steve'], year 2018 -> 'QA76.76.A65 K53 2018', approximate, ol-work
|
||||
olEdition ['QA76.A1 2000','QA76.73.R87 K53 2018'] -> 'QA76.73.R87 K53 2018' (tie -> longest line 1)
|
||||
olEdition ['[E]','Fic'] and all else empty -> null
|
||||
// resolver, with a fetch stub serving fixtures
|
||||
resolve({isbn13:'9781593278281'}) -> exact, callNumber starts 'QA76.73.R87', meta.title contains 'Rust', onMeta called before resolve settles
|
||||
unknown ISBN -> meta null, callNumber null, reason 'Not found in Open Library or the Library of Congress'
|
||||
LoC returns loc-block.html -> rejects with TemporaryError
|
||||
second resolve of the same ISBN makes zero fetch calls
|
||||
two different uncached ISBNs -> sleep called with ~locIntervalMs between the LoC requests
|
||||
resolve({lccn:'88005934'}) -> callNumber non-null, source 'loc-lccn'
|
||||
search('mythical man-month','brooks') -> non-empty, first result has a title
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Database, jobs, HTTP API
|
||||
|
||||
**Files:** `src/server/{db,jobs,app,main}.ts`, tests for db, jobs, app.
|
||||
|
||||
**Consumes:** `normalizeIsbn`, `parseCallNumber`, `formatCallNumber`, `sortKeyOfRaw`, `classNames`, `Resolver`, `TemporaryError`, `SourceCache` (Task 2); `renderCardsPdf`, `renderCalibrationPdf` (Task 4). `app.ts` and `jobs.ts` receive these through parameters so their tests use stubs; only `main.ts` imports the real ones.
|
||||
|
||||
**Produces:**
|
||||
|
||||
```ts
|
||||
// db.ts
|
||||
export function openDb(path: string): Db; // creates tables: books, source_cache, settings
|
||||
// Db methods: insertPending(fields), getBook(id), findByIsbn(isbn13), listBooks({filter, q}),
|
||||
// updateBook(id, patch), deleteBook(id), listPendingIds(), getSettings(), putSettings(s), cache: SourceCache
|
||||
// books.isbn13 is UNIQUE (nullable). listBooks orders by sort_key, nulls last, then title.
|
||||
|
||||
// jobs.ts
|
||||
export function createJobs(deps: { db: Db; resolver: Resolver; onChange: (book: Book) => void;
|
||||
retryDelaysMs?: number[] /* default [30000, 120000, 600000] */ }):
|
||||
{ enqueue(id: number): void; resume(): void; idle(): Promise<void> };
|
||||
|
||||
// app.ts
|
||||
export function createApp(deps: { db: Db; jobs; resolver: Resolver;
|
||||
renderCardsPdf; renderCalibrationPdf; }): Hono;
|
||||
```
|
||||
|
||||
**Routes** (JSON unless noted; errors are `{ error: string }` with 400/404):
|
||||
|
||||
| Route | Behaviour |
|
||||
|---|---|
|
||||
| `POST /api/scan {isbn}` | Normalize; invalid → 400 `"Not a valid ISBN"`. Existing → `{book, duplicate:true}`, unchanged. New → pending book, `inQueue` true, title = the ISBN, enqueue → `{book, duplicate:false}`. |
|
||||
| `POST /api/books/lccn {lccn}` | Pending book keyed by LCCN, enqueue. |
|
||||
| `GET /api/search?title=&author=` | `SearchResult[]` from `resolver.search`. |
|
||||
| `POST /api/books/from-search {result}` | Pending book with the result's title, authors, year, lccn; enqueue. |
|
||||
| `POST /api/books/manual {title, authors, year?, publisher?, callNumber?}` | With `callNumber`: resolved, `manual`. Without: pending, enqueue (resolves by title and author). |
|
||||
| `GET /api/books?filter=all\|queue\|attention&q=` | `queue` = `inQueue`; `q` matches title, authors, ISBN, call number. |
|
||||
| `PATCH /api/books/:id` | Editable: title, authors, publisher, year, callNumber. Setting `callNumber` stores the formatted value if it parses, else as typed with status `needs_attention` and reason `"Call number not recognised"`; either way `manualOverride` true, confidence `manual`. |
|
||||
| `DELETE /api/books/:id` | |
|
||||
| `POST /api/books/:id/queue` | `inQueue` true. |
|
||||
| `POST /api/books/:id/retry` | Back to pending, attempts reset, enqueue. Refused (400) when `manualOverride`. |
|
||||
| `GET /api/print.pdf?start=1\|2\|3` | PDF of queued, resolved books in shelf order. Empty → 400 `"Nothing to print"`. Response header `X-Book-Ids` lists the ids included. |
|
||||
| `POST /api/print/confirm {ids}` | `printedAt` now, `inQueue` false. |
|
||||
| `GET /api/calibration.pdf` | |
|
||||
| `GET /api/settings`, `PUT /api/settings` | `Settings`; offsets limited to ±10 mm. |
|
||||
| `GET /api/events` | Server-sent events; `book` event with the Book JSON on every change, `deleted` with `{id}`. |
|
||||
|
||||
**Job rules.** One job at a time. `onMeta` saves title/authors/etc. immediately and emits a change. A `Resolution` with a call number → `resolved`. Without → `needs_attention` with its `reason` (metadata still saved). `TemporaryError` → retry after the next delay; after the last, `needs_attention` with reason `"Lookup failed: " + message`. A book with `manualOverride` keeps its call number; only metadata is filled. `resume()` enqueues every pending book; `main.ts` calls it at startup. The card's `approximate` flag is `confidence === 'approximate'`.
|
||||
|
||||
**main.ts:** open db, real resolver with global `fetch`, jobs, app; serve `dist/web` statics (`/` → `index.html`); listen on `127.0.0.1`; print `Booksorter running at http://localhost:4321`. A port already in use prints a one-line message and exits 1.
|
||||
|
||||
**Tests:** scan valid/invalid/duplicate; two simultaneous scans of one ISBN yield one row; job success, no-number, no-metadata, temporary-failure-then-success (retry delays injected as `[0,0,0]`), failure after all retries, manual override preserved; `resume()` picks up pending rows; PATCH with `'QA76.73.R87 K53 2018'` and with `'shelf by the window'`; listBooks order follows sort key with unparseable last; print with empty queue → 400; print passes cards in shelf order to the stub and honours `start`; confirm clears the queue; settings clamp.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: PDF
|
||||
|
||||
**Files:** `src/server/pdf/{layout,card,render}.ts`, tests.
|
||||
|
||||
**Consumes:** `parseCallNumber`, `cardLines`, `CardData`, `Settings`.
|
||||
|
||||
**Produces:**
|
||||
|
||||
```ts
|
||||
// layout.ts
|
||||
export const SHEET = { width: 612, height: 792 };
|
||||
export const CARD = { width: 216, height: 360 }; // card-local, upright
|
||||
export function cardMatrix(position: 1 | 2 | 3, s: Settings): [number, number, number, number, number, number];
|
||||
// render.ts
|
||||
export function renderCardsPdf(cards: CardData[], opts: Settings & { startPosition: 1 | 2 | 3 }): Promise<Uint8Array>;
|
||||
export function renderCalibrationPdf(s: Settings): Promise<Uint8Array>;
|
||||
// card.ts
|
||||
export interface TextRun { text: string; x: number; y: number; size: number; bold: boolean; gray: number }
|
||||
export function layoutCard(card: CardData, measure: (text: string, size: number, bold: boolean) => number): TextRun[];
|
||||
```
|
||||
|
||||
**Geometry.** Each card is drawn upright in card-local points (origin bottom-left, 216 wide, 360 tall) and placed with a matrix that turns it a quarter turn anticlockwise, so the card's top is toward the sheet's left edge: `[0, 1, -1, 0, 486 + dx, yBottom - dy]`, where `yBottom` is 504, 288, 72 for positions 1, 2, 3, `dx = offsetXmm * 72 / 25.4` (positive moves the print right) and `dy = offsetYmm * 72 / 25.4` (positive moves it down). Use `pushGraphicsState` / `concatTransformationMatrix` / `popGraphicsState`. The first sheet starts at `startPosition`; later sheets at 1.
|
||||
|
||||
**Card content**, top down, side margins 14 pt (starting sizes; adjust for looks while keeping the invariants):
|
||||
- Call number line 1: bold 26 pt, baseline 326, shrunk in 1 pt steps to fit 188 pt, minimum 12.
|
||||
- Call number line 2: bold 20 pt, baseline 300, same shrink rule, minimum 11.
|
||||
- Rule at y 286, 0.75 pt.
|
||||
- Class name then subclass name: 9 pt, gray 0.35, one line each, truncated. Omitted when null; subclass omitted when equal to class.
|
||||
- Title: bold 13 pt, word-wrapped, up to 3 lines; if it needs more, 11 pt; if still more, truncate the third line with `…`.
|
||||
- Authors joined with `, `: 10 pt, up to 2 lines; more than three authors → first three + ` et al.`
|
||||
- Publisher, year: 9 pt, one line.
|
||||
- Up to two subjects: 9 pt, gray 0.35, each up to 2 lines.
|
||||
- `ISBN {isbn13}`: 8 pt at baseline 16. `~` bold 12 pt right-aligned at baseline 16 when `approximate`.
|
||||
- Blocks stack downward from baseline 268 with 8 pt between blocks. A block that would go below y 30 is dropped whole.
|
||||
- Fonts: DejaVu Sans and DejaVu Sans Bold from `dejavu-fonts-ttf`, embedded without subsetting. Before measuring or drawing, replace every character the font has no glyph for with `?`.
|
||||
- An unparseable call number prints whole on line 1 with line 2 empty.
|
||||
|
||||
**Calibration page:** the three card outlines as 0.5 pt rectangles with the same matrices, a small cross at each card centre, and the line `Calibration: hold against an Avery 5388 sheet. Offset X {x} mm, Y {y} mm.` inside card 1.
|
||||
|
||||
**Tests:**
|
||||
- `cardMatrix(1, zero)` = `[0,1,-1,0,486,504]`; position 3 → f = 72; `offsetXmm: 1` adds 72/25.4 to e; `offsetYmm: 1` subtracts it from f.
|
||||
- Mapping the four card-local corners through each matrix gives sheet rectangles x 126..486 and y 504..720, 288..504, 72..288.
|
||||
- `layoutCard` with a fixed-width fake `measure`: both call number runs have baseline ≥ 288 (top inch); every run satisfies 14 ≤ x, x + width ≤ 202, 10 ≤ y ≤ 350; with a 300-character title, the title uses at most 3 runs and the last ends with `…`; twelve authors → text ends with `et al.`; a three-cutter call number shrinks below 26 pt and still fits 188 pt.
|
||||
- `renderCardsPdf` of 4 cards with `startPosition: 3` produces a 2-page PDF (load it back with pdf-lib and count pages); 0 cards rejects; a title of `日本語のタイトル 🙂` renders without throwing.
|
||||
- Render one real sample (the Rust book) to `/tmp` and convert with `pdftoppm -png -r 80` to confirm it is not blank; mention the path in your report.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Web app
|
||||
|
||||
**Files:** `scripts/build-web.ts`, `src/web/**`.
|
||||
|
||||
**Consumes:** the routes in Task 3 (code against the table; the server may not exist yet), `normalizeIsbn`, `parseCallNumber`, `cardLines`, shared types.
|
||||
|
||||
**Build:** `scripts/build-web.ts` bundles `src/web/main.tsx` with esbuild (`jsx: automatic`, `jsxImportSource: preact`, ESM, sourcemap) to `dist/web/app.js`, copies `index.html` and `styles.css`, and copies the zxing reader `.wasm` from `node_modules` to `dist/web/`. Configure the `barcode-detector` ponyfill to load that local file, never a CDN; check the installed version's README for the current override call.
|
||||
|
||||
**Views** (three tabs; plain CSS, system font, works down to 380 px wide, light and dark by `prefers-color-scheme`):
|
||||
|
||||
- **Scan.** Left: live video (shown mirrored with CSS; frames are read unmirrored), a camera picker when more than one video input exists (choice kept in `localStorage`), and a Start/Stop camera button. The ISBN box sits under the video and holds focus; Enter submits. Right: this session's scans, newest first: title (the ISBN until known), call number in two lines, status chip (`Looking up`, `Ready`, `Needs attention` + reason, `Already in catalog` with a `Queue reprint` button). Below: three collapsed forms, `Search by title and author` (results list; click adds), `Enter LCCN`, `Enter by hand` (title, authors, year, call number optional).
|
||||
- **Print queue.** Books queued and ready, in shelf order, with a count and the number of sheets. A start-position picker drawn as a little sheet with three slots. `Make PDF` fetches `/api/print.pdf?start=N`, reads `X-Book-Ids`, opens the PDF in a new tab, then shows `Did the cards print correctly?` with `Yes, clear these from the queue` and `Not yet`. A line of text: `Print at actual size (100%), single-sided, from the manual feed slot.` A `Needs attention` section lists unresolved books with `Retry`, `Edit`, `Delete`. A `Printer alignment` section: offset X and Y in mm (step 0.25) and `Print calibration page`.
|
||||
- **Catalog.** Search box, `Needs attention only` toggle, all books in shelf order: call number, title, authors, year, a `~` for approximate. Clicking a book opens an editor: title, authors, publisher, year, call number (helper text: `Changing this locks the number`), `Save`, `Queue reprint`, `Look up again`, `Delete` (confirm).
|
||||
|
||||
**Scanner (`scanner.ts`):**
|
||||
|
||||
```ts
|
||||
export function startScanner(video: HTMLVideoElement, deviceId: string | undefined,
|
||||
onIsbn: (isbn13: string) => void, onReject: (code: string) => void): Promise<() => void>; // returns stop()
|
||||
export function acceptRead(state: ReadState, code: string, now: number): { state: ReadState; emit: string | null; reject: boolean };
|
||||
```
|
||||
|
||||
`getUserMedia` with `width: {ideal: 1920}`, `height: {ideal: 1080}`. Detect `ean_13` about every 150 ms. `acceptRead` is the pure rule: a code must be read in two consecutive detections to count; one that fails `normalizeIsbn` sets `reject` (once per 5 s per code); an accepted ISBN is not emitted again for 5 s. Sounds (`sound.ts`, Web Audio): 880 Hz for 120 ms on accept, 220 Hz for 200 ms on reject or duplicate. A camera error shows a plain message and leaves the ISBN box usable.
|
||||
|
||||
**Live updates:** one `EventSource('/api/events')` updating a shared book store; all three views read from it. On reconnect, refetch `/api/books`.
|
||||
|
||||
**Tests** (`node --test`, pure parts only): `acceptRead` (single read emits nothing; second consecutive read emits; third does not; emits again after 5 s; a UPC rejects once), the book-store reducer (upsert, delete, shelf-order sort with unparseable last), sheet count (`0→0, 1→1, 3→1, 4→2` with start 1; `3` cards with start 3 → 2 sheets).
|
||||
|
||||
Done when `npm run build` produces `dist/web/{index.html,app.js,styles.css,*.wasm}` and tests and typecheck pass for your files.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Integration and proof
|
||||
|
||||
**Consumes:** everything.
|
||||
|
||||
1. `npm test` and `npm run typecheck` clean across the repo; fix seams between tasks.
|
||||
2. `npm start`; with curl, scan 9781593278281, 9780201835953, 9780441172719 and one unknown ISBN against the live services; wait for resolution; confirm three call numbers and one "needs attention"; fetch `/api/print.pdf?start=1`, convert with `pdftoppm -png -r 100`, and report the PNG path.
|
||||
3. Browser check with Playwright (Firefox): the page loads with no console errors; the three tabs render; typing an ISBN in the box adds a row that reaches `Ready`; the wasm loads from localhost (no request leaves for a CDN); a generated EAN-13 image drawn to a canvas is decoded by the same detector the scanner uses. If Playwright's Firefox cannot be installed, say so and do the checks that remain possible.
|
||||
4. `README.md`: what it is, `npm install`, `npm start`, how to scan, how to print on Avery 5388 (actual size, manual feed, calibration page), where the data lives.
|
||||
@@ -0,0 +1,319 @@
|
||||
# Booksorter design
|
||||
|
||||
Date: 2026-11-18. Status: awaiting approval.
|
||||
|
||||
## Intent
|
||||
|
||||
Steve wants his home bookshelves arranged as topically as they can be. The
|
||||
tool gets him there with the least effort: scan a pile of books with the
|
||||
laptop's camera, print one 3x5 card per book, put each card in its book, and shelve the books
|
||||
in the order the cards say.
|
||||
|
||||
Each card carries one sort number. The tool chooses that number itself. Steve
|
||||
does not want to pick a classification system, choose between candidate
|
||||
numbers, or tune settings. Sane defaults everywhere.
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Pile scanning is fast.** Hold one barcode after another up to the camera.
|
||||
Each scan is acknowledged within about a second, and slow lookups never
|
||||
block the next scan.
|
||||
2. **Every book gets one canonical shelf number, chosen automatically.**
|
||||
3. **Barcodes are not the only way in.** Typed ISBN, title and author search,
|
||||
LCCN, and fully manual entry all work.
|
||||
4. **Scans build a print queue; printing produces a PDF** laid out for Avery
|
||||
5388 (three 3x5 index cards per letter sheet), front side only.
|
||||
5. **A persistent catalog** of every book scanned, viewable in shelf order, so
|
||||
a new book's neighbours on the shelf are visible.
|
||||
|
||||
## Non-goals (first version)
|
||||
|
||||
- Double-sided cards. The front carries everything. A back side may come
|
||||
later as an off-by-default option.
|
||||
- Avery products other than 5388. Templates are data, so adding one later is
|
||||
a small job, but only 5388 ships now. The 10-per-sheet business card
|
||||
(2 x 3.5 inches) is the first one to add afterwards.
|
||||
- Scanning with a phone, or any setup involving two devices. Everything runs
|
||||
on one laptop. Running the whole app on a phone is a possible later step.
|
||||
- Accounts, login, multiple users, cloud hosting.
|
||||
- Printing the Dewey number. It is stored when found, never shown on the card.
|
||||
- Reading the copyright page or cover by OCR.
|
||||
- AI-estimated numbers for books no source knows.
|
||||
- Loan tracking, reading status, ratings, cover images.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
These make the tool a failure even if it technically works:
|
||||
|
||||
- Asking Steve to choose a classification system or pick among candidate
|
||||
numbers during normal scanning.
|
||||
- A scan flow that waits on a network lookup before accepting the next book.
|
||||
- Cards that print out of register with the Avery perforations.
|
||||
- Depending on a paid service or one that needs an API key.
|
||||
|
||||
## Constraints
|
||||
|
||||
- One user, one laptop. The app is opened at `localhost`, where browsers
|
||||
grant camera access with no certificate.
|
||||
- Laptop webcams are often fixed-focus and low resolution, so barcode reading
|
||||
may be finicky. This is the riskiest assumption in the design and must be
|
||||
proven on the real laptop before anything else is built on it. Typed ISBN
|
||||
is always available beside the camera.
|
||||
- The Library of Congress catalog sends no CORS header, so it must be called
|
||||
from a server, not from the browser.
|
||||
- The Library of Congress reportedly blocks clients above roughly 10 requests
|
||||
a minute. A block arrives as an HTML page with status 200.
|
||||
- The printer is a Brother laser. Card stock goes through the manual feed
|
||||
slot, one side only.
|
||||
|
||||
## Approaches
|
||||
|
||||
### Which number is canonical
|
||||
|
||||
Measured on 42 real ISBNs across genres on 2026-11-18:
|
||||
|
||||
| | Dewey | Library of Congress |
|
||||
|---|---|---|
|
||||
| Exact match for the scanned edition | 67% | 83% |
|
||||
| Counting other editions of the same work | 95% | 98% |
|
||||
| What a source returns | topic number only | full call number: class, author cutter, year |
|
||||
|
||||
1. **Library of Congress call number (chosen).** Assigned by the national
|
||||
library to nearly every US-published book, published free, finer-grained
|
||||
than Dewey, and a complete shelf address, so no two books tie. Harder to
|
||||
read than a decimal number.
|
||||
2. **Dewey.** Easier to read. A third of books came back without one, OCLC
|
||||
closed its free lookup in January 2024, and the number stops at the topic,
|
||||
so the rest of the shelf order would have to be invented locally.
|
||||
3. **Dewey when available, LC otherwise.** Two systems cannot share a shelf.
|
||||
|
||||
Steve handed this choice over ("sane defaults"). Claude picked option 1.
|
||||
|
||||
### Where it runs
|
||||
|
||||
1. **A small local app on Steve's laptop (chosen).** One program serves the
|
||||
page at `localhost`, does the lookups, and keeps the catalog in one SQLite
|
||||
file. Something outside the browser is needed for Library of Congress
|
||||
lookups regardless.
|
||||
2. **A hosted static page with the catalog in the phone's browser storage.**
|
||||
Nothing to run, but iOS can evict that storage and printing card stock
|
||||
from a phone is awkward.
|
||||
3. **A hosted app with a cloud database.** Reachable anywhere, at the cost of
|
||||
an account, a login and a deployment for a one-person tool.
|
||||
|
||||
Claude picked option 1. Steve then ruled out any setup that needs a phone and
|
||||
a computer together: one laptop, its own camera.
|
||||
|
||||
## How it works
|
||||
|
||||
### The pieces
|
||||
|
||||
One program on Steve's Linux laptop does three things: serves the web page at
|
||||
`localhost`, looks books up, and stores the catalog in a single SQLite file.
|
||||
Starting it is one command, and it listens only on the laptop itself.
|
||||
|
||||
The page has three views:
|
||||
|
||||
- **Scan.** The camera view beside a running list of this session's scans,
|
||||
with the ISBN box and the other alternate-input forms.
|
||||
- **Print queue.** The books waiting for cards, and the button that makes
|
||||
the PDF.
|
||||
- **Catalog.** Every book in shelf order.
|
||||
|
||||
The page layout should hold up on a narrow screen, so that running the whole
|
||||
thing on a phone later is not ruled out. Nothing else is built for that now.
|
||||
|
||||
### Scanning
|
||||
|
||||
1. The laptop camera reads EAN-13 barcodes continuously. Only codes starting
|
||||
978 or 979 count as ISBNs; the 5-digit price add-on is ignored.
|
||||
2. On a read: a beep and a flash on screen, and the ISBN is recorded at
|
||||
once. The scanner is ready for the next book immediately.
|
||||
3. The same ISBN read again within a few seconds is ignored. An ISBN already
|
||||
in the catalog is not added twice: the page says "already in catalog" and
|
||||
offers to queue a reprint.
|
||||
4. Each book is resolved in the background. The session list shows each scan
|
||||
move from "looking up" to its title and call number, or to "needs
|
||||
attention".
|
||||
|
||||
The ISBN box stays focused while the camera runs, so a typed ISBN, or a USB
|
||||
barcode scanner (which types like a keyboard), works with no mode switch.
|
||||
|
||||
### Alternate input
|
||||
|
||||
For a book whose barcode is missing, covered, or unreadable:
|
||||
|
||||
- **Type the ISBN** (10 or 13 digits, hyphens allowed, check digit verified).
|
||||
- **Search by title and author.** Results list title, author, year and
|
||||
publisher; picking one adds it. This is the one place the user chooses
|
||||
among candidates, because only they can see the book.
|
||||
- **Type the LCCN** printed on the copyright page of older books.
|
||||
- **Enter it by hand.** Title, author, and a call number copied from the
|
||||
copyright page or typed from knowledge.
|
||||
|
||||
### Choosing the number
|
||||
|
||||
For each book the server tries these in order and stops at the first that
|
||||
yields a Library of Congress class:
|
||||
|
||||
| Step | Source | What it gives | Confidence |
|
||||
|---|---|---|---|
|
||||
| 1 | Library of Congress catalog, by ISBN | Full call number for this edition | exact |
|
||||
| 2 | Open Library edition record, by ISBN | Call number for this edition, messier | exact |
|
||||
| 3 | Library of Congress catalog, by title and author | Call number for another edition | approximate |
|
||||
| 4 | Open Library work-level search | Class numbers pooled from all editions | approximate |
|
||||
| 5 | Nothing found | Goes to "needs attention" | none |
|
||||
|
||||
Open Library is also asked first for title, author, publisher, year and
|
||||
subjects, because it answers quickly and lets the page confirm the title
|
||||
within a second or so. If Open Library returns an LCCN, the Library of
|
||||
Congress record is fetched by LCCN instead of by ISBN.
|
||||
|
||||
Rules that keep this automatic:
|
||||
|
||||
- **Several candidates.** Normalize them all, then take the most frequent.
|
||||
Break ties with the most specific (longest class part), then
|
||||
alphabetically. Never ask.
|
||||
- **Class without a cutter.** When a source gives only the class
|
||||
(`QA76.76.A65`), build the rest: an author cutter from the Library of
|
||||
Congress cutter table applied to the author's surname (or the title when
|
||||
there is no author), then the publication year.
|
||||
- **Approximate numbers** come from a different edition, so their year is
|
||||
replaced with this edition's year.
|
||||
- **Legacy fiction classes.** When a record has both an old `PZ3` or `PZ4`
|
||||
number and a literature number (`PR`, `PS` and so on), prefer the
|
||||
literature number.
|
||||
- **Fiction gets no special treatment.** It is shelved by its call number
|
||||
like everything else, which groups it by country and era, then author.
|
||||
- **Dewey** from any source is stored on the book record and otherwise unused.
|
||||
|
||||
Everything fetched from a source is cached in the database, so a book can be
|
||||
re-resolved later without asking the source again. Library of Congress
|
||||
requests go through a throttle (start at one every 6 seconds) and the server
|
||||
detects the HTML block page and backs off.
|
||||
|
||||
### The call number as data
|
||||
|
||||
A call number is parsed into parts: class letters (one to three), class
|
||||
number (integer with optional decimal), up to two cutters (a letter and
|
||||
digits read as a decimal fraction), and a trailing year or volume.
|
||||
|
||||
- **Display form** is normalized: `QA76.73.R87 K53 2018`. The inputs are
|
||||
messy (`TX719 .C454 2001`, `QA76.73.C15K47 1988`, Open Library's
|
||||
zero-padded `QA-0076.76000000.A65`), and all must parse to the same parts.
|
||||
- **Sort key** is derived from the parts so that plain string comparison in
|
||||
the database gives correct shelf order: letters alphabetically, class
|
||||
number numerically, each cutter by letter then by its digits as a decimal
|
||||
(`.R87` before `.R9`), then year.
|
||||
|
||||
A call number that will not parse is kept as typed, sorted after everything
|
||||
else, and flagged for attention.
|
||||
|
||||
### The card
|
||||
|
||||
Avery 5388: letter sheet, three cards, each 5 inches wide by 3 inches tall on
|
||||
the sheet. Believed geometry is 1 inch top and bottom margins, 1.75 inch side
|
||||
margins, no gaps. This must be checked against Avery's published template
|
||||
before the layout code is written.
|
||||
|
||||
The card is read as a bookmark: upright, 3 inches wide and 5 tall, so its
|
||||
content is rotated a quarter turn on the sheet. The call number sits in the
|
||||
top inch, the part that sticks out of the book.
|
||||
|
||||
```
|
||||
┌──────────────────────────┐
|
||||
│ QA76.73.R87 │ class: where on the shelves
|
||||
│ K53 2018 │ cutter and year: which book
|
||||
│ ──────────────────────── │
|
||||
│ Science │
|
||||
│ Mathematics │
|
||||
│ │
|
||||
│ The Rust Programming │
|
||||
│ Language │
|
||||
│ Steve Klabnik, │
|
||||
│ Carol Nichols │
|
||||
│ No Starch Press, 2018 │
|
||||
│ │
|
||||
│ Rust (Computer program │
|
||||
│ language) │
|
||||
│ │
|
||||
│ ISBN 9781593278281 ~ │
|
||||
└──────────────────────────┘
|
||||
```
|
||||
|
||||
- Line 1 is the class part, the largest type on the card. Line 2 is the
|
||||
cutter and year, slightly smaller. Both must be readable in the top inch.
|
||||
- Below the rule: the plain-language names of the main class and subclass,
|
||||
from the Library of Congress outline (a small fixed table, about 220
|
||||
entries, shipped with the app). A class missing from the table leaves
|
||||
these lines blank.
|
||||
- Then title, authors, publisher and year, up to two subject headings, ISBN.
|
||||
- A small `~` in the corner marks an approximate number.
|
||||
- Long titles shrink a step, then truncate with an ellipsis. Nothing ever
|
||||
overflows the card or pushes the call number down.
|
||||
|
||||
### Printing
|
||||
|
||||
- The print queue holds every book scanned and not yet printed. A book in
|
||||
"needs attention" is not in the queue until it has a number; a card is
|
||||
never printed with a placeholder.
|
||||
- The PDF opens in a browser tab, and the print screen says to print at
|
||||
actual size.
|
||||
- "Print" produces a PDF with cards in shelf order, so the stack of cards
|
||||
comes out already sorted.
|
||||
- For a partly used sheet, the user picks which position (1, 2 or 3) the
|
||||
first card starts at.
|
||||
- The PDF is drawn at exact coordinates by the server, not by the browser's
|
||||
print dialog, which scales and adds margins unpredictably. It must be
|
||||
printed at 100% scale.
|
||||
- A calibration page prints the three card outlines on plain paper to hold
|
||||
against an Avery sheet. Horizontal and vertical offset settings, in
|
||||
fractions of a millimetre, correct a printer that shifts the image.
|
||||
- After printing, the user confirms the cards came out, and those books
|
||||
leave the queue. Any book can be queued again from the catalog.
|
||||
|
||||
### Catalog
|
||||
|
||||
A list of every book in shelf order with search by title, author, ISBN or
|
||||
call number. Each book can be edited (including overriding its call number,
|
||||
which marks it manual and stops automatic re-resolution), deleted, or queued
|
||||
for a reprint. A "needs attention" filter shows books without a usable
|
||||
number.
|
||||
|
||||
## Error handling
|
||||
|
||||
- **Lookup fails or a source is down.** The scan is kept and retried with
|
||||
backoff. It never disappears. After retries run out it goes to "needs
|
||||
attention" with the reason.
|
||||
- **No source knows the book.** "Needs attention", with the title and author
|
||||
search and manual entry one tap away.
|
||||
- **The laptop is offline.** Scans are still recorded and resolve when the
|
||||
connection returns.
|
||||
- **The camera will not read a barcode.** Type the ISBN in the box beside it.
|
||||
- **Library of Congress block page.** Detected, treated as a temporary
|
||||
failure, throttle widened.
|
||||
|
||||
## Testing
|
||||
|
||||
- Call-number parsing, normalization and sort order, against a table of real
|
||||
values including every messy form listed above.
|
||||
- Cutter generation against the published examples in the Library of
|
||||
Congress cutter table.
|
||||
- The number-choosing rules, using recorded source responses as fixtures. No
|
||||
test calls a live service.
|
||||
- PDF geometry: card boxes land on the exact coordinates for each start
|
||||
position, and text stays inside its box for very long titles.
|
||||
- ISBN validation and ISBN-10 to ISBN-13 conversion.
|
||||
- One manual end-to-end check with the laptop camera and the real printer.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- Language, framework and libraries. Claude's call is TypeScript throughout
|
||||
(server and web app) with SQLite, unless the machine's installed tooling
|
||||
argues for something else.
|
||||
- The barcode-reading library, provided it works in the laptop's browser and
|
||||
does not rule out phone browsers later.
|
||||
- How the page learns that a background lookup finished (server-sent events,
|
||||
polling, or websockets).
|
||||
- Database schema, API shape, fonts and exact type sizes on the card.
|
||||
- Retry counts and backoff timings.
|
||||
Reference in new issue
Block a user