epubsite
v0.9.14
Published
Zero-rewrite EPUB to static single-page reader. Ships an EPUB byte-for-byte and layers an htmx reading experience on top.
Maintainers
Readme
epubsite
Publish an EPUB as a real static website — without rewriting a single byte of the book.
epubsite takes an .epub file and produces a folder you can drop on any static
host. The book's own files are copied out verbatim, at their own paths, with
their own bytes. A reading shell — sidebar, client-side navigation, full-text
search, dark mode — is layered on top from a reserved namespace beside them.
$ npx epubsite childrens-literature.epub
Built 3 chapters, 7 resources (630.0 kB) into ./distNo server, no database, no CDN, no runtime dependencies. Just files.
Install
Requires Node.js ≥ 20.11.
# one-off, no install
npx epubsite book.epub
# or install it
npm install --global epubsite
epubsite book.epubInside this repository, use the bundled script:
npm install
# enable search of on the website
npm run epubsite -- book.epub --search
# or not
# npm run epubsite -- book.epub
cd dist
# host static website for your epub! (surge is an app help you deploy static website)
surge . https://book-name-of-your-choice.surge.sh/
Package metadata
The npm package is described by the root package.json.
It requires Node.js ≥ 20.11, exposes the epubsite executable through
build/bin/epubsite.js, and exposes the library API through
build/index.js with TypeScript declarations at build/index.d.ts.
The package publishes only the built artifacts, vendored browser assets, documentation, and license files:
build/ compiled CLI, library, and browser runtime
vendor/ vendored htmx and its license
README.md
LICENSEThe root package.json is also exported as epubsite/package.json, so tools
can inspect the installed package metadata without relying on the caller's
working directory. Runtime dependencies are limited to htmlparser2 and
yauzl; Pagefind is an external tool used only when --search is requested.
Usage
epubsite <book.epub> [options]s
epubsite serve [dir]Quick start
# Build into ./dist
epubsite moby-dick.epub
# Build into a specific directory, wiping it first
epubsite moby-dick.epub -o public --clean
# Preview it locally
epubsite serve public
# → http://127.0.0.1:8080/Deploying to a subdirectory
If the site will live at https://example.com/books/moby/, say so — this is what
makes the reader's assets and links resolve correctly:
epubsite moby-dick.epub --base-url /books/moby/ -o publicWith a full URL, the build can also emit the landing page's canonical link and
write the chapter nodes' static url: it knows the origin, so it can write an
absolute address instead of leaving the field out.
The canonical tag describes the landing page and nothing else. The reader
withdraws it the moment a chapter is on screen and puts it back when you return,
because "this document lives at epubsite.html" is true of the landing page and
false of a chapter — said about a chapter, it tells a search engine that every
chapter is a duplicate of the front page. A chapter is deliberately given no
canonical at all, in either of the two addresses it is reachable at. A path-only
base URL cannot produce any of this, because it does not know the origin.
epubsite moby-dick.epub --base-url https://example.com/books/moby/Either way, the reader itself fills url in at runtime — see
the token protocol below.
Adding search
epubsite moby-dick.epub --searchSearch is powered by Pagefind. The build looks for the
binary on your PATH, then in node_modules/.bin, then falls back to npx. If
it cannot find it, the build still succeeds — it prints a warning, and the
rest of the site is complete and correct:
warning W_SEARCH_UNAVAILABLE: the Pagefind binary could not be found; no search
index was generated.Pass --pagefind ./path/to/pagefind to point at a specific binary.
Pagefind is deliberately not a dependency of this package, and the search index is built over the spine only — the reader's own pages are never indexed as part of the book.
Checking before you write
epubsite moby-dick.epub --dry-run --verbose--dry-run validates the book and reports everything it found without touching
the filesystem. --json makes the result machine-readable:
epubsite moby-dick.epub --dry-run --json | jq '.stats'Options
| Option | Default | Description |
|---|---|---|
| -o, --out <dir> | ./dist | Output directory, relative to your shell's cwd. |
| --name <file> | epubsite.html | Name of the reader shell. Must not be index.html. |
| --base-url <url> | / | Where the site will be deployed. Path form (/sub/) or absolute (https://host/sub/), which additionally enables the landing page's canonical link and the static JSON-LD url. |
| --hosting <mode> | 404 | none | 404 | rewrite | all. See Hosting. |
| --json-ld <mode> | full | full | thin | none. How much Schema.org data to emit. |
| --no-json-ld | | Shorthand for --json-ld none. |
| --search | off | Build a Pagefind full-text index. |
| --pagefind <path> | auto | Explicit Pagefind binary. |
| --no-spa | | Multi-page site only — do not inject htmx. Every chapter link becomes a normal page load. |
| --pwa <bool> | true | true emits an installable offline PWA with a manifest and service worker; false omits all PWA output. |
| --theme <t> | auto | auto | light | dark. |
| --content-style <s> | book | book | reader. reader drops the book's own stylesheets and typesets its content with the reader's default, which follows --theme. See The reader's own style. |
| --clean | off | Delete the output directory first. |
| --force | off | Write into a non-empty output directory. |
| --dry-run | off | Validate and report, but write nothing. |
| --verbose | off | Explanatory detail on stderr. |
| --json | off | Machine-readable result on stdout. |
| -h, --help | | Usage. |
| -v, --version | | Version. |
serve additionally accepts --port <n> (default 8080; 0 picks a free port).
PWA output is enabled by default. The generated service worker precaches the
completed site, including a Pagefind index when --search produces one, so the
reader remains available offline after its first load. Use --pwa false for a
plain static site with no manifest, registration script, or service worker.
Offline token links such as /OPS/@chapter.xhtml are routed through the cached
404 guide, so shared reader links continue to work without a network
connection.
Stream discipline: the build result goes to stdout; warnings, errors and
progress go to stderr. epubsite book.epub > result.json is safe.
Why "zero-rewrite" is the whole point
Most EPUB-to-web converters rewrite the book: they flatten paths, strip the
package document, rewrite every href, and hand you back HTML that resembles
the book. That is lossy, and it silently breaks anything the converter did not
anticipate — embedded fonts, xml:lang, custom CSS, SVG, MathML.
epubsite does the opposite. The EPUB is a ZIP; the site is that same directory
tree, extracted. EPUB/s04.xhtml becomes /EPUB/s04.xhtml. META-INF/container.xml,
mimetype, the OPF, the NCX — all of it ships, unchanged.
Two consequences follow, and they are the reason this tool exists:
- Every chapter opens on its own.
https://example.com/EPUB/ch03.xhtmlis a real, working URL. It renders as a bare, readable page with no JavaScript, no shell, no build artifacts — because that is literally the file from the EPUB. Crawlers,curl, and JavaScript-disabled browsers all get the book. - Nothing can be broken by the conversion, because there is no conversion.
The reading experience is added beside the book, never over it:
dist/
├── EPUB/ ← the book, byte-for-byte
│ ├── package.opf
│ ├── nav.xhtml
│ ├── css/
│ ├── images/
│ └── s04.xhtml ← also a standalone, working page
├── META-INF/
├── mimetype
│
├── epubsite.html ┐
├── index.html │ the reserved namespace:
├── 404.html │ the reader, its assets and its metadata
├── publication.json │
├── .epubsite-root │
└── _epubsite_assets/ ┘
├── shell.js
├── shell.css
├── shell-data.json
├── htmx.esm.js
└── pagefind/ ← only with --searchepubsite refuses to build (exit 4) if the book already contains a file in that
namespace, rather than silently overwriting part of your book.
Features
| | |
|---|---|
| Zero-rewrite publishing | The book is extracted verbatim. Paths, bytes, metadata, fonts and CSS all survive. |
| Every chapter is a real page | Deep-linkable, crawlable, works without JavaScript. |
| Single-page reading experience | Once you enter the reader, chapter changes swap content in place via htmx — the sidebar never reloads, scroll and focus behave. Degrades to plain multi-page when JS is unavailable. |
| Back to the landing page | The toolbar's home control returns to the book's front page with the same in-place swap as a chapter, so the document is never reloaded. |
| Page through the book | The toolbar's previous/next buttons walk the spine's linear reading order — the same list publication.json publishes — so covers and the navigation document are not pages you turn into. A chapter the book's own table of contents omits is still visited. |
| One honest canonical | With an absolute --base-url the landing page carries a canonical link and a chapter carries none: the reader withdraws it on entry and restores it on the way back. |
| Sidebar from the book's own navigation | Uses the EPUB 3 nav document, falling back to the NCX. Honours page-progression-direction for RTL books. |
| Per-chapter styles, restored | Each chapter's own stylesheet links, @imports, inline <style>, body class, lang and dir are reapplied as you navigate — the book looks the way its publisher intended, chapter by chapter. Unless you ask for the reader's own style instead. |
| Shareable deep links | A link to /EPUB/text/@ch01.xhtml enters the reader at the right chapter, then rewrites the address bar to the honest path. Copy the link button gives a URL that always works. |
| Full-text search | --search builds a Pagefind index over the spine. Results are highlighted and clicking one stays inside the reader. |
| Structured data | Schema.org Book / Chapter JSON-LD, plus a publication.json Web Publication Manifest. Each chapter's url lists both addresses it is reachable at. A @id is the book's own dc:identifier, so it survives a redeploy. |
| Theming | auto / light / dark, implemented with light-dark() and color-scheme so it follows the OS and can be overridden. |
| A reader's own style, on request | --content-style reader stops shipping the book's stylesheets and typesets the content with the reader's own default — for books whose typography fights dark mode. The book's files are still untouched. |
| A namespace for the reader's chrome | Every class and id the reader emits is prefixed epubsite-. A book whose stylesheet calls its own table of contents #toc gets its own table of contents styled — never the reader's sidebar. |
| Fixed-layout books handled honestly | Pre-paginated EPUBs cannot be reflowed by a shell, so the build degrades to the plain multi-page site and says so on the landing page instead of pretending. |
| Reference auditing | The build reports external resources and links that escape the site root, so you know what will break offline. |
| Strict by design | Unknown flags are errors. Every failure has a stable exit code and a machine-readable --json form. |
| No lock-in | The output is plain files. Delete epubsite.html and the book is still there, intact. |
How it works
The reader
epubsite.html is the shell. Its head is fully server-rendered — title,
description, the landing page's canonical (when --base-url names an origin),
Book JSON-LD — so a crawler or a reader with JavaScript disabled gets a
complete, useful document with a table of contents and a landing page describing
the book. That page ends with a line crediting the project and
linking to this repository; it is part
of the landing markup, so it is gone as soon as a chapter opens and comes back
with the home control. Deep links enter on a chapter and never show it.
When the runtime loads, it:
- reads the site root from
document.documentElement.dataset, - absolutizes the shell's own links (a relative asset URL would resolve under a chapter's directory after a navigation),
- loads htmx and the shell data,
- enters a chapter if the URL asked for one,
- then, on every navigation, reapplies the chapter's styles,
lang,dir,bodyclass and JSON-LD — including the chapter'surlarray, which it computes from the address you actually arrived at — marks the current sidebar entry, and withdraws the landing page's canonical link. Coming back it does the reverse: the book's styles and the chapter's JSON-LD go, and the canonical returns.
hx-boost handles link interception, with two deliberate exceptions: a link
within the chapter you are already reading performs the fragment jump
natively rather than re-requesting the chapter, and external links are left
alone.
The toolbar's home control returns to the landing page the same way a chapter
opens: the shell's response is cut down to the content pane and swapped in, so the
document is never reloaded and the sidebar keeps its scroll position and
expansion. It is a plain link, which is why middle-click and "open in a new tab"
behave as expected, and why it still works when htmx never loads. The contents
control beside it is drawn as a symbol rather than written as the word
"Contents" — the word moved into aria-label, which is where a screen reader
finds it and the only place it can now be.
Next to the title are previous and next, which walk the spine's linear
reading order rather than the sidebar: the same sequence publication.json
publishes, so a linear="no" cover or navigation document is skipped while a
chapter the book's own table of contents never mentions is still visited. On the
landing page "next" starts the book, and at either end the control is dimmed but
still in place instead of disappearing. They are the only links in the shell whose
href changes as you read, so they carry hx-boost="false" and the runtime
issues the swap itself — a boosted link would keep requesting whichever chapter it
was first processed for, and a click that does nothing at all is what that looks
like.
Everything the reader owns is namespaced: its classes and ids are prefixed
epubsite-. Chapter markup is swapped into the same document as that chrome,
and the book's stylesheets are active while it is, so a generic name would be a
rule waiting to collide in both directions — a book whose stylesheet says
#toc { display: none } would hide the reader's sidebar, and a book's own
.notice would pick up the reader's notice box.
The reader's own style
The book's typography is the publisher's, by default: each chapter's stylesheets
are collected at build time and reapplied as you navigate. That is the right
default, and it has one visible cost — a book that hard-codes black text on white
paper stays a white page inside a dark reader, because --theme governs the
reader's own chrome and nothing else.
--content-style reader closes that gap the only way this project can, without
editing the book: the build stops shipping the book's stylesheets to the reader at
all, and the reader applies its own stylesheet instead — a typographic default
(platform serif for text, a monospace stack for code, tables and quotes drawn with
the same tokens as the toolbar) whose few colours come from the theme palette, so
light and dark both work. The book's files are untouched, which is why a chapter
opened directly, without the reader, still looks exactly as its publisher made it.
The reader's sheet replaces the book's rather than layering under it, because
that is what "use your own" has to mean. Two limits are worth knowing before you
reach for it: styles written into the book's markup (style="…", align,
bgcolor) are markup and are left alone, and the flag fails the build with exit 2
when there is no reader to apply it to — under --no-spa, or for a fixed-layout
book, whose chapters are the book's own pages.
The token protocol: shareable deep links
A reader who lands on /EPUB/text/ch01.xhtml directly gets a bare page — correct,
but without the sidebar. To offer a way into the reader from an arbitrary
chapter, epubsite reserves a parallel addressing scheme: prefix a basename with
@.
sequenceDiagram
autonumber
participant R as Reader
participant H as Static host
participant G as 404.html (guide)
participant S as epubsite.html (shell)
R->>H: GET /EPUB/text/@ch01.xhtml
H-->>R: 404 — path does not exist
Note over R,H: the 404 body is the guide, URL unchanged
R->>G: guide recognises the @ token
G->>S: redirect to epubsite.html?p=%2FEPUB%2Ftext%2Fch01.xhtml
S->>R: history.replaceState → /EPUB/text/ch01.xhtml
S->>H: fetch the chapter
H-->>S: the chapter, verbatim
Note over S: sidebar, styles and scroll restoredThe URL the reader ends on is the honest one. Copy it, reload it, send it to someone — it works, with or without the shell.
Without the guide — on a host that does not serve 404.html for unknown paths —
the @ form simply 404s; the book's real chapter URLs still work exactly as
before. The token protocol is an enhancement, never a dependency.
Because both addresses reach the same chapter, the reader publishes both. When
you are on a chapter, its JSON-LD node carries a url array holding the honest
path and its @ form, so a search engine sees that the chapter is reachable
either way rather than indexing the bare page alone. The arrays are rebuilt on
every navigation, and the landing page has no chapter node at all.
The @ address is never a canonical URL and never appears in book.hasPart.
Canonical answers "where does this chapter live" — a question the @ form would
answer with a 404. A url entry answers "where else can it be reached", which is
true of the @ form by construction. The distinction is why one is emitted and
the other is not.
A chapter gets no canonical at all, not even its honest path. The reader is a shell whose own address is the landing page, so the only canonical it could write for a chapter is one made on the chapter's behalf — and the chapter, served as its own document, is perfectly capable of speaking for itself. It leaves the question alone instead.
Hosting
| Mode | What you get |
|---|---|
| none | Just the files. You handle unknown paths yourself. |
| 404 (default) | A 404.html guide, which is what enables the token protocol on GitHub Pages, Netlify, Cloudflare Pages and similar. |
| rewrite | Host-level rewrite rules. Not implemented — this is the one documented gap, and it fails with exit 2 rather than emitting rules that look right and are not. |
| all | Both. Also fails, for the same reason. |
Diagnostics
The build reports what it found without stopping, because a book with an external image is still a book. Warnings and notes go to stderr, above the result:
$ epubsite moby-dick.epub
note[external-resource] the book references http://www.gutenberg.org
Built 144 chapters, 10 resources (3.2 MB) into ./distW_PRE_PAGINATED— the book is fixed-layout, so the shell cannot reflow it. The site degrades to multi-page and the landing page explains why.W_SEARCH_*— search could not be indexed, and why.- External resources and out-of-tree links — reported per chapter, so you can see what will fail offline or behind a firewall.
Exit codes
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | An unexpected internal error. If you see this, it is a bug. |
| 2 | Usage error, or a documented gap (--hosting rewrite). |
| 3 | The input is not a valid EPUB. |
| 4 | A file in the book collides with the reserved namespace, or the output directory is non-empty. |
| 5 | The book contains encrypted content. |
Under --verbose, errors print a stack trace. Without it, you get the message and
the location in the book that caused it.
Using it as a library
The CLI is a thin wrapper over a small API:
import { build } from 'epubsite'
const result = await build('moby-dick.epub', {
out: 'public',
baseUrl: { form: 'absolute', href: 'https://example.com/moby/' },
search: true,
})
console.log(result.stats) // { chapters, resources, bytes }
console.log(result.diagnostics)build throws an EpubSiteError carrying a stable code and the exitCode the
CLI would use. No function in the library calls process.exit.
Limitations
These are decisions, not oversights:
- No path rewriting. The book keeps its own paths, so a book whose files sit in a subdirectory keeps that subdirectory in the URL. This is the price of the zero-rewrite guarantee, and it is why the tool exists.
- No pagination. The reader scrolls. Paginated reflow requires measuring the viewport and rewriting the document's layout, which is exactly the class of transformation this tool refuses to perform.
- No
--book-dir. Removed permanently;--base-urlcovers the use case. - Fixed-layout books get the multi-page site. A shell cannot reflow a pre-paginated book, and pretending otherwise produces a worse result than being honest.
- Scripts in the book do not execute. Chapter content is inserted with script tags disallowed, so a hosted book cannot run arbitrary code in the reader's session.
--content-style readerneeds the reader. With--no-spa, or for a fixed-layout book, a chapter is the book's own file and there is nothing to apply the reader's stylesheet with, so the build fails with exit 2 and names the reason rather than quietly ignoring the flag. Styles written into the book's markup (style="…",align,bgcolor) are markup and are left alone: the promise is "the book's stylesheets are not applied", not "the book is edited".- A book's
@idis its owndc:identifier, copied as written. Identity is not location: the value does not change when you move the site to another domain. The consequence is that a book identifying itself with something that is not an IRI — free text, a dotted string — keeps that text in the graph rather than have a tidier identity invented for it. A book that declares no identifier at all is identified by its title, slugged:Moby-Dick; or, The Whale→moby-dick-or-the-whale. --hosting rewriteis not implemented and fails loudly.
License
MIT — see LICENSE.
One asset is not MIT: src/runtime/icon.svg is a
Font Awesome Free icon, which is CC BY 4.0.
Attribution is carried inside the SVG as a leading comment, so it travels with
the image into every generated site, and is restated in
src/runtime/icon.LICENSE. The vendored htmx module carries its own licence as
vendor/htmx.LICENSE.
Development
npm install
npm run verify # build + typecheck + lint + unit + integration + browser tests
npm run test # unit and integration, fast
npm run test:e2e # Playwright, against real Chrome
npm run epubsite -- <book.epub> --helpThe browser tests drive the system Chrome (PLAYWRIGHT_CHANNEL overrides the
channel). Real-world fixtures come from the
IDPF EPUB 3 samples; drop
them into test/fixtures/real/ and they are picked up.
The spec lives in spec-v1.3.md. It is the current text; v1.1 and v1.2 are frozen,
and v1.3 preserves their section numbering because the source and tests cite it.
Source is organised by dependency boundary, and that boundary is enforced by lint:
| Path | May use |
|---|---|
| src/shared/ | nothing — no imports, no node: |
| src/build/ | Node.js. Never the DOM. |
| src/runtime/ | The DOM. Never Node.js. |
