Files
booksorter/docs/superpowers/plans/2026-11-18-booksorter.md
T
2026-11-18 09:39:28 -07:00

32 KiB

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

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:

// 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):

// 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:

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:

// 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:

// 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:

// 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:

// 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):

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.