// Generates src/shared/lcc-outline.ts (main classes and subclasses, used by the web app too) and // src/server/lcc-ranges.ts (every nested number range with its caption, server only) from the Library of // Congress Classification Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication. // Usage: node scripts/gen-lcc-outline.ts [cacheDir] (or env LCC_CACHE_DIR) // Requires `pdftotext` (poppler). Downloads are cached outside the repo. import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { parseOutlineText } from './lcc-parse.ts'; import type { Range } from './lcc-parse.ts'; const INDEX = 'https://www.loc.gov/catdir/cpso/lcco/'; const UA = 'Mozilla/5.0 (compatible; lcc-outline-generator)'; const cache = process.argv[2] ?? process.env.LCC_CACHE_DIR ?? join(tmpdir(), 'lcc-outline-cache'); mkdirSync(cache, { recursive: true }); const out = new URL('../src/shared/lcc-outline.ts', import.meta.url); const outRanges = new URL('../src/server/lcc-ranges.ts', import.meta.url); // Fix-ups applied to names after sentence-casing / extraction. const MAIN_FIXES: Record = { 'Auxiliary sciences of history': 'Auxiliary sciences of history', }; const SUB_FIXES: Record = { 'Christian Denominations': 'Christian denominations', }; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function get(url: string, file: string): Promise { const p = join(cache, file); if (existsSync(p)) return readFileSync(p); const res = await fetch(url, { headers: { 'User-Agent': UA } }); if (!res.ok) throw new Error(`${url}: ${res.status}`); const buf = Buffer.from(await res.arrayBuffer()); writeFileSync(p, buf); await sleep(1000); return buf; } const clean = (s: string) => s.replace(/\s+/g, ' ').trim(); function sentenceCase(s: string): string { const t = clean(s).toLowerCase(); return t .replace(/(^|\. )([a-z])/g, (_m, a: string, b: string) => a + b.toUpperCase()) .replace(/\((general)\)/g, '(General)') .replace(/\b(europe|asia|africa|australia|new zealand|americas?)\b/g, (w) => w.replace(/\b[a-z]/g, (c) => c.toUpperCase())) .replace(/,? etc$/, ', etc.'); } // Captions over 120 chars (PT lists many literatures) are cut at the last " - " that fits. function shorten(s: string): string { if (s.length <= 120) return s; const parts = s.split(' - '); let r = parts[0]!; for (const p of parts.slice(1)) { if ((r + ' - ' + p).length > 120) break; r += ' - ' + p; } return r.length <= 120 ? r : r.slice(0, 119).trimEnd() + '…'; } const indexHtml = (await get(INDEX, 'index.html')).toString('utf8'); const hrefs = [...new Set([...indexHtml.matchAll(/href="([^"]*lcco_[a-z]+\.pdf)"/g)].map((m) => m[1]!))]; if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.length}`); const MAIN: Record = {}; const SUB: Record = {}; const RANGES = new Map(); for (const href of hrefs) { const name = href.split('/').pop()!; const pdf = join(cache, name); await get(new URL(href, INDEX).href, name); const text = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 }); const lines = text.split('\n'); const parsed = parseOutlineText(text); for (const [letters, rows] of parsed.ranges) RANGES.set(letters, rows); for (const p of parsed.problems) console.warn(`${name}: skipped "${p}"`); // Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines. const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l)); if (ti < 0) throw new Error(`no title in ${name}`); const tm = lines[ti]!.match(/CLASS ([A-Z])(?:-([A-Z]))? - (.*)$/)!; let title = tm[3]!; for (let i = ti + 1; i < lines.length && lines[i]!.trim() && !lines[i]!.includes('Click'); i++) title += ' ' + lines[i]!.trim(); const mainName = sentenceCase(title.replace(/[.,]\s*$/, '')); for (const c of [tm[1]!, tm[2]].filter(Boolean) as string[]) MAIN[c] = MAIN_FIXES[mainName] ?? mainName; // Summary list at top: "Subclass QA Mathematics" with indented wrapped continuations. for (let i = ti; i < lines.length; i++) { const l = lines[i]!; if (/^\s*Subclass [A-Z]+\s*$/.test(l) || /^[A-Z]{1,3}\d/.test(l)) break; // detail section starts const m = l.match(/^\s*Subclass ([A-Z]{1,3})\s{2,}(\S.*)$/); if (!m) continue; let cap = m[2]!; while (i + 1 < lines.length && /^\s{4,}\S/.test(lines[i + 1]!) && !/^\s*Subclass /.test(lines[i + 1]!)) cap += ' ' + lines[++i]!.trim(); cap = clean(cap).replace(/\.$/, ''); SUB[m[1]!] = shorten(SUB_FIXES[cap] ?? cap); } } const q = (s: string) => JSON.stringify(s); const rec = (o: Record) => Object.keys(o).sort().map((k) => ` ${k}: ${q(o[k]!)},`).join('\n'); const src = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand. // Source: Library of Congress Classification Outline, ${INDEX} // (a US government publication). Re-run: node scripts/gen-lcc-outline.ts export const MAIN_CLASSES: Record = { ${rec(MAIN)} }; export const SUBCLASSES: Record = { ${rec(SUB)} }; export function classNames(letters: string): { className: string | null; subclassName: string | null } { const l = letters.trim().toUpperCase(); if (!/^[A-Z]{1,3}$/.test(l)) return { className: null, subclassName: null }; const className = MAIN_CLASSES[l[0]!] ?? null; const subclassName = SUBCLASSES[l] ?? (l.length === 3 ? (SUBCLASSES[l.slice(0, 2)] ?? null) : null); return { className, subclassName }; } `; writeFileSync(out, src); console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`); const rangesSrc = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand. // Source: Library of Congress Classification Outline, ${INDEX} // (a US government publication). Re-run: node scripts/gen-lcc-outline.ts // Server only: the web app does not import this file. /** [lo, hi, caption], or [lo, hi, caption, cutterLo, cutterHi] for a range bounded by cutters. Captions are verbatim. */ export type OutlineRange = [lo: number, hi: number, caption: string, cutterLo?: string, cutterHi?: string]; /** Every range of the outline by class letters, in outline order (a range comes before the ranges nested in it). */ export const OUTLINE_RANGES: Record = { ${[...RANGES.keys()].sort().map((k) => ` ${k}: [\n${RANGES.get(k)!.map((r) => ' ' + JSON.stringify(r)).join(',\n')},\n ],`).join('\n')} }; `; writeFileSync(outRanges, rangesSrc); const perClass: Record = {}; for (const [k, rows] of RANGES) perClass[k[0]!] = (perClass[k[0]!] ?? 0) + rows.length; console.log(`wrote ${[...RANGES.values()].reduce((n, r) => n + r.length, 0)} ranges in ${RANGES.size} subclasses; per main class: ${Object.entries(perClass).map(([k, n]) => k + '=' + n).join(' ')}`);