Show the edition statement on cards and in the library
The edition comes only from a record for this exact edition: the Library of Congress record's edition statement first, then Open Library's edition name when it is a well-formed statement. Existing books are filled in at startup without changing anything else about them. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
e83774adbd
commit
bb46d343a8
26 files changed
+455
-34
No files matched your search
+15
-2
@@ -17,7 +17,7 @@ function setupRecording(fresh: (boolean | undefined)[]) {
|
||||
function setup(resolve: (i?: any, o?: any) => Promise<Resolution> = async () => found, port?: number) {
|
||||
const db = openDb(':memory:');
|
||||
const events = createEventBus();
|
||||
const resolver = { resolve, tail: async () => [], search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
|
||||
const resolver = { resolve, tail: async () => [], edition: async () => '', search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} });
|
||||
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
|
||||
const app = createApp({
|
||||
@@ -239,7 +239,7 @@ test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', as
|
||||
const dir = mkdtempSync(join(tmpdir(), 'captures-'));
|
||||
try {
|
||||
const db = openDb(':memory:');
|
||||
const resolver = { resolve: async () => found, tail: async () => [], search: async () => [] };
|
||||
const resolver = { resolve: async () => found, tail: async () => [], edition: async () => '', search: async () => [] };
|
||||
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
|
||||
const app = createApp({
|
||||
db, jobs, resolver, capturesDir: join(dir, 'captures'),
|
||||
@@ -312,3 +312,16 @@ test('a cross-origin request that changes state is refused', async () => {
|
||||
assert.equal((await req('POST', '/api/books/manual', { title: 'X' }, { origin: 'http://localhost:4321' })).status, 200);
|
||||
assert.equal(db.listBooks().length, 1);
|
||||
});
|
||||
|
||||
test('PATCH edition: typed text is kept, clearing it means "none" (not "look up again"), and the card gets it', async () => {
|
||||
const { req, db, pdfCalls } = setup();
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 't', status: 'resolved', callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn' });
|
||||
assert.equal(book.edition, null);
|
||||
const a = await (await req('PATCH', `/api/books/${book.id}`, { edition: ' Third edition ' })).json() as any;
|
||||
assert.equal(a.book.edition, 'Third edition');
|
||||
assert.equal((await req('GET', '/api/print.pdf')).status, 200);
|
||||
assert.equal(pdfCalls[0]!.cards[0]!.edition, 'Third edition');
|
||||
const b = await (await req('PATCH', `/api/books/${book.id}`, { edition: '' })).json() as any;
|
||||
assert.equal(b.book.edition, '');
|
||||
assert.equal(db.getBook(book.id)!.edition, '');
|
||||
});
|
||||
+3
-1
@@ -190,6 +190,7 @@ export function createApp(deps: AppDeps): Hono {
|
||||
if (!title) throw new HttpError(400, 'Title is required');
|
||||
const fields: NewBook = {
|
||||
title, authors: strList(b.authors) ?? [], year: yearOf(b.year), publisher: str(b.publisher),
|
||||
edition: str(b.edition) ?? '',
|
||||
};
|
||||
const callNumber = str(b.callNumber);
|
||||
if (callNumber) Object.assign(fields, callNumberFields(callNumber));
|
||||
@@ -223,6 +224,7 @@ export function createApp(deps: AppDeps): Hono {
|
||||
patch.authors = a;
|
||||
}
|
||||
if ('publisher' in b) patch.publisher = b.publisher === null ? null : str(b.publisher);
|
||||
if ('edition' in b) patch.edition = b.edition === null ? '' : (str(b.edition) ?? '');
|
||||
if ('year' in b) {
|
||||
if (b.year !== null && yearOf(b.year) === null) throw new HttpError(400, 'Year must be a number');
|
||||
patch.year = b.year === null ? null : yearOf(b.year);
|
||||
@@ -276,7 +278,7 @@ export function createApp(deps: AppDeps): Hono {
|
||||
return {
|
||||
callNumber: b.callNumber!, hierarchy: hierarchyOf(b.callNumber, b.hierarchyTail),
|
||||
title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: displayAuthors(b.authors), publisher: b.publisher, year: b.year,
|
||||
subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate',
|
||||
edition: b.edition || null, subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate',
|
||||
};
|
||||
});
|
||||
const pdf = await deps.renderCardsPdf(cards, { ...db.getSettings(), startPosition });
|
||||
|
||||
@@ -109,6 +109,12 @@ test('a database made before the hierarchy tail gets the column; old books read
|
||||
assert.equal(before.hierarchyTail, null);
|
||||
assert.equal(before.callNumber, 'GV199.42.U82 G733 1997');
|
||||
assert.deepEqual(db.listTailMissingIds(), [before.id]);
|
||||
assert.equal(before.edition, null); // the edition column was added too; old books read as not looked up
|
||||
assert.deepEqual(db.listEditionMissingIds(), [before.id]);
|
||||
assert.equal(db.updateBook(before.id, { edition: 'Third edition' })!.edition, 'Third edition');
|
||||
assert.equal(db.updateBook(before.id, { edition: '' })!.edition, '');
|
||||
assert.deepEqual(db.listEditionMissingIds(), []);
|
||||
assert.equal(db.updateBook(before.id, { edition: null })!.edition, null);
|
||||
const after = db.updateBook(before.id, { hierarchyTail: ['Utah'] })!;
|
||||
assert.deepEqual(after.hierarchyTail, ['Utah']);
|
||||
assert.equal(after.printedAt, before.printedAt);
|
||||
@@ -132,3 +138,15 @@ test('search finds an inverted stored name by its natural form', () => {
|
||||
assert.equal(db.listBooks({ q: 'allen, steve' }).length, 1);
|
||||
assert.equal(db.listBooks({ q: 'nobody' }).length, 0);
|
||||
});
|
||||
|
||||
test('edition: NULL means not looked up, empty means none, text is kept as given', () => {
|
||||
const db = openDb(':memory:');
|
||||
const a = db.insertPending({ isbn13: '9781593278281', title: 'A', status: 'resolved' }).book;
|
||||
const b = db.insertPending({ isbn13: '9780201835953', title: 'B', status: 'resolved', edition: '' }).book;
|
||||
const c = db.insertPending({ title: 'C', status: 'resolved', edition: '2nd ed.' }).book;
|
||||
assert.equal(a.edition, null);
|
||||
assert.equal(b.edition, '');
|
||||
assert.equal(c.edition, '2nd ed.');
|
||||
assert.deepEqual(db.listEditionMissingIds(), [a.id]);
|
||||
db.close();
|
||||
});
|
||||
+16
-4
@@ -13,7 +13,7 @@ export interface NewBook {
|
||||
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; hierarchyTail?: string[] | null;
|
||||
manualOverride?: boolean; inQueue?: boolean; hierarchyTail?: string[] | null; edition?: string | null;
|
||||
}
|
||||
export type BookPatch = Partial<Omit<Book, 'id' | 'createdAt' | 'updatedAt'>>;
|
||||
export type Filter = 'all' | 'queue' | 'attention';
|
||||
@@ -28,6 +28,8 @@ export interface Db {
|
||||
listPendingIds(): number[];
|
||||
/** Books that are not pending and whose hierarchy tail has not been looked for yet. */
|
||||
listTailMissingIds(): number[];
|
||||
/** Books that are not pending and whose edition has not been looked for yet (NULL). */
|
||||
listEditionMissingIds(): number[];
|
||||
/**
|
||||
* Once per rules version: books with an empty tail (and not hand-entered) go back to "not looked for yet" (NULL),
|
||||
* so the backfill tries them again under newer rules. Returns how many were reset. Nothing but the tail changes.
|
||||
@@ -46,7 +48,7 @@ const COLUMNS: Record<keyof BookPatch, string> = {
|
||||
publisher: 'publisher', year: 'year', subjects: 'subjects', callNumber: 'call_number',
|
||||
sortKey: 'sort_key', confidence: 'confidence', source: 'source', dewey: 'dewey',
|
||||
status: 'status', attentionReason: 'attention_reason', manualOverride: 'manual_override',
|
||||
inQueue: 'in_queue', printedAt: 'printed_at', hierarchyTail: 'hierarchy_tail',
|
||||
inQueue: 'in_queue', printedAt: 'printed_at', hierarchyTail: 'hierarchy_tail', edition: 'edition',
|
||||
};
|
||||
const JSON_FIELDS = new Set(['authors', 'subjects']);
|
||||
const BOOL_FIELDS = new Set(['manualOverride', 'inQueue']);
|
||||
@@ -67,6 +69,7 @@ function toBook(r: Row): Book {
|
||||
attentionReason: r.attention_reason, manualOverride: !!r.manual_override,
|
||||
inQueue: !!r.in_queue, printedAt: r.printed_at, createdAt: r.created_at, updatedAt: r.updated_at,
|
||||
hierarchyTail: r.hierarchy_tail == null ? null : JSON.parse(r.hierarchy_tail),
|
||||
edition: r.edition ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,12 +112,17 @@ export function openDb(path: string): Db {
|
||||
db.exec('ALTER TABLE books ADD COLUMN hierarchy_tail TEXT');
|
||||
}
|
||||
|
||||
// Likewise for the edition statement. NULL: not looked up; '': looked, none found.
|
||||
if (!(db.prepare('PRAGMA table_info(books)').all() as Row[]).some((c) => c.name === 'edition')) {
|
||||
db.exec('ALTER TABLE books ADD COLUMN edition TEXT');
|
||||
}
|
||||
|
||||
const getById = db.prepare('SELECT * FROM books WHERE id = ?');
|
||||
const getByIsbn = db.prepare('SELECT * FROM books WHERE isbn13 = ?');
|
||||
const insert = db.prepare(`INSERT INTO books (isbn13, lccn, title, subtitle, authors, publisher, year,
|
||||
subjects, call_number, sort_key, confidence, source, dewey, status, attention_reason,
|
||||
manual_override, in_queue, created_at, updated_at, hierarchy_tail)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
manual_override, in_queue, created_at, updated_at, hierarchy_tail, edition)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(isbn13) DO NOTHING`);
|
||||
|
||||
const self: Db = {
|
||||
@@ -126,6 +134,7 @@ export function openDb(path: string): Db {
|
||||
f.sortKey ?? null, f.confidence ?? null, f.source ?? null, f.dewey ?? null,
|
||||
f.status ?? 'pending', f.attentionReason ?? null, f.manualOverride ? 1 : 0,
|
||||
(f.inQueue ?? true) ? 1 : 0, now, now, f.hierarchyTail == null ? null : JSON.stringify(f.hierarchyTail),
|
||||
f.edition ?? null,
|
||||
);
|
||||
if (r.changes === 0 && f.isbn13) return { book: self.findByIsbn(f.isbn13)!, created: false };
|
||||
return { book: self.getBook(Number(r.lastInsertRowid))!, created: true };
|
||||
@@ -174,6 +183,9 @@ export function openDb(path: string): Db {
|
||||
listTailMissingIds() {
|
||||
return (db.prepare("SELECT id FROM books WHERE hierarchy_tail IS NULL AND status != 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
|
||||
},
|
||||
listEditionMissingIds() {
|
||||
return (db.prepare("SELECT id FROM books WHERE edition IS NULL AND status != 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
|
||||
},
|
||||
recheckEmptyTails(version) {
|
||||
const key = 'tailRulesVersion';
|
||||
const have = Number((db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined)?.value ?? 0);
|
||||
|
||||
+79
-5
@@ -18,7 +18,7 @@ function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) {
|
||||
const db = openDb(':memory:');
|
||||
const changes: Book[] = [];
|
||||
const logs: string[] = [];
|
||||
const resolver: ResolverLike = { resolve, tail: async () => [], search: async () => [] };
|
||||
const resolver: ResolverLike = { resolve, tail: async () => [], edition: async () => '', search: async () => [] };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: delays, log: (l) => logs.push(l) });
|
||||
return { db, jobs, changes, logs };
|
||||
}
|
||||
@@ -286,7 +286,7 @@ test('tail backfill changes only the tail, emits the update, and never touches s
|
||||
const { db, changes } = setup(async () => found);
|
||||
const resolver: ResolverLike = {
|
||||
resolve: async () => { throw new Error('no lookup'); }, search: async () => [],
|
||||
tail: async (i) => { calls.push(i); return ['Utah', 'Uinta Mountains']; },
|
||||
edition: async () => '', tail: async (i) => { calls.push(i); return ['Utah', 'Uinta Mountains']; },
|
||||
};
|
||||
const j = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0], log: () => {} });
|
||||
const printed = '2026-02-03T00:00:00.000Z';
|
||||
@@ -307,7 +307,7 @@ test('tail backfill changes only the tail, emits the update, and never touches s
|
||||
test('tail backfill: hand entries get [] without asking; every other book is asked, whatever its source', async () => {
|
||||
const { db } = setup(async () => found);
|
||||
const asked: unknown[] = [];
|
||||
const resolver: ResolverLike = { resolve: async () => found, search: async () => [], tail: async (i) => { asked.push(i); return ['X']; } };
|
||||
const resolver: ResolverLike = { resolve: async () => found, search: async () => [], edition: async () => '', tail: async (i) => { asked.push(i); return ['X']; } };
|
||||
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
|
||||
const none = tailBook(db, { title: 'no ids' });
|
||||
const manual = tailBook(db, { isbn13: '9780000000002', manualOverride: true, source: 'manual' });
|
||||
@@ -327,7 +327,7 @@ test('tail rules version: books with [] are checked again once, hand entries and
|
||||
const asked: string[] = [];
|
||||
const resolver: ResolverLike = {
|
||||
resolve: async () => found, search: async () => [],
|
||||
tail: async (i) => { asked.push(i.isbn13 ?? ''); return ['Utah']; },
|
||||
edition: async () => '', tail: async (i) => { asked.push(i.isbn13 ?? ''); return ['Utah']; },
|
||||
};
|
||||
const mk = () => createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
|
||||
const empty = tailBook(db, { isbn13: '9780000000002', hierarchyTail: [] });
|
||||
@@ -357,7 +357,7 @@ test('tail backfill: a temporary failure is retried, then left NULL for the next
|
||||
const logs: string[] = [];
|
||||
const resolver: ResolverLike = {
|
||||
resolve: async () => found, search: async () => [],
|
||||
tail: async (i) => { n++; if (i.isbn13 === '9780000000002') throw new TemporaryError('loc.gov busy'); return []; },
|
||||
edition: async () => '', tail: async (i) => { n++; if (i.isbn13 === '9780000000002') throw new TemporaryError('loc.gov busy'); return []; },
|
||||
};
|
||||
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0, 0], isTemporary: (e) => e instanceof TemporaryError, log: (l) => logs.push(l) });
|
||||
const busy = tailBook(db, { isbn13: '9780000000002' });
|
||||
@@ -370,3 +370,77 @@ test('tail backfill: a temporary failure is retried, then left NULL for the next
|
||||
assert.equal(n, 4); // busy: first try and two retries; empty: once
|
||||
assert.ok(logs.some((l) => l.includes('left for the next start')));
|
||||
});
|
||||
|
||||
// The edition backfill.
|
||||
function editionSetup(edition: ResolverLike['edition']) {
|
||||
const { db } = setup(async () => found);
|
||||
const changes: Book[] = [];
|
||||
const logs: string[] = [];
|
||||
const resolver: ResolverLike = { resolve: async () => { throw new Error('no lookup'); }, search: async () => [], tail: async () => [], edition };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0], log: (l) => logs.push(l), isTemporary: (e) => e instanceof TemporaryError });
|
||||
return { db, jobs, changes, logs };
|
||||
}
|
||||
|
||||
test('a lookup sets the edition of a book not looked up yet; "look up again" replaces it, but never with nothing', async () => {
|
||||
const a = setup(async () => ({ ...found, edition: 'Third edition' }));
|
||||
const x = a.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book;
|
||||
a.jobs.enqueue(x.id);
|
||||
await a.jobs.idle();
|
||||
assert.equal(a.db.getBook(x.id)!.edition, 'Third edition');
|
||||
// A normal lookup leaves a value (for example one typed by hand) alone.
|
||||
a.db.updateBook(x.id, { edition: 'By hand', status: 'pending' });
|
||||
a.jobs.enqueue(x.id);
|
||||
await a.jobs.idle();
|
||||
assert.equal(a.db.getBook(x.id)!.edition, 'By hand');
|
||||
a.db.updateBook(x.id, { status: 'pending' });
|
||||
a.jobs.enqueue(x.id, { fresh: true });
|
||||
await a.jobs.idle();
|
||||
assert.equal(a.db.getBook(x.id)!.edition, 'Third edition');
|
||||
const b = setup(async () => ({ ...found, edition: null }));
|
||||
const y = b.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book;
|
||||
b.jobs.enqueue(y.id);
|
||||
await b.jobs.idle();
|
||||
assert.equal(b.db.getBook(y.id)!.status, 'resolved');
|
||||
assert.equal(b.db.getBook(y.id)!.edition, null); // unknown: the backfill asks later
|
||||
});
|
||||
|
||||
test('edition backfill fills only NULL rows and changes nothing else about the book', async () => {
|
||||
const asked: unknown[] = [];
|
||||
const { db, jobs, changes } = editionSetup(async (i) => { asked.push(i); return 'Third edition'; });
|
||||
const printed = '2026-02-03T00:00:00.000Z';
|
||||
const b = tailBook(db, { isbn13: '9781593278281', hierarchyTail: ['Utah'] });
|
||||
db.updateBook(b.id, { printedAt: printed, inQueue: true, confidence: 'approximate' });
|
||||
const typed = tailBook(db, { isbn13: '9780000000002', edition: 'By hand' });
|
||||
const none = tailBook(db, { isbn13: '9780000000019', edition: '' });
|
||||
const noIds = tailBook(db, { title: 'no ids' });
|
||||
const pending = db.insertPending({ isbn13: '9780000000026', title: 'p' }).book;
|
||||
const before = db.getBook(b.id)!;
|
||||
jobs.resumeEditions();
|
||||
await jobs.idle();
|
||||
const after = db.getBook(b.id)!;
|
||||
assert.equal(after.edition, 'Third edition');
|
||||
for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'attentionReason', 'inQueue', 'printedAt', 'manualOverride', 'hierarchyTail', 'title', 'publisher', 'year'] as const) {
|
||||
assert.deepEqual(after[k], before[k], k);
|
||||
}
|
||||
assert.equal(db.getBook(typed.id)!.edition, 'By hand');
|
||||
assert.equal(db.getBook(none.id)!.edition, '');
|
||||
assert.equal(db.getBook(noIds.id)!.edition, ''); // neither ISBN nor LCCN: nothing to ask
|
||||
assert.equal(db.getBook(pending.id)!.edition, null); // the lookup will set it
|
||||
assert.deepEqual(asked, [{ isbn13: '9781593278281', lccn: null }]);
|
||||
assert.ok(changes.some((c) => c.id === b.id));
|
||||
});
|
||||
|
||||
test('edition backfill: a network failure leaves NULL (retried next start), and a later answer is not overwritten if typed meanwhile', async () => {
|
||||
let down = true;
|
||||
const { db, jobs, logs } = editionSetup(async () => { if (down) throw new TemporaryError('Library of Congress timed out'); return 'Second edition'; });
|
||||
const b = tailBook(db, { isbn13: '9781593278281' });
|
||||
jobs.resumeEditions();
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(b.id)!.edition, null);
|
||||
assert.ok(logs.some((l) => l.includes('left for the next start')));
|
||||
assert.deepEqual(db.listEditionMissingIds(), [b.id]);
|
||||
down = false;
|
||||
jobs.resumeEditions();
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(b.id)!.edition, 'Second edition');
|
||||
});
|
||||
+58
-7
@@ -21,6 +21,12 @@ export interface Jobs {
|
||||
* changes). Books that cannot have one get [] at once; a temporary failure leaves NULL for the next start.
|
||||
*/
|
||||
resumeTails(): void;
|
||||
/**
|
||||
* Backfill, for books made before the edition statement was collected: look up only the edition (nothing else about
|
||||
* the book changes, and a hand-typed edition is never touched: only NULL rows are filled). A book with neither ISBN
|
||||
* nor LCCN gets '' at once; a temporary failure leaves NULL for the next start.
|
||||
*/
|
||||
resumeEditions(): void;
|
||||
idle(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -57,6 +63,8 @@ export function createJobs(deps: {
|
||||
// The tail backfill queues behind real lookups, and retries on its own timers.
|
||||
const tailQueue: number[] = [];
|
||||
const tailAttempts = new Map<number, number>();
|
||||
const editionQueue: number[] = [];
|
||||
const editionAttempts = new Map<number, number>();
|
||||
let running: Promise<void> | null = null;
|
||||
let idlers = 0;
|
||||
let wake: (() => void)[] = [];
|
||||
@@ -113,15 +121,22 @@ export function createJobs(deps: {
|
||||
let similar = '';
|
||||
const took = () => `${Date.now() - started} ms`;
|
||||
try {
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, fresh: fresh.has(id), onSimilar: (d) => { similar = d; } });
|
||||
const wasFresh = fresh.has(id);
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, fresh: wasFresh, onSimilar: (d) => { similar = d; } });
|
||||
attempts.delete(id); fresh.delete(id);
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
if (res.meta) applyMeta(id, res.meta);
|
||||
const dewey = res.dewey ?? cur.dewey ?? undefined;
|
||||
const tail = res.tail !== undefined && res.tail !== null ? { hierarchyTail: res.tail } : {};
|
||||
const tail: Parameters<Db['updateBook']>[1] = res.tail !== undefined && res.tail !== null ? { hierarchyTail: res.tail } : {};
|
||||
// The edition: a normal lookup fills only a book not looked up yet (NULL); "Look up again" replaces it with
|
||||
// what the catalogue says now, but never erases a value with "none".
|
||||
if (res.edition !== undefined && res.edition !== null) {
|
||||
if (cur.edition === null) tail.edition = res.edition;
|
||||
else if (wasFresh && res.edition !== '') tail.edition = res.edition;
|
||||
}
|
||||
if (cur.manualOverride) {
|
||||
emit(id, { dewey, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}) });
|
||||
emit(id, { dewey, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}), ...(tail.edition !== undefined ? { edition: tail.edition } : {}) });
|
||||
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
|
||||
} else if (res.callNumber) {
|
||||
emit(id, {
|
||||
@@ -191,22 +206,54 @@ export function createJobs(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
async function backfillEdition(id: number): Promise<void> {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.edition !== null || book.status === 'pending') { editionAttempts.delete(id); return; }
|
||||
const label = book.isbn13 ?? book.lccn ?? book.title;
|
||||
// Only the edition column is ever written here.
|
||||
if (!book.isbn13 && !book.lccn) { editionAttempts.delete(id); emit(id, { edition: '' }); return; }
|
||||
const n = editionAttempts.get(id) ?? 0;
|
||||
try {
|
||||
const edition = await resolver.edition({ isbn13: book.isbn13, lccn: book.lccn });
|
||||
editionAttempts.delete(id);
|
||||
// The row may have been edited by hand while the catalogue was asked: only fill it if it is still NULL.
|
||||
if (db.getBook(id)?.edition === null) emit(id, { edition });
|
||||
log(`[edition] ${label}: ${edition || 'none'}`);
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
if (isTemporary(e) && n < delays.length) {
|
||||
editionAttempts.set(id, n + 1);
|
||||
const delay = delays[n]!;
|
||||
log(`[edition] ${label}: ${message}; trying again in ${Math.round(delay / 1000)} s`);
|
||||
const t = setTimeout(() => { waiting.delete(-1_000_000_000 - id); editionQueue.push(id); start(); notify(); }, delay);
|
||||
if (idlers === 0) t.unref();
|
||||
waiting.set(-1_000_000_000 - id, t);
|
||||
return;
|
||||
}
|
||||
editionAttempts.delete(id);
|
||||
log(`[edition] ${label}: left for the next start, ${message}`); // NULL stays: the next start tries again
|
||||
}
|
||||
}
|
||||
|
||||
async function drain(): Promise<void> {
|
||||
while (queue.length || tailQueue.length) {
|
||||
while (queue.length || tailQueue.length || editionQueue.length) {
|
||||
if (queue.length) {
|
||||
const id = queue.shift()!;
|
||||
queued.delete(id);
|
||||
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
|
||||
} else {
|
||||
} else if (tailQueue.length) {
|
||||
const id = tailQueue.shift()!;
|
||||
try { await backfillTail(id); } catch { /* ditto */ }
|
||||
} else {
|
||||
const id = editionQueue.shift()!;
|
||||
try { await backfillEdition(id); } catch { /* ditto */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
if (running) return;
|
||||
running = drain().finally(() => { running = null; if (queue.length || tailQueue.length) start(); notify(); });
|
||||
running = drain().finally(() => { running = null; if (queue.length || tailQueue.length || editionQueue.length) start(); notify(); });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -227,11 +274,15 @@ export function createJobs(deps: {
|
||||
for (const id of db.listTailMissingIds()) if (!tailQueue.includes(id)) tailQueue.push(id);
|
||||
start();
|
||||
},
|
||||
resumeEditions() {
|
||||
for (const id of db.listEditionMissingIds()) if (!editionQueue.includes(id)) editionQueue.push(id);
|
||||
start();
|
||||
},
|
||||
async idle() {
|
||||
idlers++;
|
||||
for (const t of waiting.values()) t.ref();
|
||||
try {
|
||||
while (running || queue.length || tailQueue.length || waiting.size) {
|
||||
while (running || queue.length || tailQueue.length || editionQueue.length || waiting.size) {
|
||||
if (running) await running;
|
||||
else await new Promise<void>((r) => { wake.push(r); });
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ const server = serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
|
||||
console.log(`Booksorter running at http://localhost:${port}`);
|
||||
jobs.resume();
|
||||
jobs.resumeTails();
|
||||
jobs.resumeEditions();
|
||||
});
|
||||
server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
if (err.code === 'EADDRINUSE') console.error(`Port ${port} is already in use. Is Booksorter already running?`);
|
||||
|
||||
@@ -7,7 +7,7 @@ const measure = (t: string, size: number, _b: boolean) => Array.from(t).length *
|
||||
const base: CardData = {
|
||||
callNumber: 'QA76.73.R87 K53 2018', hierarchy: { outline: ['Science', 'Mathematics'], tail: [] },
|
||||
title: 'The Rust Programming Language', authors: ['Steve Klabnik', 'Carol Nichols'],
|
||||
publisher: 'No Starch Press', year: 2018, subjects: ['Rust (Computer program language)'],
|
||||
publisher: 'No Starch Press', year: 2018, edition: null, subjects: ['Rust (Computer program language)'],
|
||||
isbn13: '9781593278281', approximate: true,
|
||||
};
|
||||
/** The text runs only; the tree and rule are tested through layout() itself. */
|
||||
@@ -215,3 +215,18 @@ test('worst case: five levels with one wrapped, 3-line title, two authors fits a
|
||||
const ruleToTitleTop = l.ruleY! - 18;
|
||||
assert.ok(ruleToTitleTop > 24);
|
||||
});
|
||||
|
||||
test('the publisher line: edition first, then publisher and year; just the edition when it stands alone', () => {
|
||||
const line = (c: Partial<CardData>) => {
|
||||
const runs = layoutCard({ ...base, ...c }, measure).filter((r) => r.size === 9 && !r.bold && !r.text.startsWith('ISBN'));
|
||||
return runs.map((r) => r.text);
|
||||
};
|
||||
assert.deepEqual(line({}), ['No Starch Press, 2018']);
|
||||
assert.deepEqual(line({ edition: 'Third edition' }), ['Third edition · No Starch Press, 2018']);
|
||||
assert.deepEqual(line({ edition: 'Third edition', publisher: null, year: null }), ['Third edition']);
|
||||
assert.deepEqual(line({ edition: 'Third edition', publisher: null }), ['Third edition · 2018']);
|
||||
assert.deepEqual(line({ publisher: null, year: null }), []);
|
||||
const long = line({ edition: 'A very long edition statement '.repeat(4) });
|
||||
assert.equal(long.length, 1);
|
||||
assert.ok(long[0]!.endsWith('…'));
|
||||
});
|
||||
@@ -159,7 +159,9 @@ function whatBlocks(card: CardData, measure: Measure): { required: Block[]; publ
|
||||
const list = card.authors.length > 3 ? card.authors.slice(0, 3).join(', ') + ' et al.' : card.authors.join(', ');
|
||||
required.push({ size: 10, bold: false, gray: 0, lines: wrapLimited(list, 10, false, 2, measure).lines });
|
||||
}
|
||||
const pub = [card.publisher, card.year != null ? String(card.year) : null].filter(Boolean).join(', ');
|
||||
// Citation order: edition, then publisher and year. "Third edition · Wilderness Press, 2019".
|
||||
const imprint = [card.publisher, card.year != null ? String(card.year) : null].filter(Boolean).join(', ');
|
||||
const pub = [card.edition, imprint].filter(Boolean).join(' · ');
|
||||
return { required, publisher: pub ? { size: 9, bold: false, gray: 0, lines: [truncate(pub, 9, false, measure)] } : null };
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ const zero = { offsetXmm: 0, offsetYmm: 0, rotationDeg: 0 };
|
||||
const card: CardData = {
|
||||
callNumber: 'QA76.73.R87 K53 2018', hierarchy: { outline: ['Science', 'Mathematics'], tail: [] },
|
||||
title: 'The Rust Programming Language', authors: ['Steve Klabnik'], publisher: 'No Starch Press',
|
||||
year: 2018, subjects: [], isbn13: null, approximate: false,
|
||||
year: 2018, subjects: [], isbn13: null, approximate: false, edition: null,
|
||||
};
|
||||
|
||||
test('4 cards starting at position 3 make 2 pages', async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
||||
import { normalizeTitle, recordMatches, titlesMatch } from './match.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [], isbns: [], subjectTail: [] });
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [], isbns: [], subjectTail: [], edition: null });
|
||||
|
||||
test('normalizeTitle', () => {
|
||||
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
|
||||
|
||||
@@ -492,7 +492,7 @@ test('tail: records from the similar-books searches count only with the book\'s
|
||||
test('tail: similar-search records give what the works share, never more; one work gives its first element only', async () => {
|
||||
const rec = (title: string, tail: string[], raw = 'GV199.42.U82 X1') => ({
|
||||
lccn: null, lcc: [{ raw, complete: true }], dewey: null,
|
||||
meta: { title, authors: [], subjects: [] }, names: [], topics: [], isbns: [], subjectTail: tail,
|
||||
meta: { title, authors: [], subjects: [] }, names: [], topics: [], isbns: [], subjectTail: tail, edition: null,
|
||||
});
|
||||
const { commonTail } = await import('./tail.ts');
|
||||
const K = 'GV199.42.U82';
|
||||
@@ -508,3 +508,70 @@ test('tail: similar-search records give what the works share, never more; one wo
|
||||
assert.equal(commonTail('GV199.42.W82', [rec('A', ['Utah'])]), null);
|
||||
assert.equal(commonTail(K, [rec('A', [])]), null);
|
||||
});
|
||||
|
||||
// The edition statement: only from a record for this exact edition.
|
||||
const olIsbn = (f: ReturnType<typeof fixtureFetch>, byIsbn: Record<string, string>): typeof fetch =>
|
||||
(async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const m = /openlibrary\.org\/isbn\/(\d+)\.json/.exec(String(input));
|
||||
if (m && byIsbn[m[1]!] !== undefined) return new Response(JSON.stringify({ key: '/books/OL1M', edition_name: byIsbn[m[1]!] }));
|
||||
return f.fetch(input as string, init);
|
||||
}) as typeof fetch;
|
||||
|
||||
test('edition comes from the Library of Congress record fetched by the ISBN', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: olIsbn(f, { '9780201835953': 'Open Library edition' }), cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780201835953' });
|
||||
assert.equal(res.edition, 'Anniversary ed.'); // the Library of Congress wins over Open Library
|
||||
});
|
||||
|
||||
test('edition comes from an LCCN record only when it lists the book\'s ISBN', async () => {
|
||||
const f = fixtureFetch();
|
||||
const isbnMiss = (async (input: string | URL | Request, init?: RequestInit) =>
|
||||
decodeURIComponent(String(input)).includes('bath.isbn') ? new Response('<searchRetrieveResponse></searchRetrieveResponse>') : f.fetch(input as string, init)) as typeof fetch;
|
||||
const mine = await createResolver({ fetch: isbnMiss, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780201835953', lccn: '94036653' });
|
||||
assert.equal(mine.edition, 'Anniversary ed.');
|
||||
});
|
||||
|
||||
test('edition is never taken from another edition\'s LCCN record, a title match or similar books', async () => {
|
||||
const f = fixtureFetch();
|
||||
// LCCN 96067014 is the 1996 edition ("1st ed."); its 020 does not list this ISBN.
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: UTAH_BYWAYS, lccn: '96067014' });
|
||||
assert.equal(res.edition, '');
|
||||
const none = await createResolver({ fetch: fixtureFetch().fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
|
||||
assert.equal(none.edition, '');
|
||||
});
|
||||
|
||||
test('edition falls back to Open Library\'s edition record when the Library of Congress has none', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: olIsbn(f, { '9781593278281': 'Second edition.' }), cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
|
||||
assert.equal(res.edition, 'Second edition');
|
||||
});
|
||||
|
||||
test('edition stays unknown (null) when the Library of Congress could not be asked and had none', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' }, { tolerateLocFailure: true });
|
||||
assert.equal(res.edition, null);
|
||||
});
|
||||
|
||||
test('a fresh lookup also sets the edition, from a new answer rather than the cache', async () => {
|
||||
const f = fixtureFetch();
|
||||
const cache = memCache();
|
||||
const r = createResolver({ fetch: f.fetch, cache, sleep: noSleep });
|
||||
assert.equal((await r.resolve({ isbn13: '9780201835953' })).edition, 'Anniversary ed.');
|
||||
const n = f.calls.length;
|
||||
const again = await r.resolve({ isbn13: '9780201835953' }, { fresh: true });
|
||||
assert.equal(again.edition, 'Anniversary ed.');
|
||||
assert.ok(f.calls.length > n);
|
||||
});
|
||||
|
||||
test('edition(): same rules without a lookup; cached answers; nothing to ask without an ISBN or LCCN', async () => {
|
||||
const f = fixtureFetch();
|
||||
const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep });
|
||||
assert.equal(await r.edition({ isbn13: '9780201835953' }), 'Anniversary ed.');
|
||||
const n = f.calls.length;
|
||||
assert.equal(await r.edition({ isbn13: '9780201835953' }), 'Anniversary ed.');
|
||||
assert.equal(f.calls.length, n);
|
||||
assert.equal(await r.edition({ isbn13: UTAH_BYWAYS, lccn: '96067014' }), ''); // another edition's LCCN record
|
||||
assert.equal(await r.edition({ lccn: '88005934' }), '2nd ed.'); // no ISBN: the LCCN is its own identifier
|
||||
assert.equal(await r.edition({}), '');
|
||||
await assert.rejects(createResolver({ fetch: locDown(fixtureFetch()), cache: memCache(), sleep: noSleep }).edition({ isbn13: '9781593278281' }), TemporaryError);
|
||||
});
|
||||
@@ -47,6 +47,12 @@ export interface Resolver {
|
||||
* [] when there is none; throws TemporaryError when the catalogue cannot be asked.
|
||||
*/
|
||||
tail(input: TailInput, opts?: { onTailSource?: (s: TailSource) => void }): Promise<string[]>;
|
||||
/**
|
||||
* Only the edition statement of a book already in the library, from records for this exact edition (see
|
||||
* editionOf). '' when there is none; throws TemporaryError when a catalogue could not be asked, so the caller
|
||||
* can try again later. Same rate limit and cache as a lookup.
|
||||
*/
|
||||
edition(input: { isbn13?: string | null; lccn?: string | null }): Promise<string>;
|
||||
}
|
||||
|
||||
type Partials = (Partial<BookMeta> | null | undefined)[];
|
||||
@@ -160,6 +166,14 @@ export function createResolver(deps: {
|
||||
lccnOtherCands = lccOf(others);
|
||||
}
|
||||
|
||||
// The edition statement may only come from a record for this exact edition: the record fetched by the ISBN, or
|
||||
// the LCCN record that lists this ISBN (or any LCCN record when the book has no ISBN). Never from a title match,
|
||||
// a work-level record, another edition or the similar-books search. The Library of Congress first, then Open
|
||||
// Library's edition record. null (unknown, asked again later) when the Library of Congress failed and had none.
|
||||
let edit: string | null = locRecs.find((r) => r.edition)?.edition ?? null;
|
||||
if (edit === null && isbn && !locError) edit = (await ol.editionName(isbn)) ?? '';
|
||||
else if (edit === null && !isbn && !locError) edit = '';
|
||||
|
||||
const olEditionCands: Candidate[] = edition?.lcc ?? [];
|
||||
const metaOf = (extra: Partials = []): BookMeta | null =>
|
||||
mergeMeta([edition?.meta, locRecs[0]?.meta, ...extra, input.title ? { title: input.title } : null]);
|
||||
@@ -294,14 +308,14 @@ export function createResolver(deps: {
|
||||
if (chosen) {
|
||||
return {
|
||||
meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey,
|
||||
confidence: chosen.confidence, source: chosen.source, dewey, tail, reason: null,
|
||||
confidence: chosen.confidence, source: chosen.source, dewey, tail, edition: edit, reason: null,
|
||||
};
|
||||
}
|
||||
// Open Library had nothing and the LoC could not be asked: report that, not "no number found".
|
||||
if (locError) throw locError;
|
||||
if (olError) throw olError;
|
||||
return {
|
||||
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey, tail,
|
||||
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey, tail, edition: edit,
|
||||
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
|
||||
};
|
||||
}
|
||||
@@ -363,5 +377,18 @@ export function createResolver(deps: {
|
||||
}, (fn) => fn(), opts?.onTailSource);
|
||||
}
|
||||
|
||||
return { resolve, tail, search: (title, author) => ol.search(title, author) };
|
||||
async function edition(input: { isbn13?: string | null; lccn?: string | null }): Promise<string> {
|
||||
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
|
||||
if (!isbn && !input.lccn) return '';
|
||||
let found: string | null = null;
|
||||
if (isbn) found = (await loc.byIsbn(isbn)).find((r) => r.edition)?.edition ?? null;
|
||||
if (found === null && input.lccn) {
|
||||
// Same edition only if the book has no ISBN or the record lists this ISBN.
|
||||
found = (await loc.byLccn(input.lccn)).filter((r) => !isbn || r.isbns.includes(isbn)).find((r) => r.edition)?.edition ?? null;
|
||||
}
|
||||
if (found === null && isbn) found = await ol.editionName(isbn);
|
||||
return found ?? '';
|
||||
}
|
||||
|
||||
return { resolve, tail, edition, search: (title, author) => ol.search(title, author) };
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').r
|
||||
|
||||
function pick(u: URL, locOverride: string | null): string | null {
|
||||
if (u.hostname === 'openlibrary.org') {
|
||||
const m = /^\/isbn\/(\d+)\.json$/.exec(u.pathname);
|
||||
if (m) return `ol-isbn-${m[1]}.json`;
|
||||
if (u.pathname === '/api/books') return `ol-data-${u.searchParams.get('bibkeys')!.replace('ISBN:', '')}.json`;
|
||||
const kw = u.searchParams.get('q');
|
||||
if (kw) return `ol-similar-${slug(kw)}.json`; // keyword search for the similar-books tier
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"key": "/books/OL26740375M", "type": {"key": "/type/edition"}, "title": "The Rust Programming Language", "publish_date": "2018", "isbn_13": ["9781593278281"], "revision": 3}
|
||||
@@ -125,3 +125,41 @@ test('names: personal names with indicator 1 are put in natural order, others ar
|
||||
assert.deepEqual(rec(g('700', '1', 'Secor, R. J.,') ).meta.authors, ['R. J. Secor']);
|
||||
assert.deepEqual(rec(g('700', '3', 'Sierra Club, Angeles Chapter')).meta.authors, ['Sierra Club, Angeles Chapter']);
|
||||
});
|
||||
|
||||
const withEdition = (a: string | null) => `<record xmlns="http://www.loc.gov/MARC21/slim"><leader>00000nam a2200000 a 4500</leader>
|
||||
<datafield tag="245" ind1="1" ind2="0"><subfield code="a">T /</subfield></datafield>
|
||||
${a === null ? '' : `<datafield tag="250" ind1=" " ind2=" "><subfield code="a">${a}</subfield><subfield code="b">revised by Someone.</subfield></datafield>`}</record>`;
|
||||
const editionOf = (a: string | null) => parseMarcXml(withEdition(a))[0]!.edition;
|
||||
|
||||
test('edition: 250 $a only, wording untouched, closing punctuation cleaned', () => {
|
||||
assert.equal(editionOf(null), null);
|
||||
assert.equal(editionOf('2nd ed.'), '2nd ed.');
|
||||
assert.equal(editionOf('Third edition.'), 'Third edition');
|
||||
assert.equal(editionOf('Third edition /'), 'Third edition');
|
||||
assert.equal(editionOf('Third edition ;'), 'Third edition');
|
||||
assert.equal(editionOf('Rev. and enl. ed.,'), 'Rev. and enl. ed.');
|
||||
assert.equal(editionOf('Second printing.'), 'Second printing');
|
||||
assert.equal(editionOf('4th print.'), '4th print.');
|
||||
assert.equal(editionOf('Nouvelle éd.'), 'Nouvelle éd.');
|
||||
assert.equal(editionOf('3. Aufl.'), '3. Aufl.');
|
||||
assert.equal(editionOf(' Third edition '), 'Third edition');
|
||||
assert.equal(editionOf(' / '), null);
|
||||
});
|
||||
|
||||
test('edition from real records: ISBN fixture and LCCN fixture', () => {
|
||||
assert.equal(parseMarcXml(fx('loc-isbn-9780201835953.xml'))[0]!.edition, 'Anniversary ed.');
|
||||
assert.equal(parseMarcXml(fx('loc-lccn-88005934.xml'))[0]!.edition, '2nd ed.');
|
||||
assert.equal(parseMarcXml(fx('loc-isbn-9781593278281.xml'))[0]!.edition, null);
|
||||
});
|
||||
|
||||
test('edition: a bare number reads as an ordinal edition; "Edition" is lower-cased unless first', () => {
|
||||
for (const [raw, want] of [['9.', '9th edition'], ['9', '9th edition'], ['2', '2nd edition'], ['1', '1st edition'], ['3.', '3rd edition'],
|
||||
['11', '11th edition'], ['12', '12th edition'], ['22', '22nd edition'], ['101', '101st edition']] as const) {
|
||||
assert.equal(editionOf(raw), want, raw);
|
||||
}
|
||||
assert.equal(editionOf('Third Edition'), 'Third edition');
|
||||
assert.equal(editionOf('Second Revised Edition.'), 'Second Revised edition');
|
||||
assert.equal(editionOf('Edition 2'), 'Edition 2');
|
||||
assert.equal(editionOf('Library Edition'), 'Library edition'); // Library of Congress values are not filtered
|
||||
assert.equal(parseMarcXml(fx('loc-isbn-9780899978840.xml'))[0]!.edition, '9th edition');
|
||||
});
|
||||
@@ -16,6 +16,8 @@ export interface MarcFields {
|
||||
isbns: string[];
|
||||
/** Place words for the card's hierarchy, from the first usable Library of Congress subject heading; see subjectTail(). */
|
||||
subjectTail: string[];
|
||||
/** The edition statement (250 $a), cleaned by cleanEdition(); null when the record has none. */
|
||||
edition: string | null;
|
||||
}
|
||||
|
||||
type Node = Record<string, unknown>;
|
||||
@@ -89,6 +91,32 @@ export function displayName(name: string): string {
|
||||
return [forenames, surname, ...suffix].join(' ');
|
||||
}
|
||||
|
||||
/** Statements that end in an abbreviation keep their final full stop. */
|
||||
const ABBREVIATED = /(?:^|[\s(])(?:ed|rev|enl|print|impr|éd|aufl)\.$/i;
|
||||
|
||||
/** 1 -> "1st", 2 -> "2nd", 3 -> "3rd", 4 -> "4th", 11 -> "11th", 22 -> "22nd". */
|
||||
export function ordinal(n: number): string {
|
||||
const t = n % 100;
|
||||
const suffix = t >= 11 && t <= 13 ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' } as Record<number, string>)[n % 10] ?? 'th';
|
||||
return `${n}${suffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* An edition statement as catalogued, minimally cleaned: ISBD punctuation at the end ( / , ; : ) and the final
|
||||
* full stop go, unless the statement ends in an abbreviation ("2nd ed." stays). A statement that is only a number
|
||||
* ("9.", "2") reads as an ordinal edition ("9th edition"), unless `ordinalise` is false. A capitalised "Edition" that
|
||||
* is not the first word is lower-cased ("Third Edition" -> "Third edition"). Nothing else is reworded.
|
||||
* Returns null for an empty result.
|
||||
*/
|
||||
export function cleanEdition(raw: string, ordinalise = true): string | null {
|
||||
let s = raw.replace(/\s+/g, ' ').trim();
|
||||
s = s.replace(/[\s\/,;:]+$/, '');
|
||||
if (s.endsWith('.') && !ABBREVIATED.test(s)) s = s.replace(/\.+$/, '').trim();
|
||||
if (ordinalise && /^\d{1,3}$/.test(s) && Number(s) > 0) s = `${ordinal(Number(s))} edition`;
|
||||
s = s.replace(/(?<=\S )Edition\b/g, 'edition');
|
||||
return s || null;
|
||||
}
|
||||
|
||||
/** A heading without its closing ISBD full stop: "Utah." -> "Utah". */
|
||||
const noStop = (s: string) => s.trim().replace(/\.+$/, '').trim();
|
||||
|
||||
@@ -159,7 +187,9 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
if (ym) meta.year = Number(ym[1]);
|
||||
if (lccn) meta.lccn = lccn;
|
||||
const isbns = uniq(all('020').flatMap((f) => f.subs.filter((x) => x.code === 'a').map((x) => normalizeIsbn(x.value.split(/\s/)[0] ?? '')).filter((x): x is string => x !== null)));
|
||||
return { lccn, lcc, dewey, meta, names, topics, isbns, subjectTail: subjectTail(fields) };
|
||||
const f250 = all('250')[0];
|
||||
const edition = f250 ? cleanEdition(sub(f250, 'a')) : null;
|
||||
return { lccn, lcc, dewey, meta, names, topics, isbns, subjectTail: subjectTail(fields), edition };
|
||||
}
|
||||
|
||||
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseEditionName } from './openlibrary.ts';
|
||||
|
||||
test('edition_name is cleaned like a MARC 250 and absent when missing', () => {
|
||||
assert.equal(parseEditionName('{"key":"/books/OL1M","edition_name":"Third edition."}'), 'Third edition');
|
||||
assert.equal(parseEditionName('{"key":"/books/OL1M","edition_name":"2nd ed."}'), '2nd ed.');
|
||||
assert.equal(parseEditionName('{"key":"/books/OL1M","edition_name":" "}'), null);
|
||||
assert.equal(parseEditionName('{"key":"/books/OL1M","title":"x"}'), null);
|
||||
});
|
||||
|
||||
test('edition_name is accepted only when it is a well-formed edition statement', () => {
|
||||
const name = (v: string) => parseEditionName(JSON.stringify({ key: '/books/OL1M', edition_name: v }));
|
||||
for (const ok of ['Third edition', 'third edition.', '2nd ed.', '7th edition', 'New ed.', 'Second revised edition', 'Revised edition', '10th ed', 'Anniversary edition']) {
|
||||
assert.ok(name(ok), ok);
|
||||
}
|
||||
assert.equal(name('Third Edition'), 'Third edition');
|
||||
for (const bad of ['2 edition', '3 Spi edition', '1', '9.', 'Paperback', 'Kindle Edition', 'Paperback edition', 'Large print edition',
|
||||
'Illustrated edition', 'Reprint edition', 'Third', 'edition', 'Special edition', 'First large print edition', 'Seventh Annual Report of the thing in full edition']) {
|
||||
assert.equal(name(bad), null, bad);
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BookMeta, Candidate, SearchResult } from '../../shared/types.ts';
|
||||
import { formatCallNumber, parseCallNumber } from '../../shared/callnumber.ts';
|
||||
import { cleanEdition } from './marc.ts';
|
||||
import { getText, trimPunct, TemporaryError } from './http.ts';
|
||||
import type { SourceCache } from './http.ts';
|
||||
|
||||
@@ -64,6 +65,33 @@ function docs(body: string): Record<string, unknown>[] {
|
||||
return Array.isArray(d) ? d.map(obj).filter((x): x is Record<string, unknown> => x !== null) : [];
|
||||
}
|
||||
|
||||
const ORDINAL_WORDS = new Set(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth',
|
||||
'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth']);
|
||||
const STARTERS = new Set(['new', 'revised', 'rev.', 'updated', 'expanded', 'enlarged', 'anniversary']);
|
||||
/** Words that describe a format or a printing, never an edition. */
|
||||
const FORMAT_WORDS = new Set(['kindle', 'paperback', 'hardcover', 'hardback', 'large', 'illustrated', 'reprint', 'ebook', 'e-book', 'library', 'audio']);
|
||||
|
||||
/**
|
||||
* Open Library's edition_name is free text, often import data. It counts only when it reads as an edition statement:
|
||||
* it starts with an ordinal word (first..twentieth), an ordinal number (1st, 22nd) or one of new / revised / rev. /
|
||||
* updated / expanded / enlarged / anniversary; ends with "edition", "ed." or "ed"; is at most six words; and has no
|
||||
* format word (Kindle, paperback, large print, illustrated, reprint...). Anything else is "none".
|
||||
*/
|
||||
export function wellFormedEdition(s: string): boolean {
|
||||
const words = s.toLowerCase().split(' ');
|
||||
if (words.length > 6 || words.some((w) => FORMAT_WORDS.has(w))) return false;
|
||||
const first = words[0]!;
|
||||
if (!(ORDINAL_WORDS.has(first) || /^\d+(st|nd|rd|th)$/.test(first) || STARTERS.has(first))) return false;
|
||||
return /^(edition|ed\.?)$/.test(words.at(-1)!) && words.length > 1;
|
||||
}
|
||||
|
||||
/** The edition's own name ("Third edition") from /isbn/{isbn}.json, cleaned like a MARC 250 and kept only if well formed; null otherwise. */
|
||||
export function parseEditionName(body: string): string | null {
|
||||
const v = obj(parseJson(body))?.['edition_name'];
|
||||
const s = typeof v === 'string' ? cleanEdition(v, false) : null;
|
||||
return s && wellFormedEdition(s) ? s : null;
|
||||
}
|
||||
|
||||
/** Parse the work-level search by ISBN; null when no doc. */
|
||||
export function parseWork(body: string): OlInfo | null {
|
||||
const d = docs(body)[0];
|
||||
@@ -114,6 +142,8 @@ export interface OpenLibrary {
|
||||
/** Keyword relevance search (all words must match); results carry their LC classification when Open Library has one. */
|
||||
similar(keywords: string[]): Promise<SimilarDoc[]>;
|
||||
edition(isbn: string): Promise<OlInfo | null>;
|
||||
/** The edition record's edition_name for this ISBN (a separate request: api/books does not carry it); null when none. */
|
||||
editionName(isbn: string): Promise<string | null>;
|
||||
work(isbn: string): Promise<OlInfo | null>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
@@ -142,6 +172,10 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach
|
||||
const url = `https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&jscmd=data&format=json`;
|
||||
return parseEdition(await body(`ol-data:${isbn}`, url, (t) => parseEdition(t, isbn) !== null), isbn);
|
||||
},
|
||||
async editionName(isbn) {
|
||||
const url = `https://openlibrary.org/isbn/${isbn}.json`;
|
||||
return parseEditionName(await body(`ol-isbn:${isbn}`, url, (t) => obj(parseJson(t))?.['key'] !== undefined));
|
||||
},
|
||||
async work(isbn) {
|
||||
const url = `https://openlibrary.org/search.json?isbn=${isbn}&fields=${FIELDS}`;
|
||||
return parseWork(await body(`ol-search:${isbn}`, url, (t) => parseWork(t) !== null));
|
||||
|
||||
+5
-1
@@ -11,6 +11,8 @@ export interface Book {
|
||||
inQueue: boolean; printedAt: string | null; createdAt: string; updatedAt: string;
|
||||
/** Place words from the catalogue record's subject heading. null: not looked for yet; []: looked, none. */
|
||||
hierarchyTail: string[] | null;
|
||||
/** The edition statement ("Third edition") from a record for this exact edition. null: not looked up yet; '': looked, none. */
|
||||
edition: string | null;
|
||||
}
|
||||
/** A call number explained in plain words: `outline` from the LC outline (main class first), `tail` from the record's subject. */
|
||||
export interface Hierarchy { outline: string[]; tail: string[] }
|
||||
@@ -31,11 +33,13 @@ export interface Resolution {
|
||||
dewey: string | null;
|
||||
/** The tail for this book; null when the catalogue could not be asked (so it is looked for again later). */
|
||||
tail?: string[] | null;
|
||||
/** The edition statement from this edition's own record: '' when there is none; null when the catalogue could not be asked. */
|
||||
edition?: string | null;
|
||||
reason: string | null; // set when callNumber is null
|
||||
}
|
||||
export interface CardData {
|
||||
callNumber: string; hierarchy: Hierarchy;
|
||||
title: string; authors: string[]; publisher: string | null; year: number | null;
|
||||
title: string; authors: string[]; publisher: string | null; year: number | null; edition: string | null;
|
||||
subjects: string[]; isbn13: string | null; approximate: boolean;
|
||||
}
|
||||
/** Print position: offsets in mm, and a turn of the whole print in degrees (positive = clockwise as seen on the printed sheet). */
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ function toBook(r: unknown): Book {
|
||||
}
|
||||
|
||||
export interface ManualInput { title: string; authors: string[]; year?: number; publisher?: string; callNumber?: string }
|
||||
export interface BookPatch { title?: string; authors?: string[]; publisher?: string | null; year?: number | null; callNumber?: string }
|
||||
export interface BookPatch { title?: string; authors?: string[]; publisher?: string | null; year?: number | null; edition?: string | null; callNumber?: string }
|
||||
|
||||
export const api = {
|
||||
scan: (isbn: string) => request<{ book: Book; duplicate: boolean }>('POST', '/api/scan', { isbn }),
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'pending', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, hierarchyTail: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const ready = (id: number, over: Partial<Book> = {}) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id, ...over });
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CallNo } from './CallNo.tsx';
|
||||
import { StateMark, StateText } from './StateMark.tsx';
|
||||
|
||||
function Main({ book, showYear }: { book: Book; showYear: boolean }) {
|
||||
const byline = [displayAuthors(book.authors).join(', '), showYear ? book.year : null].filter(Boolean).join(' · ');
|
||||
const byline = [displayAuthors(book.authors).join(', '), showYear ? book.edition : null, showYear ? book.year : null].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<span class="row-main">
|
||||
<span class="row-title">{book.title}</span>
|
||||
|
||||
@@ -43,6 +43,7 @@ function EditorForm({ book, fixing, initial, onClose }: {
|
||||
const [authors, setAuthors] = useState(book ? displayAuthors(book.authors).join('; ') : initial?.authors ?? '');
|
||||
const [publisher, setPublisher] = useState(book?.publisher ?? '');
|
||||
const [year, setYear] = useState(book?.year?.toString() ?? '');
|
||||
const [edition, setEdition] = useState(book?.edition ?? '');
|
||||
const [callNumber, setCallNumber] = useState(book?.callNumber ?? '');
|
||||
const [picked, setPicked] = useState<SearchResult | null>(null);
|
||||
const [yearError, setYearError] = useState('');
|
||||
@@ -77,6 +78,7 @@ function EditorForm({ book, fixing, initial, onClose }: {
|
||||
title: title.trim(), authors: names,
|
||||
...(y.value !== null ? { year: y.value } : {}),
|
||||
...(publisher.trim() ? { publisher: publisher.trim() } : {}),
|
||||
...(edition.trim() ? { edition: edition.trim() } : {}),
|
||||
...(callNumber.trim() ? { callNumber: callNumber.trim() } : {}),
|
||||
});
|
||||
upsertBook(created); setLastScan(created.id, false);
|
||||
@@ -85,6 +87,8 @@ function EditorForm({ book, fixing, initial, onClose }: {
|
||||
return;
|
||||
}
|
||||
const patch: BookPatch = { title: title.trim(), authors: names, publisher: publisher.trim() || null, year: y.value };
|
||||
// Only a changed edition is sent: an untouched empty one stays "not looked up yet" so the catalogue can fill it.
|
||||
if (edition.trim() !== (book.edition ?? '')) patch.edition = edition.trim();
|
||||
const numberChanged = callNumber.trim() !== (book.callNumber ?? '');
|
||||
if (numberChanged) patch.callNumber = callNumber.trim();
|
||||
let saved = await api.patchBook(book.id, patch);
|
||||
@@ -130,6 +134,10 @@ function EditorForm({ book, fixing, initial, onClose }: {
|
||||
</label>
|
||||
</div>
|
||||
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
|
||||
<label class="field">Edition
|
||||
<input value={edition} onInput={e => setEdition(e.currentTarget.value)} />
|
||||
<span class="help">From the catalogue when it has one, for example Third edition. Optional.</span>
|
||||
</label>
|
||||
<label class="field">Call number
|
||||
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
|
||||
<span class="help">{book ? 'Changing this locks the number' : 'Optional. Leave it empty to have it looked up.'}</span>
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: false,
|
||||
printedAt: null, hierarchyTail: null, createdAt: '', updatedAt: '', ...over,
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: '', updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const qa = (id: number, key: string) => book(id, { callNumber: 'QA76.73 .R87', sortKey: key });
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, title: string, sortKey: string | null): Book {
|
||||
id, isbn13: null, lccn: null, title, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey, confidence: null, source: null, dewey: null,
|
||||
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, hierarchyTail: null, createdAt: '', updatedAt: '',
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: '', updatedAt: '',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user