141 lines
5.8 KiB
TypeScript
141 lines
5.8 KiB
TypeScript
import { XMLParser } from 'fast-xml-parser';
|
|
import type { BookMeta, Candidate } from '../../shared/types.ts';
|
|
import { trimPunct } from './http.ts';
|
|
|
|
export interface MarcFields {
|
|
lccn: string | null;
|
|
lcc: Candidate[];
|
|
dewey: string | null;
|
|
meta: Partial<BookMeta>;
|
|
/** Every 100/700 $a, cleaned but still in "Surname, Forename" form; used to verify title/author matches. */
|
|
names: string[];
|
|
/** Subject headings with their subdivisions and place names (650, 651), for judging what a book is about. */
|
|
topics: string[];
|
|
}
|
|
|
|
type Node = Record<string, unknown>;
|
|
|
|
const ARRAYS = new Set(['record', 'datafield', 'subfield', 'controlfield']);
|
|
|
|
const parser = new XMLParser({
|
|
ignoreAttributes: false,
|
|
attributeNamePrefix: '@_',
|
|
removeNSPrefix: true,
|
|
parseTagValue: false,
|
|
parseAttributeValue: false,
|
|
trimValues: true,
|
|
isArray: (name) => ARRAYS.has(name),
|
|
});
|
|
|
|
function isNode(v: unknown): v is Node { return typeof v === 'object' && v !== null; }
|
|
function asArray<T>(v: T | T[] | undefined | null): T[] { return v == null ? [] : Array.isArray(v) ? v : [v]; }
|
|
|
|
/** Find MARC records anywhere in the tree: SRU wrapper, bare record, or collection. */
|
|
function findRecords(node: unknown, out: Node[]): void {
|
|
if (Array.isArray(node)) { for (const n of node) findRecords(n, out); return; }
|
|
if (!isNode(node)) return;
|
|
if ('datafield' in node || 'leader' in node) { out.push(node); return; }
|
|
for (const k of Object.keys(node)) if (!k.startsWith('@_')) findRecords(node[k], out);
|
|
}
|
|
|
|
function text(v: unknown): string {
|
|
if (typeof v === 'string') return v;
|
|
if (typeof v === 'number') return String(v);
|
|
if (isNode(v)) return typeof v['#text'] === 'string' ? (v['#text'] as string) : '';
|
|
return '';
|
|
}
|
|
|
|
interface Field { tag: string; ind2: string; subs: { code: string; value: string }[] }
|
|
|
|
function fieldsOf(rec: Node): Field[] {
|
|
return asArray(rec['datafield'] as Node | Node[] | undefined).filter(isNode).map((d) => ({
|
|
tag: String(d['@_tag'] ?? ''),
|
|
ind2: String(d['@_ind2'] ?? ' '),
|
|
subs: asArray(d['subfield'] as unknown).map((s) => ({
|
|
code: isNode(s) ? String(s['@_code'] ?? '') : '',
|
|
value: text(s).trim(),
|
|
})),
|
|
}));
|
|
}
|
|
|
|
function sub(f: Field, code: string): string {
|
|
return f.subs.find((s) => s.code === code && s.value)?.value ?? '';
|
|
}
|
|
|
|
function uniq(a: string[]): string[] { return [...new Set(a)]; }
|
|
|
|
/** Strip trailing punctuation and life dates from a MARC name: "Brooks, Frederick P., 1931-" -> "Brooks, Frederick P." */
|
|
export function cleanName(raw: string): string {
|
|
let s = raw.trim();
|
|
s = s.replace(/[,\s]*\(?\b(?:b\.\s*|d\.\s*|ca\.\s*)?\d{3,4}\??\s*-\s*(?:\d{3,4})?\)?[.,\s]*$/i, '');
|
|
s = s.replace(/[\s,;:\/]+$/, '');
|
|
// Keep the period of an initial or Jr./Sr.; drop the ISBD full stop after other words.
|
|
const last = /([^\s,]+)\.$/.exec(s)?.[1];
|
|
if (last && last.length > 1 && !/^(jr|sr)$/i.test(last)) s = s.slice(0, -1);
|
|
return s.trim();
|
|
}
|
|
|
|
/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. */
|
|
export function displayName(name: string): string {
|
|
const parts = name.split(',').map((p) => p.trim()).filter(Boolean);
|
|
if (parts.length < 2) return name.trim();
|
|
const [surname, forenames, ...suffix] = parts as [string, string, ...string[]];
|
|
return [forenames, surname, ...suffix].join(' ');
|
|
}
|
|
|
|
export function parseMarcRecord(rec: Node): MarcFields {
|
|
const fields = fieldsOf(rec);
|
|
const all = (tag: string) => fields.filter((f) => f.tag === tag);
|
|
|
|
// Leader position 6 is the record type. Videos, sound recordings and the like carry their own
|
|
// classification (a DVD of a novel is not the novel's shelf number), so only text records count.
|
|
const leader = text(rec['leader']);
|
|
const isText = leader.length < 7 || 'at'.includes(leader[6]);
|
|
const lcc: Candidate[] = [];
|
|
for (const f of isText ? all('050') : []) {
|
|
const a = sub(f, 'a');
|
|
if (!a) continue;
|
|
const b = sub(f, 'b');
|
|
lcc.push(b ? { raw: `${a} ${b}`, complete: true } : { raw: a, complete: false });
|
|
}
|
|
|
|
const d082 = all('082')[0];
|
|
const dewey = d082 && sub(d082, 'a') ? sub(d082, 'a').replace(/\//g, '') : null;
|
|
|
|
const f245 = all('245')[0];
|
|
const title = f245 ? trimPunct(sub(f245, 'a')) : '';
|
|
const subtitle = f245 ? trimPunct(sub(f245, 'b')) : '';
|
|
|
|
const f100 = all('100');
|
|
const names = uniq([...f100, ...all('700')].map((f) => cleanName(sub(f, 'a'))).filter(Boolean));
|
|
// The 100 is the author; 700s (editors, illustrators, co-authors) only stand in when there is none.
|
|
const authors = uniq((f100.length ? f100 : all('700')).map((f) => cleanName(sub(f, 'a'))).filter(Boolean).map(displayName));
|
|
|
|
const pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0];
|
|
const publisher = pub ? trimPunct(sub(pub, 'b')) : '';
|
|
const ym = pub ? /\b(1[0-9]\d\d|20\d\d)\b/.exec(sub(pub, 'c')) : null;
|
|
|
|
const subjects = uniq(all('650').map((f) => trimPunct(sub(f, 'a'))).filter(Boolean));
|
|
const topics = uniq([...all('650'), ...all('651')].flatMap((f) =>
|
|
f.subs.filter((s) => 'avxyz'.includes(s.code) && s.value).map((s) => trimPunct(s.value))));
|
|
const f010 = all('010')[0];
|
|
const lccn = f010 && sub(f010, 'a') ? sub(f010, 'a').replace(/\s+/g, '') : null;
|
|
|
|
const meta: Partial<BookMeta> = { authors, subjects };
|
|
if (title) meta.title = title;
|
|
if (subtitle) meta.subtitle = subtitle;
|
|
if (publisher) meta.publisher = publisher;
|
|
if (ym) meta.year = Number(ym[1]);
|
|
if (lccn) meta.lccn = lccn;
|
|
return { lccn, lcc, dewey, meta, names, topics };
|
|
}
|
|
|
|
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
|
|
export function parseMarcXml(xml: string): MarcFields[] {
|
|
let tree: unknown;
|
|
try { tree = parser.parse(xml); } catch { return []; }
|
|
const recs: Node[] = [];
|
|
findRecords(tree, recs);
|
|
return recs.map(parseMarcRecord);
|
|
}
|