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 { createGoogleBooks } from '../sources/googlebooks.ts'; import type { GbInfo } from '../sources/googlebooks.ts'; import type { OlInfo } from '../sources/openlibrary.ts'; import { classified, cuesOf, finishSimilar, keywordsOf, mergeCandidates, placeQueries, placeWords, searchWords, shortQueries, variants, voteSimilar } from './similar.ts'; import type { Keywords, SimilarCandidate, VoteOpts } 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; /** * Settling mode, for a lookup that has failed for a while: a source that cannot be asked no longer blocks a number * already in hand (the other source's check, the edition, the tail stay unknown, to be filled in later). With no * number at all it still throws, so the lookup goes on. */ 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; search(title: string, author: string): Promise; /** * 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; /** * 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; } type Partials = (Partial | null | undefined)[]; function mergeMeta(parts: Partials): BookMeta | null { const first = (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): Partial => { const { lccn: _l, ...rest } = m; return rest; }; /** The fewest books that must agree on a class when the search had to be widened. */ export const MIN_AGREE = 2; 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; }): 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 gb = createGoogleBooks({ fetch: deps.fetch, cache }); const sleep = deps.sleep ?? ((ms: number) => new Promise((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 { if (!opts?.fresh) return lookup(input, opts); bypass++; try { return await lookup(input, opts); } finally { bypass--; } } async function lookup(input: ResolveInput, opts?: ResolveOpts): Promise { // 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): Promise => { 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 => { 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; }; let olError: unknown = null; if (isbn) { workP = ol.work(isbn).then((v) => ({ v }), (e: unknown) => ({ e })); try { edition = await ol.edition(isbn); } catch (e) { if (!(opts?.tolerateLocFailure && e instanceof TemporaryError)) throw e; olError = e; // settling: the Library of Congress may still have the number } if (edition) notify(mergeMeta([edition.meta])); else { work = await getWork(!olError); 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) { try { edit = (await ol.editionName(isbn)) ?? ''; } catch (e) { // Settling with a number in hand: the edition stays unknown (NULL) and is looked for later. if (!(opts?.tolerateLocFailure && e instanceof TemporaryError)) throw e; } } else if (edit === null && !isbn && !locError) edit = ''; const olEditionCands: Candidate[] = edition?.lcc ?? []; // Google Books (asked below, only while there is no number): the last source for a title, and a filler of gaps. let google: GbInfo | null = null; let googleError: unknown = null; const metaOf = (extra: Partials = []): BookMeta | null => mergeMeta([edition?.meta, locRecs[0]?.meta, ...extra, google?.meta, 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); // Google Books: a title and authors for an ISBN neither Open Library nor the Library of Congress knows, and the // subtitle, publisher and categories they left out. It never gives a number, so it is asked only when there is none. if (!chosen && isbn) { try { google = await gb.byIsbn(isbn); } catch (e) { if (!(e instanceof TemporaryError)) throw e; googleError = e; // a number found below still stands; with none, the lookup is tried again } if (google) notify(metaOf()); } // 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. 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), }))); } // The searches so far found no class: widen them, one step at a time, voting after each request and stopping at // the first vote that wins. At most 12 requests in all for the tier (3 Open Library + 2 Library of Congress // above, 1 more with a class hint, then 1 for word forms, up to 3 with place words, up to 2 shorter ones). const hintOpt = hint ? { hint: hint.cls } : {}; const cues = cuesOf([meta.title, meta.subtitle, meta.publisher, ...(google?.categories ?? []), ...meta.subjects]); const strict: VoteOpts = hintOpt; // A widened vote: two books must agree (never one), they hold half the weight, and lead the rival by half again. const relaxed: VoteOpts = { ...hintOpt, minAgree: MIN_AGREE, minShare: 0.2, margin: 1.5, cues }; const asGroup = (recs: MarcFields[]): SimilarCandidate[] => 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), })); let vote = voteSimilar(kw, mergeCandidates(groups), strict); let how = ''; const widen = async (label: string, q: () => Promise, kws: Keywords, o: VoteOpts): Promise => { if (vote || locError) return; const recs = await locCall(q); similarRecs.push(...recs); groups.push(asGroup(recs)); vote = voteSimilar(kws, mergeCandidates(groups), o); if (vote) how = label; }; if (!vote && kw.own.length >= 2) { // b: other forms of the words (hike, hikes, hiking) in one query. await widen('other forms of the title words', () => loc.byWordForms(kw.own.slice(0, 3).map(variants)), kw, strict); } const ctx = { title: meta.title, subtitle: meta.subtitle, publisher: meta.publisher, authors: meta.authors, subjects: meta.subjects, categories: google?.categories ?? [] }; const places = placeWords(ctx); // c: place and topic words from the subtitle, publisher, author and categories; they also add weight to a book that has them. const kwPlaces: Keywords = { ...kw, extra: [...new Set([...places, ...kw.extra])].slice(0, 6) }; if (!vote) { for (const q of placeQueries(kw, ctx, places)) { await widen(`${q.join(' ')}, a place or topic from the record`, () => loc.byKeywords(q), kwPlaces, relaxed); } } // d: shorter searches from the title's most distinctive words. if (!vote) { for (const q of shortQueries(kw)) await widen(`${q.join(' ')}, a shorter search`, () => loc.byKeywords(q), kwPlaces, relaxed); } // e: what has been found, judged once more with the match threshold lowered to one title word. Still two books must agree. if (!vote) { vote = voteSimilar(kwPlaces, mergeCandidates(groups), { ...relaxed, minMatched: 1, minShare: 0.3, margin: 1.25 }); if (vote) how = 'a lower match threshold'; } 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${how ? `; widened: ${how}` : ''})`); } } } // 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) { // Settled with a source unasked: the number was not checked against it, so it is marked as approximate. const settled = !!opts?.tolerateLocFailure && !!(locError || olError); return { meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey, confidence: settled && chosen.confidence === 'exact' ? 'approximate' : 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; if (googleError) throw googleError; 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, Google Books 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) => Promise, report?: (s: TailSource) => void): Promise { 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 { 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 { 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) }; }