# epub-codec [![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white)](https://github.com/ExaDev/documents.js/tree/main/packages/epub-codec) [![npm](https://img.shields.io/badge/npm-CB3837?logo=npm&logoColor=white)](https://www.npmjs.com/package/epub-codec) [![npm version](https://img.shields.io/npm/v/epub-codec)](https://www.npmjs.com/package/epub-codec) [![CI](https://img.shields.io/github/actions/workflow/status/ExaDev/documents.js/ci.yml?branch=main)](https://github.com/ExaDev/documents.js/actions) > A hand-written, dependency-minimal EPUB 2/3 codec: reads flowable EPUB 2 and EPUB 3 packages into the shared [document-schema.js](../document-schema.js/README.md) content pivot, and writes deterministic, minimal EPUB 3. Built on [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser), [fflate](https://github.com/101arrowz/fflate), and [Zod 4](https://zod.dev). An EPUB decomposes into two things this family already does well: an OCF ZIP container with a manifest and a fixed first entry — structurally `odf.js`/`ooxml.js` territory — whose payload is flowable block content in well-formed XHTML — semantically `markdown-codec` territory, since EPUB 3.3 requires its content documents to be real XML, not tag-soup HTML. This package sits at exactly that intersection: its OCF/ZIP layer and XML parse/build wrapper mirror the conventions those siblings already established (hand-duplicated, not imported — see [Architecture](#architecture) for why), and its XHTML-to-`ContentDocument` mapping is the closest relative `markdown-codec`'s own AST-to-`ContentDocument` lowering has in this family. ```mermaid graph TD schema("document-schema.js") bytes("byte-codec") epubcodec("epub-codec") schema --> epubcodec bytes --> epubcodec click schema "https://github.com/ExaDev/documents.js/tree/main/packages/document-schema.js" "document-schema.js" click bytes "https://github.com/ExaDev/documents.js/tree/main/packages/byte-codec" "byte-codec" click epubcodec "https://github.com/ExaDev/documents.js/tree/main/packages/epub-codec" "epub-codec" style epubcodec fill:#f9a825,stroke:#333,stroke-width:3px ``` `epub-codec` depends on `document-schema.js` for the content pivot and on `byte-codec` for base64 — see [Dependency choices](#dependency-choices) for why it does _not_ depend on `archive-codec`, and why `byte-codec` carries the base64 but not this package's image-dimension reading. Wiring this package into `documents.js`'s conversion engine, `document-cli`, `document-mcp`, or the web UI is explicitly out of scope here — see [ExaDev/documents.js#802](https://github.com/ExaDev/documents.js/issues/802), a separate, already-filed follow-up blocked on this package existing at all. ## Scope **Flowable EPUB only.** Fixed-layout EPUB (FXL, `rendition:layout-pre-paginated`) is fixed-page geometry — closer to `pdf-codec`'s own private layout representation than to flowable content — and is not specially detected or rejected; an FXL package's XHTML still reads as ordinary flowable content, just without the positioning its `properties="rendition:layout-pre-paginated"` metadata was asking a reading system to honour. **Read EPUB 2 and EPUB 3. Write EPUB 3 only.** `readEpub`/`readEpubContent` accept either; `writeEpub`/`writeEpubContent` always produce a minimal, spec-valid EPUB 3 package, matching how this family already treats legacy format quirks elsewhere (read, never re-emitted). ## Getting started Requires Node.js `>=20` and pnpm (the version pinned as `packageManager` in `package.json`). ```sh pnpm install ``` Install as a dependency in another project: ```sh pnpm add epub-codec # or npm install epub-codec ``` ## Usage Reading and writing EPUB bytes, at the tree level (the primary API — [document-schema.js](../document-schema.js/README.md)'s `DocumentTree`, matching `markdown-codec`'s identical dual-level convention): ```ts import { readEpub, writeEpub } from "epub-codec"; const tree = readEpub(epubBytes); // -> DocumentTree, kind: 'wordprocessing' // tree.children is one section group per spine itemref, in spine order — headings, lists, and // footnote/blockquote constructs already promoted into their own groups by document-schema.js's assembleTree. const bytes = writeEpub(tree); // a fresh, minimal, spec-valid EPUB 3 ``` The flat pair one level down (`ContentDocument`, the codec-exchange shape every reader/writer in this family actually reads and writes): ```ts import { readEpubContent, writeEpubContent } from "epub-codec"; const { sections, metadata } = readEpubContent(epubBytes); // ContentDocument, kind: 'wordprocessing' const bytes = writeEpubContent({ kind: "wordprocessing", metadata, sections }); ``` Both accept an optional `sink` (`EpubDiagnosticSink`, called once per recoverable read issue or unrepresentable construct — see [Conventions](#conventions) for the three-tier policy this shares with `markdown-codec`/`pdf-codec`): ```ts import { readEpubContent } from "epub-codec"; const document = readEpubContent(epubBytes, { sink: (diagnostic) => console.warn(diagnostic.code, diagnostic.message), }); ``` The same round trip as a schema-validated [`z.codec()`](https://zod.dev) pair, mirroring `markdown-codec`'s `markdownCodec`/`markdownContentCodec`: ```ts import { z } from "zod"; import { epubCodec, epubContentCodec } from "epub-codec"; const tree = z.decode(epubCodec, epubBytes); // throws a ZodError if epubBytes has no zip header const bytes2 = z.encode(epubCodec, tree); ``` This is the no-extra-options form only — `readEpub(Content)`/`writeEpub(Content)` remain the entry points for a diagnostic sink. The lossless byte-level `Package` (ExaDev/documents.js#963), for a caller that wants a genuine EPUB-to-EPUB round trip with no `ContentDocument`/`DocumentTree` projection in between — `readEpub(Content)`/`writeEpubContent` already cross this exact boundary internally, so reaching for it directly is for a caller inspecting or editing raw parts, not a prerequisite for ordinary reading/writing: ```ts import { decodePackage, encodePackage } from "epub-codec"; const pkg = decodePackage(epubBytes); // -> { parts: Record }, every zip entry as XML nodes or base64 bytes const bytes2 = encodePackage(pkg); // decode -> encode is a fixed point: bytes2 carries the identical part content ``` Unlike `ooxml.js`/`odf.js`, neither of which offers a one-shot bytes-in convenience at all (their own typed readers take an already-decoded `Package`, e.g. `readDocx(decodePackage(bytes))`), `readEpub(Content)`/`writeEpub(Content)` above stay this package's own established bytes-in/bytes-out API — `decodePackage`/`encodePackage` are additive, not a replacement for it. One spine itemref becomes one `ContentSection`, in spine order — **every** itemref, including one marked `linear="no"` (an EPUB 2 idiom for supplementary content, most often a footnote/endnote page): this package reads it as an ordinary section rather than silently skipping real content a reading system happens to route around. EPUB has no page concept of its own, so every section is given the same invented A4 + 1in default geometry (`ReadEpubOptions`/`WriteEpubOptions` carry no override for this, unlike `markdown-codec`'s `pageSize`/`margins` options — nothing in this package's own scope needs one yet). ## Architecture Layered from the lossless OCF/XML primitives outward to the XHTML-to-`ContentDocument` mapping itself: - **`src/zip.ts`** — the OCF ZIP container: fixed-mtime, ordered-entries `zipPackage`/`unzipPackage` over `fflate`, hand-duplicated from `ooxml.js`'s and `odf.js`'s own identical wrappers rather than depending on `archive-codec` — see [Dependency choices](#dependency-choices). - **`src/xml/`** — the lossless XML layer every other module in this package builds on: `parse.ts`/`build.ts` wrap `fast-xml-parser` with the identical `preserveOrder` configuration `ooxml.js`'s and `odf.js`'s own XML modules use (order and mixed content survive; entity encoding stays raw until `entities.ts` decodes it in the one place text actually becomes content), `query.ts` the same handful of tree-walking helpers (`rootElement`, `findChildElement`, `childrenWithTag`, `elementsWithTag`, `attrValue`, plus `findElement` and `textContent`, needed here for footnote-target and nav-toc resolution respectively), `node.ts` the ordered `XmlNode` forest itself — also the shape `src/model/package.ts`'s own `XmlPart` carries. - **`src/model/package.ts`/`src/package-io/`** — the lossless byte-level `Package` model (ExaDev/documents.js#963), mirroring `ooxml.js`'s and `odf.js`'s own `model/package.ts`/`package-io/` exactly: every zip entry as a `Part` (an `XmlNode[]` forest, or raw base64 bytes), `read.ts`'s `parsePackage`/`packageFromEntries` classifying entries into parts, `write.ts`'s `serializePackage`/`packageToEntries` the structural inverse (including the OCF mimetype-first-stored hoist). `src/codec.ts` wraps the pair as `decodePackage`/`encodePackage`; `src/read.ts`/`src/write.ts` cross this same boundary internally rather than talking to `src/zip.ts` directly. - **`src/ocf/`** — `container.ts` resolves the OPF rootfile from `META-INF/container.xml` (EPUB 3.3 §6.7.2); `write.ts` is its structural inverse. - **`src/opf/`** — `parse.ts`/`write.ts` read and write the OPF package document (§5.4): Dublin Core metadata (`metadata.ts`), the manifest, and the spine. - **`src/nav/`** — `nav3.ts`/`ncx.ts` reduce the EPUB 3 `