/** * A BOOK'S OWN FILE FILLS ITS EMPTY COLUMNS IN THE OBJECT (lane * books-opf-rule, 7 Nov 2026): whoever writes a `book` row naming an EPUB * (the phone, Cotton Fetch, MCP, an import), the object reads the EPUB's * package document from its media and fills what the row leaves empty, by * the one OPF rule the phone's core and the Mac fetcher run * (crates/cotton-rules opf.rs, as WASM: `book.container` finds the package, * `book.opf` reads it). Every column it fills is the book's (author, * publisher, description, subjects, ISBN, DOI, Open Library work and edition, * language, year, series and its number), and only an empty one: what a * person or another source wrote stays. The title is never written here (a * book always has one), nor the cover (the artwork engine's) or the rating. * * Each fill says itself in the book's `filled_from` as `opf`, beside what * other sources said (books.ts `stampFilled`); a pass that fills nothing * writes nothing, so no stamp. * * ONE READ PER FILE (`book_file_seen`): each book is read once for the file * it names, and what came of it is kept: `filled`, `nothing` (the package * filled nothing empty), `unreadable` (no zip, no package: never read again * until its file changes), `absent` (the media holds no such file yet: the * row came before its upload) or `failed` (the media did not answer); those * two are read again after RETRY_MS. It runs off the request that wrote a * book (src/business.ts `kickBookFiles`) and on the object's alarm; a pass * reads at most PER_PASS books, the newest written first. */importtype { Engine, Outcome } from"./engine.ts";import { stampFilled } from"./books.ts";import { tryRule } from"./rules/index.ts";importtype { Store } from"./store.ts";exportconst BOOK = "book";/** Books read in one pass: each is three or four ranged reads of its file. */exportconst PER_PASS = 10;/** A file not there yet, or a read the media did not answer, is tried again after this long. */exportconst RETRY_MS = 60 * 60 * 1000;/** The most a container or a package document may inflate to: metadata, never megabytes (as the core reads it). */exportconst MOST_PACKAGE_BYTES = 4 * 1024 * 1024;const SCHEMA = "CREATE TABLE IF NOT EXISTS book_file_seen (id TEXT PRIMARY KEY, file TEXT NOT NULL, outcome TEXT NOT NULL, at INTEGER NOT NULL)";/** A file read by range: its size, and `length` bytes at `offset`. */exportinterfaceRanged { size: number; read(offset: number, length: number): Promise<Uint8Array>;}/** What the pass needs of the object: its store and SQL, one write in its own transaction and version, and a book's file by its media key (null when the media holds none). */exportinterfaceBookFileHost { store: Store; sql: SqlStorage; write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T; open(key: string): Promise<Ranged | null>;}/** A file that is no EPUB this reads: said, and not read again until the row names another file. */exportclassUnreadableextendsError {}/** The book's file is sealed on the person's device (R6): the object reads nothing of it, and the device's core fills the columns itself. */exportclassSealedextendsError {}// ── the zip ──────────────────────────────────────────────────────────────interfaceEntry { name: string; method: number; flags: number; compressed: number; size: number; local: number;}const EOCD = 0x06054b50;const CENTRAL = 0x02014b50;const LOCAL = 0x04034b50;/** The end record (22 bytes) and the longest comment a zip may carry. */const TAIL = 22 + 0xffff;/** Every entry the zip's central directory names. A ZIP64 or a split archive is no EPUB this reads. */exportasyncfunction entries(file: Ranged): Promise<Entry[]> {if (file.size < 22) thrownewUnreadable("it is too short to be a zip");const tailAt = Math.max(0, file.size - TAIL);const tail = await file.read(tailAt, file.size - tailAt);const tv = newDataView(tail.buffer, tail.byteOffset, tail.byteLength);let end = -1;for (let i = tail.byteLength - 22; i >= 0; i--) {if (tv.getUint32(i, true) === EOCD) { end = i;break; } }if (end < 0) thrownewUnreadable("it is not a zip");const count = tv.getUint16(end + 10, true);const length = tv.getUint32(end + 12, true);const offset = tv.getUint32(end + 16, true);if (count === 0xffff || length === 0xffffffff || offset === 0xffffffff) thrownewUnreadable("it is a ZIP64, which this does not read");if (offset + length > file.size) thrownewUnreadable("its directory lies past its end");const dir = await file.read(offset, length);const dv = newDataView(dir.buffer, dir.byteOffset, dir.byteLength);const names = newTextDecoder();const out: Entry[] = [];let at = 0;for (let n = 0; n < count; n++) {if (at + 46 > dir.byteLength || dv.getUint32(at, true) !== CENTRAL) thrownewUnreadable("its directory does not read");const nameLength = dv.getUint16(at + 28, true);const extra = dv.getUint16(at + 30, true);const comment = dv.getUint16(at + 32, true); out.push({ flags: dv.getUint16(at + 8, true), method: dv.getUint16(at + 10, true), compressed: dv.getUint32(at + 20, true), size: dv.getUint32(at + 24, true), local: dv.getUint32(at + 42, true), name: names.decode(dir.subarray(at + 46, at + 46 + nameLength)), }); at += 46 + nameLength + extra + comment; }return out;}/** One entry's bytes as text: stored or deflated, never encrypted, at most MOST_PACKAGE_BYTES. */exportasyncfunction entryText(file: Ranged, entry: Entry): Promise<string> {if (entry.flags & 1) thrownewUnreadable(`its ${entry.name} is encrypted`);if (entry.size > MOST_PACKAGE_BYTES || entry.compressed > MOST_PACKAGE_BYTES) thrownewUnreadable(`its ${entry.name} is larger than a package document is`);const header = await file.read(entry.local, 30);const hv = newDataView(header.buffer, header.byteOffset, header.byteLength);if (header.byteLength < 30 || hv.getUint32(0, true) !== LOCAL) thrownewUnreadable(`its ${entry.name} does not read`);const start = entry.local + 30 + hv.getUint16(26, true) + hv.getUint16(28, true);const data = entry.compressed ? await file.read(start, entry.compressed) : newUint8Array();if (entry.method === 0) returnnewTextDecoder().decode(data);if (entry.method !== 8) thrownewUnreadable(`its ${entry.name} is packed a way this does not read (method ${entry.method})`);try {const inflated = newBlob([data]).stream().pipeThrough(newDecompressionStream("deflate-raw"));returnawaitnewResponse(inflated).text(); } catch {thrownewUnreadable(`its ${entry.name} will not inflate`); }}/** The facts `book.opf` answers that the pass uses: the book columns they fill. */interfaceOpfAnswer { columns: Record<string, string | number>;}function ruled<T>(name: string, input: unknown): T {const out = tryRule<T>(name, input);if ("error"in out) thrownewUnreadable(out.error);return out.ok;}/** What the EPUB says of itself, by the rule: the book columns its package fills. */exportasyncfunction packageColumns(file: Ranged): Promise<Record<string, string | number>> {const all = await entries(file);const named = (name: string) => all.find((e) => e.name === name);const container = named("META-INF/container.xml");if (!container) thrownewUnreadable("it names no package document (META-INF/container.xml)");const { opf_path } = ruled<{ opf_path: string | null }>("book.container", { xml: await entryText(file, container) });if (!opf_path) thrownewUnreadable("its container names no package document");const opf = named(opf_path);if (!opf) thrownewUnreadable(`its package names ${opf_path}, which it does not hold`);return ruled<OpfAnswer>("book.opf", { opf: await entryText(file, opf) }).columns;}// ── the pass ─────────────────────────────────────────────────────────────typeSeen = "filled" | "nothing" | "unreadable" | "absent" | "failed" | "sealed";exportfunction ready(host: Pick<BookFileHost, "sql">): void { host.sql.exec(SCHEMA);}/** Whether book rows were written since `version`. */exportfunction touched(store: Store, version: number): boolean {// Along rows_cursor: only the rows written since (a few). By the table's own index it read every row of the table, after every write (LIVE CPU 2, 23 Nov 2026: 50,000 events on an object of his shape).return store.query<{ n: number }>("SELECT count(*) AS n FROM (SELECT 1 FROM rows INDEXED BY rows_cursor WHERE version > ? AND table_id = ? LIMIT 1)", version, BOOK)[0]!.n > 0;}function due(host: BookFileHost, now: number, limit: number): { id: string; file: string }[] {return host.store.query<{ id: string; file: string }>(`SELECT r.id AS id, json_extract(r.data, '$.file') AS file FROM rows r LEFT JOIN book_file_seen s ON s.id = r.id WHERE r.table_id = ? AND r.deleted = 0 AND lower(COALESCE(json_extract(r.data, '$.file'), '')) LIKE '%.epub' AND (s.file IS NULL OR s.file != json_extract(r.data, '$.file') OR (s.outcome IN ('absent', 'failed') AND s.at <= ?)) ORDER BY r.version DESC, r.id LIMIT ?`, BOOK, now - RETRY_MS, limit, );}/** Whether any book waits for its file to be read. */exportfunction pending(host: BookFileHost, now = Date.now()): boolean { ready(host);return due(host, now, 1).length > 0;}function mark(host: Pick<BookFileHost, "sql">, id: string, file: string, outcome: Seen, at: number): void { host.sql.exec("INSERT INTO book_file_seen (id, file, outcome, at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET file = excluded.file, outcome = excluded.outcome, at = excluded.at", id, file, outcome, at, );}const empty = (value: unknown): boolean => value === null || value === undefined || (typeof value === "string" && !value.trim());/** The book's empty columns its package fills, as the object defines the table; the row unchanged when it names another file now. */function fill(engine: Engine, version: number, outcome: Outcome, id: string, file: string, columns: Record<string, string | number>): string[] | null {const row = engine.store.get(BOOK, id);if (!row || row.data.file !== file) returnnull;const defined = newSet((engine.defs.table(BOOK)?.columns ?? []).map((c) => c.key));const patch = Object.fromEntries(Object.entries(columns).filter(([k]) => k !== "title" && defined.has(k) && empty(row.data[k])));if (!Object.keys(patch).length) return []; engine.update(row, { ...patch, ...stampFilled(engine, row.data.filled_from, Object.keys(patch), "opf") }, version, outcome);returnObject.keys(patch);}/** What a pass did. */exportinterfaceBookFileAnswer { filled: number; nothing: number; unreadable: number;/** Books whose file is sealed: never read here, never again until it changes. */ sealed: number; absent: number; failed: number;/** The pass stopped at its bound with books still to read. */ more: boolean;}/** One pass over the books whose file waits to be read (see above). Never throws: a book that fails is marked and said. */exportasyncfunction pass(host: BookFileHost, now = Date.now()): Promise<BookFileAnswer> { ready(host);const answer: BookFileAnswer = { filled: 0, nothing: 0, unreadable: 0, absent: 0, failed: 0, sealed: 0, more: false };const rows = due(host, now, PER_PASS + 1);if (rows.length > PER_PASS) answer.more = true;for (const { id, file } of rows.slice(0, PER_PASS)) {const named = `book ${id}`;let seen: Seen;try {const opened = await host.open(file);if (!opened) { seen = "absent"; console.log(`cottondb: book file ${named}: ${file} is not in the media yet; read again in an hour`); } else {const columns = await packageColumns(opened);const wrote = host.write((engine, version, outcome) => fill(engine, version, outcome, id, file, columns));if (wrote === null) continue; // it names another file now: the next pass reads that one seen = wrote.length ? "filled" : "nothing";if (wrote.length) console.log(`cottondb: book file ${named}: filled ${wrote.join(", ")}`); } } catch (error) {const words = error instanceofError ? error.message : String(error);if (error instanceofSealed) { mark(host, id, file, "sealed", now); answer.sealed++;continue; } seen = error instanceofUnreadable ? "unreadable" : "failed"; console.log(`cottondb: book file ${named}: ${seen === "unreadable" ? `${file} cannot be read: ${words}` : `the media did not answer: ${words}; read again in an hour`}`); } mark(host, id, file, seen, now); answer[seen]++; }return answer;}