earshelf / source /src /parse.ts
WilburDev's picture
Deploy 2026-11-20T20:26Z
b1876f7 verified
Raw History Blame Contribute Delete
16.8 kB
// Turn a PDF / EPUB / TXT file into { title, author, chapters[] } entirely in the browser.
import JSZip from 'jszip';
import { cleanText } from './text';
export interface Chapter {
title: string;
text: string;
}
export interface ParsedBook {
title: string;
author: string;
format: 'pdf' | 'epub' | 'txt';
cover?: Blob;
chapters: Chapter[];
}
export class ParseError extends Error {}
export async function parseFile(file: File, onProgress?: (p: number) => void): Promise<ParsedBook> {
const name = file.name.toLowerCase();
const head = new Uint8Array(await file.slice(0, 5).arrayBuffer());
const isPdf = head[0] === 0x25 && head[1] === 0x50 && head[2] === 0x44 && head[3] === 0x46; // %PDF
const isZip = head[0] === 0x50 && head[1] === 0x4b; // PK
let book: ParsedBook;
if (isPdf || name.endsWith('.pdf')) book = await parsePdf(file, onProgress);
else if (isZip || name.endsWith('.epub')) book = await parseEpub(file);
else if (name.endsWith('.txt') || name.endsWith('.md') || file.type.startsWith('text/')) book = await parseTxt(file);
else throw new ParseError("This kind of file can't be opened. Use a PDF, EPUB or TXT (plain text) file.");
book.chapters = book.chapters
.map((c) => ({ title: c.title.trim() || 'Untitled', text: cleanText(c.text) }))
.filter((c) => c.text.length > 0);
if (!book.chapters.length) {
throw new ParseError(
book.format === 'pdf'
? 'This PDF looks like photos of pages, so there are no words to read. PDFs where you can select the words work.'
: 'No readable text found in this file.',
);
}
// ignore placeholder metadata that word processors and PDF tools write
if (!book.title || /^(untitled|document\d*|microsoft word\b.*|unknown|title|\s*-\s*)$/i.test(book.title.trim())) book.title = baseName(file.name);
if (/^(anonymous|unknown|author|user|admin)$/i.test(book.author.trim())) book.author = '';
return book;
}
function baseName(n: string) {
return n.replace(/\.[^.]+$/, '').replace(/[_]+/g, ' ').trim() || 'Untitled book';
}
/* ---------------- TXT ---------------- */
async function parseTxt(file: File): Promise<ParsedBook> {
const text = decodeText(new Uint8Array(await file.arrayBuffer())).replace(/\r\n?/g, '\n');
// Chapter headings: their own paragraph, a heading word, then a number / Roman numeral / number word.
const re = /(?:^|\n[ \t]*\n)[ \t]*((?:CHAPTER|Chapter|CHAPITRE|Chapitre|CAPÍTULO|Capítulo|CAPITULO|Capitulo|PART|Part|PARTE|Parte|LIVRE|Livre|BOOK|Book)\s+(?:\d+|[IVXLCDM]+|[A-Z][a-z]+|[A-ZÉ]+)\b[^\n]{0,70}(?:\n[ \t]*[^\n]{1,80})?)[ \t]*(?=\n[ \t]*\n|\n?$)/g;
const marks = [...text.matchAll(re)];
const chapters: Chapter[] = [];
if (marks.length >= 2) {
const first = marks[0].index ?? 0;
if (text.slice(0, first).trim().length > 200) chapters.push({ title: 'Opening', text: text.slice(0, first) });
marks.forEach((m, i) => {
const start = m.index ?? 0;
const end = i + 1 < marks.length ? (marks[i + 1].index ?? text.length) : text.length;
chapters.push({ title: m[1].trim().replace(/\s*\n\s*/, ' · '), text: text.slice(start + m[0].length, end) });
});
} else {
chapters.push(...chunkByLength(text, 'Part'));
}
return { title: baseName(file.name), author: '', format: 'txt', chapters };
}
function chunkByLength(text: string, label: string, size = 25000): Chapter[] {
if (text.length <= size * 1.3) return [{ title: label + ' 1', text }];
const out: Chapter[] = [];
let i = 0;
while (i < text.length) {
let end = Math.min(text.length, i + size);
if (end < text.length) {
const br = text.lastIndexOf('\n\n', end);
if (br > i + size * 0.5) end = br;
}
out.push({ title: `${label} ${out.length + 1}`, text: text.slice(i, end) });
i = end;
}
return out;
}
/* ---------------- PDF ---------------- */
async function parsePdf(file: File, onProgress?: (p: number) => void): Promise<ParsedBook> {
// legacy build: the modern one needs Promise.withResolvers etc. (breaks on iOS < 17.4, Chrome < 119)
const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/legacy/build/pdf.worker.min.mjs', import.meta.url).href;
const data = new Uint8Array(await file.arrayBuffer());
let doc;
const task = pdfjs.getDocument({ data });
try {
doc = await task.promise;
} catch (e: any) {
void task.destroy();
if (e?.name === 'PasswordException') throw new ParseError('This PDF is password-protected.');
throw new ParseError('This PDF could not be opened. The file may be damaged.');
}
const meta: any = await doc.getMetadata().catch(() => null);
const title = (meta?.info?.Title || '').trim();
const author = (meta?.info?.Author || '').trim();
try {
return await readPdf(doc, title, author, onProgress);
} finally {
void task.destroy(); // always free the pdf.js worker, also when a page fails
}
}
async function readPdf(doc: any, title: string, author: string, onProgress?: (p: number) => void): Promise<ParsedBook> {
// page texts
const pages: string[] = [];
for (let p = 1; p <= doc.numPages; p++) {
const page = await doc.getPage(p);
const content = await page.getTextContent();
let s = '';
let lastY: number | null = null;
let lastH = 10;
const brk = (n: 1 | 2) => {
s = s.replace(/[ \t]+$/, '');
const want = n === 2 ? '\n\n' : '\n';
if (n === 2) s = s.replace(/\n?$/, '') + want;
else if (!s.endsWith('\n')) s += want;
};
for (const it of content.items as any[]) {
if (!('str' in it)) continue;
if (it.str === '') {
if (it.hasEOL && s && !s.endsWith('\n')) s += '\n';
continue;
}
const y = it.transform?.[5];
if (lastY !== null && y !== undefined && s) {
const gap = Math.abs(y - lastY);
const h = it.height || lastH;
const sizeChange = Math.abs(h - lastH) > Math.min(h, lastH) * 0.2; // heading ↔ body text
if (gap > 2 && (gap > Math.min(h, lastH) * 1.6 || sizeChange)) brk(2); // blank space or new font size = new paragraph
else if (gap > 2) brk(1);
}
s += it.str;
if (it.hasEOL) s += '\n';
if (y !== undefined) lastY = y;
if (it.height) lastH = it.height;
}
pages.push(stripPageFurniture(s));
page.cleanup();
onProgress?.(p / doc.numPages);
}
// chapters from the outline when it exists
const chapters: Chapter[] = [];
try {
const outline = await doc.getOutline();
if (outline && outline.length) {
const marks: { title: string; page: number }[] = [];
for (const item of outline) {
let dest: any = item.dest;
if (typeof dest === 'string') dest = await doc.getDestination(dest);
if (!Array.isArray(dest) || !dest[0]) continue;
const idx = await doc.getPageIndex(dest[0]).catch(() => -1);
if (idx >= 0) marks.push({ title: item.title, page: idx });
}
marks.sort((a, b) => a.page - b.page);
const uniq = marks.filter((m, i) => i === 0 || m.page !== marks[i - 1].page);
if (uniq.length >= 2) {
if (uniq[0].page > 0) chapters.push({ title: 'Opening', text: pages.slice(0, uniq[0].page).join('\n\n') });
uniq.forEach((m, i) => {
const end = i + 1 < uniq.length ? uniq[i + 1].page : pages.length;
chapters.push({ title: m.title, text: pages.slice(m.page, Math.max(end, m.page + 1)).join('\n\n') });
});
}
}
} catch {
/* outline is optional */
}
if (!chapters.length) {
const per = 10;
for (let i = 0; i < pages.length; i += per) {
const end = Math.min(pages.length, i + per);
chapters.push({ title: pages.length <= per ? 'All pages' : `Pages ${i + 1}–${end}`, text: pages.slice(i, end).join('\n\n') });
}
}
return { title, author, format: 'pdf', chapters };
}
/** Remove lines that are only page numbers. */
function stripPageFurniture(s: string): string {
return s
.split('\n')
.filter((l) => !/^\s*(page\s*)?\d{1,4}\s*(of\s*\d+)?\s*$/i.test(l))
.join('\n');
}
/* ---------------- EPUB ---------------- */
async function parseEpub(file: File): Promise<ParsedBook> {
let zip: JSZip;
try {
zip = await JSZip.loadAsync(file);
} catch {
throw new ParseError('This EPUB could not be opened. The file may be damaged.');
}
const read = async (path: string) => {
let f = zip.file(path);
if (!f) {
try {
f = zip.file(decodeURIComponent(path));
} catch {
/* a literal % in the name */
}
}
if (!f) return null;
return decodeText(await f.async('uint8array'), true);
};
const xml = (s: string, type: DOMParserSupportedType = 'application/xml') => new DOMParser().parseFromString(s, type);
const container = await read('META-INF/container.xml');
if (!container) throw new ParseError("This EPUB file is damaged or incomplete, so it can't be opened.");
const opfPath = xml(container).querySelector('rootfile')?.getAttribute('full-path');
if (!opfPath) throw new ParseError("This EPUB file is damaged or incomplete, so it can't be opened.");
const opfText = await read(opfPath);
if (!opfText) throw new ParseError("This EPUB file is damaged or incomplete, so it can't be opened.");
if (zip.file('META-INF/rights.xml')) throw new ParseError("This book is copy-protected by the store it came from, so EarShelf can't read it. Books without copy protection work.");
const encXml = await read('META-INF/encryption.xml');
if (encXml) {
// font obfuscation (IDPF / Adobe) is fine; any other encryption of a non-font file is DRM
const enc = xml(encXml);
for (const ed of Array.from(enc.getElementsByTagNameNS('*', 'EncryptedData'))) {
const alg = ed.getElementsByTagNameNS('*', 'EncryptionMethod')[0]?.getAttribute('Algorithm') || '';
const uri = ed.getElementsByTagNameNS('*', 'CipherReference')[0]?.getAttribute('URI') || '';
const fontObfuscation = alg === 'http://www.idpf.org/2008/embedding' || alg === 'http://ns.adobe.com/pdf/enc#RC';
if (!fontObfuscation && !/\.(otf|ttf|woff2?)$/i.test(uri)) throw new ParseError("This book is copy-protected by the store it came from, so EarShelf can't read it. Books without copy protection work.");
}
}
const opf = xml(opfText);
const dir = opfPath.includes('/') ? opfPath.slice(0, opfPath.lastIndexOf('/') + 1) : '';
const resolve = (href: string, base = dir) => normalizePath(base + href.split('#')[0]);
const text = (sel: string) => opf.getElementsByTagNameNS('*', sel)[0]?.textContent?.trim() || '';
const title = text('title');
const author = text('creator');
const manifest = new Map<string, { href: string; type: string; props: string }>();
for (const it of Array.from(opf.getElementsByTagNameNS('*', 'item'))) {
manifest.set(it.getAttribute('id') || '', {
href: resolve(it.getAttribute('href') || ''),
type: it.getAttribute('media-type') || '',
props: it.getAttribute('properties') || '',
});
}
// cover
let cover: Blob | undefined;
try {
let coverItem = [...manifest.values()].find((m) => m.props.includes('cover-image'));
if (!coverItem) {
const metaCover = Array.from(opf.getElementsByTagNameNS('*', 'meta')).find((m) => m.getAttribute('name') === 'cover');
const id = metaCover?.getAttribute('content');
if (id) coverItem = manifest.get(id);
}
if (coverItem && coverItem.type.startsWith('image/')) {
const f = zip.file(coverItem.href);
if (f) cover = new Blob([await f.async('arraybuffer')], { type: coverItem.type });
}
} catch {
/* optional */
}
// toc titles: EPUB3 nav, else NCX
const tocTitles = new Map<string, string>();
const navItem = [...manifest.values()].find((m) => m.props.split(/\s+/).includes('nav'));
if (navItem) {
const nav = await read(navItem.href);
if (nav) {
const d = xml(nav, 'application/xhtml+xml');
const navBase = navItem.href.slice(0, navItem.href.lastIndexOf('/') + 1);
for (const a of Array.from(d.getElementsByTagName('a'))) {
const href = a.getAttribute('href');
if (href && !tocTitles.has(resolve(href, navBase))) tocTitles.set(resolve(href, navBase), a.textContent?.trim() || '');
}
}
}
if (!tocTitles.size) {
const tocId = opf.getElementsByTagNameNS('*', 'spine')[0]?.getAttribute('toc');
const ncxItem = (tocId && manifest.get(tocId)) || [...manifest.values()].find((m) => m.type === 'application/x-dtbncx+xml');
if (ncxItem) {
const ncx = await read(ncxItem.href);
if (ncx) {
const d = xml(ncx);
const ncxBase = ncxItem.href.slice(0, ncxItem.href.lastIndexOf('/') + 1);
for (const np of Array.from(d.getElementsByTagNameNS('*', 'navPoint'))) {
const src = np.getElementsByTagNameNS('*', 'content')[0]?.getAttribute('src');
const label = np.getElementsByTagNameNS('*', 'text')[0]?.textContent?.trim();
if (src && label && !tocTitles.has(resolve(src, ncxBase))) tocTitles.set(resolve(src, ncxBase), label);
}
}
}
}
const chapters: Chapter[] = [];
const spine = Array.from(opf.getElementsByTagNameNS('*', 'itemref'));
for (const ref of spine) {
const item = manifest.get(ref.getAttribute('idref') || '');
if (!item || !/html|xml/.test(item.type)) continue;
if (item === navItem) continue;
const src = await read(item.href);
if (!src) continue;
let d = xml(src, 'application/xhtml+xml');
if (d.getElementsByTagName('parsererror').length) d = xml(src, 'text/html');
const body = d.getElementsByTagName('body')[0];
if (!body) continue;
const t = htmlToText(body);
if (t.replace(/\s/g, '').length < 2) continue;
const heading = body.querySelector('h1,h2,h3')?.textContent?.trim();
const title = tocTitles.get(item.href) || heading || `Section ${chapters.length + 1}`;
chapters.push({ title, text: t });
}
return { title, author, format: 'epub', cover, chapters };
}
const BLOCK = new Set(['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LI', 'BLOCKQUOTE', 'SECTION', 'ARTICLE', 'TR', 'BR', 'PRE', 'HR', 'DT', 'DD', 'FIGCAPTION']);
const SKIP = new Set(['SCRIPT', 'STYLE', 'HEAD', 'NAV', 'svg', 'SVG', 'RT', 'RP']);
function htmlToText(root: Element): string {
let out = '';
const walk = (n: Node) => {
if (n.nodeType === 3) {
out += n.nodeValue;
return;
}
if (n.nodeType !== 1) return;
const el = n as Element;
const tag = el.tagName.toUpperCase();
if (SKIP.has(el.tagName) || SKIP.has(tag)) return;
// footnote reference markers like <sup><a>1</a></sup>
if ((tag === 'SUP' || tag === 'A') && /^\s*\[?\d{1,3}\]?\s*$/.test(el.textContent || '') && isNoteRef(el)) return;
const block = BLOCK.has(tag);
if (block) out += '\n\n';
for (const c of Array.from(el.childNodes)) walk(c);
if (block) out += '\n\n';
};
walk(root);
return out.replace(/[ \t]*\n[ \t]*/g, '\n').replace(/[^\S\n]+/g, ' ');
}
function isNoteRef(el: Element): boolean {
for (let e: Element | null = el; e && e.tagName.toUpperCase() !== 'P'; e = e.parentElement) {
const t = e.tagName.toUpperCase();
if (t === 'SUP') return true;
if (t === 'A') {
const type = e.getAttributeNS('http://www.idpf.org/2007/ops', 'type') || e.getAttribute('epub:type') || '';
if (/noteref/.test(type) || e.getAttribute('role') === 'doc-noteref') return true;
}
}
return false;
}
/** Decode bytes: BOM, then the XML-declared encoding, then strict UTF-8, else Windows-1252. */
export function decodeText(bytes: Uint8Array, isXml = false): string {
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) return new TextDecoder('utf-8').decode(bytes.subarray(3));
if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder('utf-16le').decode(bytes.subarray(2));
if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder('utf-16be').decode(bytes.subarray(2));
if (isXml) {
const head = new TextDecoder('latin1').decode(bytes.subarray(0, 200));
const enc = head.match(/encoding=["']([\w.-]+)["']/i)?.[1];
if (enc && !/^utf-?8$/i.test(enc)) {
try {
return new TextDecoder(enc).decode(bytes);
} catch {
/* unknown label: fall through */
}
}
}
try {
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch {
return new TextDecoder('windows-1252').decode(bytes);
}
}
function normalizePath(p: string): string {
const parts: string[] = [];
for (const seg of p.split('/')) {
if (seg === '..') parts.pop();
else if (seg !== '.' && seg !== '') parts.push(seg);
}
try {
return decodeURIComponent(parts.join('/'));
} catch {
return parts.join('/');
}
}