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>
395 lines
19 KiB
TypeScript
395 lines
19 KiB
TypeScript
import type { BookMeta, Candidate, ResolveInput, Resolution, SearchResult } from '../../shared/types.ts';
|
|
import { normalizeIsbn } from '../../shared/isbn.ts';
|
|
import { classKey, parseCallNumber } from '../../shared/callnumber.ts';
|
|
import { bareClassResult, chooseCallNumber, findHint } from './choose.ts';
|
|
import type { Chosen } from './choose.ts';
|
|
import { createLoc } from '../sources/loc.ts';
|
|
import { createOpenLibrary } from '../sources/openlibrary.ts';
|
|
import type { OlInfo } from '../sources/openlibrary.ts';
|
|
import { classified, finishSimilar, keywordsOf, mergeCandidates, searchWords, voteSimilar } from './similar.ts';
|
|
import type { SimilarCandidate } from './similar.ts';
|
|
import type { MarcFields } from '../sources/marc.ts';
|
|
import { TemporaryError } from '../sources/http.ts';
|
|
import { recordMatches } from './match.ts';
|
|
import { bookClassKey, hasClassKey, commonTail, titleTier } from './tail.ts';
|
|
import type { SourceCache } from '../sources/http.ts';
|
|
|
|
export { TemporaryError };
|
|
export type { SourceCache };
|
|
|
|
export interface ResolveOpts {
|
|
onMeta?: (meta: BookMeta) => void;
|
|
/** Last-attempt mode: a Library of Congress failure is not fatal; use Open Library's numbers if it has any. */
|
|
tolerateLocFailure?: boolean;
|
|
/** Called when the similar-books tier chose the number, for example "GV199.42.W8 (4 of 9 candidates)". */
|
|
onSimilar?: (detail: string) => void;
|
|
/** Ignore every cached source answer (and write fresh ones), so "Look up again" really asks again. */
|
|
fresh?: boolean;
|
|
/** Called when the tail came from a record other than this edition's own (see TailSource). */
|
|
onTailSource?: (s: TailSource) => void;
|
|
}
|
|
|
|
/** Where a tail came from: this edition's record, the title-matched record, or similar-books records with the book's class key. */
|
|
export interface TailSource { step: 'own' | 'title' | 'similar'; records: MarcFields[] }
|
|
|
|
/** What the tail needs to know about the book. `callNumber` is null for a book without one (only its own record counts). */
|
|
export interface TailInput {
|
|
isbn13?: string; lccn?: string; title?: string; author?: string; subtitle?: string; subjects?: string[]; callNumber?: string | null;
|
|
}
|
|
|
|
export interface Resolver {
|
|
resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution>;
|
|
search(title: string, author: string): Promise<SearchResult[]>;
|
|
/**
|
|
* Only the hierarchy tail of a book already in the library, by the same rules as a lookup: this edition's own
|
|
* Library of Congress record (by ISBN, then LCCN); else the title-matched record; else the keyword-search records;
|
|
* the last two only when they carry the book's class key. Uses the same rate limit and cache as a lookup.
|
|
* [] 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)[];
|
|
|
|
function mergeMeta(parts: Partials): BookMeta | null {
|
|
const first = <K extends keyof BookMeta>(k: K): BookMeta[K] | undefined => {
|
|
for (const p of parts) {
|
|
const v = p?.[k];
|
|
if (Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null && v !== '') return v as BookMeta[K];
|
|
}
|
|
return undefined;
|
|
};
|
|
const title = first('title');
|
|
if (!title) return null;
|
|
const meta: BookMeta = { title, authors: first('authors') ?? [], subjects: first('subjects') ?? [] };
|
|
const subtitle = first('subtitle'); if (subtitle) meta.subtitle = subtitle;
|
|
const publisher = first('publisher'); if (publisher) meta.publisher = publisher;
|
|
const year = first('year'); if (year) meta.year = year;
|
|
const lccn = first('lccn'); if (lccn) meta.lccn = lccn;
|
|
return meta;
|
|
}
|
|
|
|
/** A work-level or title-match record belongs to some edition, not necessarily this one: its LCCN is not this book's. */
|
|
const withoutLccn = (m: Partial<BookMeta>): Partial<BookMeta> => { const { lccn: _l, ...rest } = m; return rest; };
|
|
|
|
const lccOf = (recs: MarcFields[]): Candidate[] => recs.flatMap((r) => r.lcc);
|
|
|
|
export function createResolver(deps: {
|
|
fetch: typeof fetch; cache: SourceCache;
|
|
locIntervalMs?: number;
|
|
sleep?: (ms: number) => Promise<void>;
|
|
}): Resolver {
|
|
// While a fresh lookup runs, reads miss; writes still go through, so the new answers replace the old ones.
|
|
let bypass = 0;
|
|
const cache: SourceCache = { get: (k) => (bypass > 0 ? null : deps.cache.get(k)), set: (k, v) => deps.cache.set(k, v) };
|
|
const ol = createOpenLibrary({ fetch: deps.fetch, cache });
|
|
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
|
const loc = createLoc({
|
|
fetch: deps.fetch, cache,
|
|
intervalMs: deps.locIntervalMs ?? 6000,
|
|
sleep,
|
|
});
|
|
const OL_GAP_MS = 1000;
|
|
|
|
async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
|
if (!opts?.fresh) return lookup(input, opts);
|
|
bypass++;
|
|
try { return await lookup(input, opts); } finally { bypass--; }
|
|
}
|
|
|
|
async function lookup(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
|
// In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup.
|
|
let locError: unknown = null;
|
|
const locCall = async (fn: () => Promise<MarcFields[]>): Promise<MarcFields[]> => {
|
|
if (locError) return [];
|
|
try { return await fn(); } catch (e) {
|
|
if (opts?.tolerateLocFailure && e instanceof TemporaryError) { locError = e; return []; }
|
|
throw e;
|
|
}
|
|
};
|
|
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
|
|
let notified = false;
|
|
const notify = (m: BookMeta | null) => {
|
|
if (m && !notified) { notified = true; opts?.onMeta?.(m); }
|
|
};
|
|
|
|
// Open Library: edition first; the work search runs alongside and is awaited only when needed.
|
|
let edition: OlInfo | null = null;
|
|
let work: OlInfo | null = null;
|
|
let workP: Promise<{ v: OlInfo | null } | { e: unknown }> | null = null;
|
|
const getWork = async (required: boolean): Promise<OlInfo | null> => {
|
|
if (!workP) return null;
|
|
const r = await workP;
|
|
if ('e' in r) {
|
|
if (required) throw r.e;
|
|
return null;
|
|
}
|
|
return r.v ? { ...r.v, meta: withoutLccn(r.v.meta) } : null;
|
|
};
|
|
if (isbn) {
|
|
workP = ol.work(isbn).then((v) => ({ v }), (e: unknown) => ({ e }));
|
|
edition = await ol.edition(isbn);
|
|
if (edition) notify(mergeMeta([edition.meta]));
|
|
else { work = await getWork(true); notify(mergeMeta([work?.meta])); }
|
|
}
|
|
|
|
// Library of Congress: by LCCN when known, else by ISBN.
|
|
const lccn = input.lccn ?? edition?.meta.lccn;
|
|
let locRecs: MarcFields[] = [];
|
|
let locCands: Candidate[] = [];
|
|
// Numbers from an LCCN record that is not verifiably this edition: they are another edition's, like a title match.
|
|
let lccnOtherCands: Candidate[] = [];
|
|
let exactSource: 'loc-isbn' | 'loc-lccn' = isbn ? 'loc-isbn' : 'loc-lccn';
|
|
const tagged = (recs: MarcFields[], source: 'loc-isbn' | 'loc-lccn'): Candidate[] =>
|
|
lccOf(recs).map((c) => ({ ...c, source }));
|
|
// The ISBN comes first: its record is for this edition by construction. The LCCN is the second route, asked
|
|
// only when the ISBN gave no number, or none with evidence of being complete (a 050 with only $a).
|
|
if (isbn) {
|
|
locRecs = await locCall(() => loc.byIsbn(isbn));
|
|
locCands = tagged(locRecs, 'loc-isbn');
|
|
}
|
|
if (lccn && !locCands.some((c) => c.complete === true)) {
|
|
const recs = await locCall(() => loc.byLccn(lccn));
|
|
// Same edition only if the book has no ISBN (the LCCN is then its own identifier) or the record lists this ISBN.
|
|
const mine = recs.filter((r) => !isbn || r.isbns.includes(isbn));
|
|
const others = recs.filter((r) => !mine.includes(r));
|
|
if (mine.length > 0) {
|
|
if (locRecs.length === 0) locRecs = mine;
|
|
locCands = [...locCands, ...tagged(mine, 'loc-lccn')];
|
|
}
|
|
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]);
|
|
const forChoose = (m: BookMeta | null) => ({
|
|
authors: m?.authors.length ? m.authors : input.author ? [input.author] : [],
|
|
title: m?.title ?? input.title ?? '',
|
|
year: m?.year ?? input.year,
|
|
});
|
|
notify(metaOf());
|
|
|
|
// Tiers 1 and 2: this edition's own records, used verbatim. A bare class there is only a hint.
|
|
const own = { locExact: locCands, olEdition: olEditionCands };
|
|
let chosen: Chosen | null = chooseCallNumber({ ...own, locTitle: [], olWork: [] }, forChoose(metaOf()), exactSource);
|
|
const hint = chosen ? null : findHint(own, exactSource);
|
|
|
|
// Tier 3: LoC by title and author.
|
|
let locTitleRecs: MarcFields[] = [];
|
|
let titleSearched = false;
|
|
if (!chosen) {
|
|
titleSearched = true;
|
|
work ??= await getWork(false);
|
|
const m = metaOf([work?.meta]);
|
|
const title = m?.title ?? input.title;
|
|
const author = m?.authors[0] ?? input.author ?? '';
|
|
// Without an author a title search cannot be verified, so that search is skipped.
|
|
if (title && author) {
|
|
const found = await locCall(() => loc.byTitle(title, author));
|
|
locTitleRecs = found.filter((r) => recordMatches(r, title, author));
|
|
}
|
|
chosen = chooseCallNumber(
|
|
{ locExact: [], olEdition: [], locTitle: [...lccnOtherCands, ...lccOf(locTitleRecs)], olWork: [] },
|
|
forChoose(m), exactSource, hint,
|
|
);
|
|
}
|
|
|
|
// Tier 4, and the work-level part of the metadata merge.
|
|
work ??= await getWork(!chosen);
|
|
// Without an ISBN or LCCN, the best title hit also supplies metadata.
|
|
const hitMeta = !isbn && !input.lccn && locTitleRecs[0] ? withoutLccn(locTitleRecs[0].meta) : undefined;
|
|
const meta = metaOf([hitMeta, work?.meta]);
|
|
notify(meta);
|
|
chosen ??= chooseCallNumber(
|
|
{ locExact: [], olEdition: [], locTitle: [], olWork: work?.lcc ?? [] },
|
|
forChoose(meta), exactSource, hint,
|
|
);
|
|
|
|
// Tier 5: borrow the class from similar books. Last resort, and only for a book with a title.
|
|
let olError: unknown = null;
|
|
const similarRecs: MarcFields[] = [];
|
|
let similarSearched = false;
|
|
if (!chosen && meta?.title) {
|
|
similarSearched = true;
|
|
const kw = keywordsOf(meta.title, meta.subtitle, meta.subjects);
|
|
const groups: SimilarCandidate[][] = [];
|
|
let found = 0;
|
|
const plan = searchWords(kw);
|
|
for (const [i, words] of plan.entries()) {
|
|
if (i > 0) await sleep(OL_GAP_MS);
|
|
try {
|
|
const docs = await ol.similar(words);
|
|
groups.push(docs.map((d) => ({ title: d.title, ...(d.subtitle ? { subtitle: d.subtitle } : {}), subjects: d.subjects, lcc: d.lcc })));
|
|
} catch (e) {
|
|
if (e instanceof TemporaryError) { olError = e; break; }
|
|
throw e;
|
|
}
|
|
found = classified(groups.flat());
|
|
if (found >= 5) break;
|
|
}
|
|
const locWords = (plan[0] ?? []).slice(0, 3);
|
|
if (locWords.length > 0) {
|
|
for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) {
|
|
const recs = await locCall(() => loc.byKeywords(words));
|
|
similarRecs.push(...recs);
|
|
groups.push(recs.map((r) => ({
|
|
title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}),
|
|
subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw),
|
|
})));
|
|
if (classified(groups.at(-1)!) >= 5 || locError) break;
|
|
}
|
|
}
|
|
// With a class hint and nobody in that class found so far, one more LoC search on the title index alone.
|
|
if (hint && !locError && locWords.length >= 2 && !groups.flat().some((c) => c.lcc.some((l) => {
|
|
const cn = parseCallNumber(l);
|
|
return cn !== null && cn.cutters.length > 0 && classKey(cn) === hint.cls;
|
|
}))) {
|
|
const recs = await locCall(() => loc.byTitleWords(locWords));
|
|
similarRecs.push(...recs);
|
|
groups.push(recs.map((r) => ({
|
|
title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}),
|
|
subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw),
|
|
})));
|
|
}
|
|
const vote = voteSimilar(kw, mergeCandidates(groups), hint ? { hint: hint.cls } : {});
|
|
if (vote) {
|
|
const done = finishSimilar(vote.key, forChoose(meta));
|
|
if (done) {
|
|
chosen = { callNumber: done.callNumber, sortKey: done.sortKey, confidence: 'approximate', source: 'similar' };
|
|
opts?.onSimilar?.(`${vote.key} (${vote.support} of ${vote.counted} candidates)`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// A bare class and nothing better: the class and this edition's year, with no generated cutter.
|
|
// Unless Open Library just failed and another attempt is coming: then ask again rather than settle for it.
|
|
if (!chosen && hint) {
|
|
if (olError && !opts?.tolerateLocFailure) throw olError;
|
|
chosen = bareClassResult(hint, forChoose(meta).year);
|
|
}
|
|
|
|
const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey
|
|
?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null;
|
|
|
|
// The tail: this edition's own record, else (for a number with a class cutter) the title-matched record and the
|
|
// keyword-search records that carry the same class key. When the catalogue could not be asked it stays unknown
|
|
// (null) and is looked for later.
|
|
const ownRec = locRecs.find((r) => r.subjectTail.length > 0);
|
|
let tail: string[] | null;
|
|
if (ownRec) { tail = ownRec.subjectTail; }
|
|
else if (!chosen) {
|
|
tail = locRecs[0] ? locRecs[0].subjectTail : locTitleRecs[0] ? locTitleRecs[0].subjectTail : locError ? null : [];
|
|
} else {
|
|
const f = forChoose(meta);
|
|
tail = await classTail({
|
|
callNumber: chosen.callNumber, title: f.title, author: f.authors[0] ?? '', subtitle: meta?.subtitle,
|
|
subjects: meta?.subjects ?? [], titleRecs: titleSearched ? locTitleRecs : null,
|
|
similarRecs: similarSearched ? similarRecs : null,
|
|
}, locCall, opts?.onTailSource);
|
|
if (tail.length === 0 && locError) tail = null;
|
|
}
|
|
if (ownRec) opts?.onTailSource?.({ step: 'own', records: [ownRec] });
|
|
|
|
if (chosen) {
|
|
return {
|
|
meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey,
|
|
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, edition: edit,
|
|
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Steps b and c of the tail rules, after this edition's own record gave nothing. Both need a number with a class
|
|
* cutter and use only records whose class key equals the book's. `titleRecs` / `similarRecs` are what an earlier
|
|
* search in this lookup already found (null: not searched yet, so search here).
|
|
*/
|
|
async function classTail(c: {
|
|
callNumber: string; title: string; author: string; subtitle?: string | undefined; subjects: string[];
|
|
titleRecs: MarcFields[] | null; similarRecs: MarcFields[] | null;
|
|
}, ask: (fn: () => Promise<MarcFields[]>) => Promise<MarcFields[]>, report?: (s: TailSource) => void): Promise<string[]> {
|
|
const key = bookClassKey(c.callNumber);
|
|
if (!key) return [];
|
|
let titleRecs = c.titleRecs;
|
|
if (titleRecs === null && c.title && c.author) {
|
|
// Without an author a title search cannot be verified, so that search is skipped.
|
|
titleRecs = (await ask(() => loc.byTitle(c.title, c.author))).filter((r) => recordMatches(r, c.title, c.author));
|
|
}
|
|
const viaTitle = titleRecs ? titleTier(key, titleRecs) : null;
|
|
if (viaTitle) { report?.({ step: 'title', records: [viaTitle] }); return viaTitle.subjectTail; }
|
|
|
|
if (!c.title) return [];
|
|
const kw = keywordsOf(c.title, c.subtitle, c.subjects);
|
|
let recs = c.similarRecs;
|
|
if (recs === null) {
|
|
recs = [];
|
|
const locWords = (searchWords(kw)[0] ?? []).slice(0, 3);
|
|
const has = () => recs!.some((r) => r.subjectTail.length > 0 && hasClassKey(r, key));
|
|
if (locWords.length > 0) {
|
|
for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) {
|
|
recs.push(...await ask(() => loc.byKeywords(words)));
|
|
if (has()) break;
|
|
}
|
|
if (!has() && locWords.length >= 2) recs.push(...await ask(() => loc.byTitleWords(locWords)));
|
|
}
|
|
}
|
|
const win = commonTail(key, recs);
|
|
if (!win) return [];
|
|
report?.({ step: 'similar', records: win.records });
|
|
return win.tail;
|
|
}
|
|
|
|
async function tail(input: TailInput, opts?: { onTailSource?: (s: TailSource) => void }): Promise<string[]> {
|
|
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
|
|
let mine: MarcFields[] = [];
|
|
if (isbn) mine = await loc.byIsbn(isbn);
|
|
if (mine.length === 0 && input.lccn) {
|
|
// Same edition only if the book has no ISBN or the record lists this ISBN.
|
|
mine = (await loc.byLccn(input.lccn)).filter((r) => !isbn || r.isbns.includes(isbn));
|
|
}
|
|
const own = mine.find((r) => r.subjectTail.length > 0);
|
|
if (own) { opts?.onTailSource?.({ step: 'own', records: [own] }); return own.subjectTail; }
|
|
if (!input.callNumber) return [];
|
|
return classTail({
|
|
callNumber: input.callNumber, title: input.title ?? '', author: input.author ?? '', subtitle: input.subtitle,
|
|
subjects: input.subjects ?? [], titleRecs: null, similarRecs: null,
|
|
}, (fn) => fn(), opts?.onTailSource);
|
|
}
|
|
|
|
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) };
|
|
}
|