Scaffold project and add ISBN, call number and cutter logic

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 09:41:43 -07:00
1 parent a2ea154cd8
commit 6a7fcdc4b8
11 files changed
+1492

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
node_modules/
data/
dist/
+1174
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "booksorter",
"version": "0.1.0",
"private": true,
"type": "module",
"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"
},
"dependencies": {
"@hono/node-server": "^2.1.9",
"@pdf-lib/fontkit": "^1.1.1",
"barcode-detector": "^3.2.4",
"dejavu-fonts-ttf": "^2.37.3",
"fast-xml-parser": "^5.12.1",
"hono": "^4.13.19",
"pdf-lib": "^1.17.1",
"preact": "^11.2.0"
},
"devDependencies": {
"@types/node": "^26.6.6",
"esbuild": "^0.28.2",
"typescript": "^7.0.2"
}
}
+56
View File
@@ -0,0 +1,56 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parseCallNumber, formatCallNumber, sortKeyOfRaw, cardLines, withYear, hasYear,
} from './callnumber.ts';
const fmt = (x: string) => formatCallNumber(parseCallNumber(x)!);
test('format', () => {
const cases: [string, string][] = [
['QA76.73.R87 K53 2018', 'QA76.73.R87 K53 2018'],
['TX719 .C454 2001', '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'],
['PS-3558.00000000.E63 D8 2005', 'PS3558.E63 D8 2005'],
['PZ7.R79835 Har 1998', 'PZ7.R79835 Har 1998'],
['qa76.73.r87 k53 2018', 'QA76.73.R87 K53 2018'],
];
for (const [i, o] of cases) assert.equal(fmt(i), o, i);
});
test('card lines', () => {
const lines = (x: string) => cardLines(parseCallNumber(x)!);
assert.deepEqual(lines('QA76.73.R87 K53 2018'), ['QA76.73.R87', 'K53 2018']);
assert.deepEqual(lines('TX719 .C454 2001'), ['TX719', 'C454 2001']);
assert.deepEqual(lines('QA-0076.76000000.A65'), ['QA76.76', 'A65']);
assert.deepEqual(lines('PS-3558.00000000.E63 D8 2005'), ['PS3558.E63', 'D8 2005']);
assert.deepEqual(lines('PZ7.R79835 Har 1998'), ['PZ7', 'R79835 Har 1998']);
});
test('unparseable', () => {
for (const x of ['[E]', 'Fic', '813.54', '']) assert.equal(parseCallNumber(x), null, x);
});
test('year', () => {
assert.equal(formatCallNumber(withYear(parseCallNumber('QA76.73.R87 K53 2018')!, 2023)), 'QA76.73.R87 K53 2023');
assert.equal(formatCallNumber(withYear(parseCallNumber('QA76.76.A65')!, 2018)), 'QA76.76.A65 2018');
assert.equal(hasYear(parseCallNumber('QA76.76.A65')!), false);
assert.equal(hasYear(parseCallNumber('PZ7.R79835 Har 1998')!), true);
});
test('sort order', () => {
const want = ['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'];
const shuffled = [...want];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j]!, shuffled[i]!];
}
const key = (s: string) => sortKeyOfRaw(s);
shuffled.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
assert.deepEqual(shuffled, want);
});
+67
View File
@@ -0,0 +1,67 @@
export interface CallNumber {
letters: string; number: string; decimal: string;
cutters: { letter: string; digits: string }[];
suffix: string;
}
export function parseCallNumber(raw: string): CallNumber | null {
let s = raw.trim().replace(/\s+/g, ' ');
const pad = /^([A-Z]+)-(\d{4})\.(\d{8})(.*)$/.exec(s);
if (pad) {
const dec = pad[3]!.replace(/0+$/, '');
s = pad[1]! + String(Number(pad[2])) + (dec ? '.' + dec : '') + pad[4]!;
}
const m = /^([A-Za-z]{1,3})\s*(\d{1,4})(?:\.(\d+))?(.*)$/.exec(s);
if (!m) return null;
let rest = m[4]!;
const cutters: { letter: string; digits: string }[] = [];
while (cutters.length < 3) {
const c = /^\s*\.?\s*([A-Za-z])(\d+)/.exec(rest);
if (!c) break;
cutters.push({ letter: c[1]!.toUpperCase(), digits: c[2]! });
rest = rest.slice(c[0].length);
}
return {
letters: m[1]!.toUpperCase(), number: String(Number(m[2])), decimal: m[3] ?? '',
cutters, suffix: rest.trim(),
};
}
function base(cn: CallNumber): string {
return cn.letters + cn.number + (cn.decimal ? '.' + cn.decimal : '');
}
function cutterStr(c: { letter: string; digits: string }): string { return c.letter + c.digits; }
export function formatCallNumber(cn: CallNumber): string {
let out = base(cn);
cn.cutters.forEach((c, i) => { out += (i === 0 ? '.' : ' ') + cutterStr(c); });
if (cn.suffix) out += ' ' + cn.suffix;
return out;
}
export function sortKey(cn: CallNumber): string {
const c = (i: number) => (cn.cutters[i] ? cutterStr(cn.cutters[i]!) : '');
return cn.letters.padEnd(3) + cn.number.padStart(4, '0') + '.' + cn.decimal + ' ' +
c(0) + ' ' + c(1) + ' ' + c(2) + ' ' + cn.suffix.toUpperCase();
}
export function sortKeyOfRaw(raw: string): string {
const cn = parseCallNumber(raw);
return cn ? sortKey(cn) : '~' + raw.toUpperCase();
}
export function cardLines(cn: CallNumber): [string, string] {
let line1 = base(cn);
cn.cutters.slice(0, -1).forEach((c, i) => { line1 += (i === 0 ? '.' : ' ') + cutterStr(c); });
const last = cn.cutters[cn.cutters.length - 1];
const line2 = [last ? cutterStr(last) : '', cn.suffix].filter(Boolean).join(' ');
return [line1, line2];
}
const YEAR = /\b(1[4-9]\d\d|20\d\d)\b/;
export function hasYear(cn: CallNumber): boolean { return YEAR.test(cn.suffix); }
export function withYear(cn: CallNumber, year: number): CallNumber {
const suffix = hasYear(cn) ? cn.suffix.replace(YEAR, String(year)) : (cn.suffix ? cn.suffix + ' ' : '') + year;
return { ...cn, cutters: cn.cutters.map((c) => ({ ...c })), suffix };
}
+18
View File
@@ -0,0 +1,18 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cutterFor, mainEntry } from './cutter.ts';
test('cutterFor', () => {
const cases: [string, string][] = [
['Klabnik', 'K53'], ['Smith', 'S65'], ['Adams', 'A33'], ['Schmidt', 'S36'],
['Quine', 'Q56'], ['Herbert', 'H47'], ['Écrivain', 'E27'], ['Li', 'L5'],
["O'Brien", 'O27'], ['1984', 'A12'], ['', 'A12'],
];
for (const [name, want] of cases) assert.equal(cutterFor(name), want, name);
});
test('mainEntry', () => {
assert.equal(mainEntry(['Klabnik, Steve'], 'x'), 'Klabnik');
assert.equal(mainEntry(['Steve Klabnik'], 'x'), 'Klabnik');
assert.equal(mainEntry([], 'The Mythical Man-Month'), 'Mythical Man-Month');
});
+62
View File
@@ -0,0 +1,62 @@
// LC cutter table. Digits for a letter: the entry's own digit, else the lower entry's,
// else (before the first entry) the first entry's.
const VOWEL: Record<string, number> = {
a: 2, b: 2, c: 2, d: 3, e: 3, f: 3, g: 3, h: 3, i: 3, j: 3, k: 3, l: 4, m: 4, n: 5,
o: 5, p: 6, q: 6, r: 7, s: 8, t: 8, u: 9, v: 9, w: 9, x: 9, y: 9, z: 9,
};
const S_TABLE: Record<string, number> = {
a: 2, b: 2, c: 2, d: 3, e: 4, f: 4, g: 4, h: 5, i: 5, j: 5, k: 5, l: 5, m: 6, n: 6,
o: 6, p: 6, q: 6, r: 6, s: 6, t: 7, u: 8, v: 8, w: 9, x: 9, y: 9, z: 9,
};
const QU_TABLE: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 5, n: 5,
o: 6, p: 6, q: 6, r: 7, s: 7, t: 8, u: 8, v: 8, w: 8, x: 8, y: 9, z: 9,
};
const CONSONANT: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 5, n: 5,
o: 6, p: 6, q: 6, r: 7, s: 7, t: 7, u: 8, v: 8, w: 8, x: 8, y: 9, z: 9,
};
const THIRD: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 6, n: 6,
o: 6, p: 7, q: 7, r: 7, s: 7, t: 8, u: 8, v: 8, w: 9, x: 9, y: 9, z: 9,
};
export function cutterFor(name: string): string {
const trimmed = name.trim();
const w = trimmed.normalize('NFD').replace(/[̀-ͯ]/g, '').toUpperCase().replace(/[^A-Z]/g, '').toLowerCase();
if (w === '' || /^\d/.test(trimmed)) return 'A12';
const first = w[0]!;
let table: Record<string, number>;
let rest: string;
let second: number | null;
if ('aeiou'.includes(first)) {
table = VOWEL; rest = w.slice(1);
second = rest ? table[rest[0]!]! : null;
rest = rest.slice(1);
} else if (first === 's') {
rest = w.slice(1);
if (rest.startsWith('ch')) { second = 3; rest = rest.slice(2); }
else { second = rest ? S_TABLE[rest[0]!]! : null; rest = rest.slice(1); }
} else if (first === 'q' && w[1] === 'u') {
rest = w.slice(2);
second = rest ? QU_TABLE[rest[0]!]! : null;
rest = rest.slice(1);
} else {
rest = w.slice(1);
second = rest ? CONSONANT[rest[0]!]! : null;
rest = rest.slice(1);
}
let out = first.toUpperCase() + String(second ?? 2);
if (second !== null && rest) out += String(THIRD[rest[0]!]!);
return out;
}
export function mainEntry(authors: string[], title: string): string {
const a = authors[0]?.trim();
if (a) {
if (a.includes(',')) return a.split(',')[0]!.trim();
const words = a.split(/\s+/);
return words[words.length - 1]!;
}
return title.trim().replace(/^(a|an|the)\s+/i, '');
}
+12
View File
@@ -0,0 +1,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { normalizeIsbn } from './isbn.ts';
test('normalizeIsbn', () => {
assert.equal(normalizeIsbn('978-1-59327-828-1'), '9781593278281');
assert.equal(normalizeIsbn('0-201-83595-9'), '9780201835953');
assert.equal(normalizeIsbn('080442957x'), '9780804429573');
assert.equal(normalizeIsbn('9781593278282'), null);
assert.equal(normalizeIsbn('0123456789012'), null);
assert.equal(normalizeIsbn('hello'), null);
});
+20
View File
@@ -0,0 +1,20 @@
export function normalizeIsbn(input: string): string | null {
const s = input.replace(/[\s-]/g, '').toUpperCase();
if (/^\d{13}$/.test(s)) {
if (!/^97[89]/.test(s)) return null;
let sum = 0;
for (let i = 0; i < 12; i++) sum += Number(s[i]) * (i % 2 === 0 ? 1 : 3);
return (10 - (sum % 10)) % 10 === Number(s[12]) ? s : null;
}
if (/^\d{9}[\dX]$/.test(s)) {
let sum = 0;
for (let i = 0; i < 9; i++) sum += Number(s[i]) * (10 - i);
const last = s[9] === 'X' ? 10 : Number(s[9]);
if ((sum + last) % 11 !== 0) return null;
const body = '978' + s.slice(0, 9);
let sum13 = 0;
for (let i = 0; i < 12; i++) sum13 += Number(body[i]) * (i % 2 === 0 ? 1 : 3);
return body + String((10 - (sum13 % 10)) % 10);
}
return null;
}
+35
View File
@@ -0,0 +1,35 @@
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 }
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"noEmit": true,
"strict": true,
"target": "esnext",
"module": "nodenext",
"moduleResolution": "nodenext",
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"jsx": "react-jsx",
"jsxImportSource": "preact",
"lib": ["esnext", "DOM", "DOM.Iterable"],
"types": ["node"],
"skipLibCheck": true
},
"include": ["src", "scripts"]
}