Implement streaming EPUB reader with on-demand loading (#2350)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-19 18:07:57 -07:00
committed by GitHub
co-authored by acx10
parent da83a70281
commit 7efb0e138d
36 changed files with 2237 additions and 106 deletions
+109 -7
View File
@@ -706,15 +706,35 @@ class Loader {
#cache = new Map()
#children = new Map()
#refCount = new Map()
#getDirectUrl = null // Function to get direct streaming URLs for lazy loading
eventTarget = new EventTarget()
constructor({ loadText, loadBlob, resources }) {
constructor({ loadText, loadBlob, resources, getDirectUrl }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.manifest = resources.manifest
this.assets = resources.manifest
this.#getDirectUrl = getDirectUrl ?? null
// needed only when replacing in (X)HTML w/o parsing (see below)
//.filter(({ mediaType }) => ![MIME.XHTML, MIME.HTML].includes(mediaType))
}
// Check if a media type is an image
#isImage(mediaType) {
return mediaType?.startsWith('image/') ?? false
}
// Check if a media type is a font
#isFont(mediaType) {
return mediaType?.includes('font') ||
mediaType === 'application/vnd.ms-opentype' ||
mediaType === 'application/x-font-ttf' ||
mediaType === 'application/x-font-otf' ||
mediaType === 'application/x-font-woff' ||
mediaType === 'font/otf' ||
mediaType === 'font/ttf' ||
mediaType === 'font/woff' ||
mediaType === 'font/woff2'
}
async createURL(href, data, type, parent) {
if (!data) return ''
const detail = { data, type }
@@ -838,13 +858,59 @@ class Loader {
// replace hrefs (excluding anchors)
const replace = async (el, attr) => el.setAttribute(attr,
await this.loadHref(el.getAttribute(attr), href, parents))
// Helper to check if element is an image that should use direct URL
const shouldUseDirectUrl = (el, attr) => {
if (!this.#getDirectUrl) return false
const srcAttr = el.getAttribute(attr)
if (!srcAttr || isExternal(srcAttr)) return false
const path = resolveURL(srcAttr, href)
const item = this.manifest.find(item => item.href === path)
return item && this.#isImage(item.mediaType)
}
// Replace with direct URL (for images) - browser loads on-demand
const replaceWithDirectUrl = (el, attr) => {
const srcAttr = el.getAttribute(attr)
const path = resolveURL(srcAttr, href)
const directUrl = this.#getDirectUrl(path)
if (directUrl) {
el.setAttribute(attr, directUrl)
el.setAttribute('loading', 'lazy') // Native lazy loading hint
return true
}
return false
}
// Process link elements (stylesheets, etc.)
for (const el of doc.querySelectorAll('link[href]')) await replace(el, 'href')
for (const el of doc.querySelectorAll('[src]')) await replace(el, 'src')
for (const el of doc.querySelectorAll('[poster]')) await replace(el, 'poster')
// Process elements with src attribute
// For images: use direct URLs so browser can load on-demand
// For others: load and create blob URL
for (const el of doc.querySelectorAll('[src]')) {
if (shouldUseDirectUrl(el, 'src')) {
replaceWithDirectUrl(el, 'src')
} else {
await replace(el, 'src')
}
}
// Process poster attributes (videos)
for (const el of doc.querySelectorAll('[poster]')) {
if (shouldUseDirectUrl(el, 'poster')) {
replaceWithDirectUrl(el, 'poster')
} else {
await replace(el, 'poster')
}
}
for (const el of doc.querySelectorAll('object[data]')) await replace(el, 'data')
for (const el of doc.querySelectorAll('[*|href]:not([href])'))
el.setAttributeNS(NS.XLINK, 'href', await this.loadHref(
el.getAttributeNS(NS.XLINK, 'href'), href, parents))
// Process srcset attributes
for (const el of doc.querySelectorAll('[srcset]'))
el.setAttribute('srcset', await replaceSeries(el.getAttribute('srcset'),
/(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g,
@@ -868,15 +934,48 @@ class Loader {
return this.createURL(href, result, mediaType, parent)
}
async replaceCSS(str, href, parents = []) {
// For url() references, use direct URLs for fonts and images (lazy loading)
// This avoids fetching all fonts/images upfront - browser fetches on-demand
const replacedUrls = await replaceSeries(str,
/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `url("${url}")`))
async (_, url) => {
if (isExternal(url)) return `url("${url}")`
const path = resolveURL(url, href)
const item = this.manifest.find(item => item.href === path)
// If we have getDirectUrl and this is a font or image, use direct URL
// This lets the browser fetch on-demand instead of us prefetching everything
if (this.#getDirectUrl && item && (this.#isFont(item.mediaType) || this.#isImage(item.mediaType))) {
const directUrl = this.#getDirectUrl(path)
if (directUrl) return `url("${directUrl}")`
}
// For other resources (like CSS), load them normally
const loadedUrl = await this.loadHref(url, href, parents)
return `url("${loadedUrl}")`
})
// apart from `url()`, strings can be used for `@import` (but why?!)
return replaceSeries(replacedUrls,
// CSS imports need to be loaded and processed
const replacedImports = await replaceSeries(replacedUrls,
/@import\s*["']([^"'\n]*?)["']/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `@import "${url}"`))
// Add font-display: swap to @font-face rules that don't have it
// This ensures text is visible immediately while fonts load
return replacedImports.replace(
/@font-face\s*\{([^}]*)\}/gi,
(match, content) => {
// Check if font-display is already set
if (/font-display\s*:/i.test(content)) {
return match
}
// Add font-display: swap before the closing brace
return `@font-face {${content}font-display: swap;}`
}
)
}
// find & replace all possible relative paths for all assets without parsing
replaceString(str, href, parents = []) {
@@ -932,10 +1031,12 @@ export class EPUB {
parser = new DOMParser()
#loader
#encryption
constructor({ loadText, loadBlob, getSize, sha1 }) {
#getDirectUrl = null
constructor({ loadText, loadBlob, getSize, getDirectUrl, sha1 }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.getSize = getSize
this.#getDirectUrl = getDirectUrl ?? null
this.#encryption = new Encryption(deobfuscators(sha1))
}
async #loadXML(uri) {
@@ -973,6 +1074,7 @@ ${doc.querySelector('parsererror').innerText}`)
loadBlob: uri => Promise.resolve(this.loadBlob(uri))
.then(this.#encryption.getDecoder(uri)),
resources: this.resources,
getDirectUrl: this.#getDirectUrl,
})
this.transformTarget = this.#loader.eventTarget
this.sections = this.resources.spine.map((spineItem, index) => {
@@ -0,0 +1,121 @@
/**
* Creates a streaming loader that fetches EPUB files from the server on-demand
* instead of loading the entire ZIP file into memory.
*
* @param {number} bookId - The book ID for API requests
* @param {string} baseUrl - API base URL (e.g., '/api/v1/epub')
* @param {Object} bookInfo - Pre-fetched EPUB metadata from /info endpoint
* @param {string} [authToken] - Optional authentication token
* @returns {Object} Loader interface compatible with Foliate's EPUB class
*/
export const makeStreamingLoader = (bookId, baseUrl, bookInfo, authToken = null) => {
// Build a map of file paths to their manifest info for quick lookup
const manifestMap = new Map(
bookInfo.manifest.map(item => [item.href, item])
)
// Build URL for fetching a file
const getFileUrl = (name) => {
if (!name) return null
// URL encode the path but preserve slashes
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
return `${baseUrl}/${bookId}/file/${encodedPath}`
}
// Build fetch options with auth header
const getFetchOptions = () => {
if (!authToken) return {}
return {
headers: {
'Authorization': `Bearer ${authToken}`
}
}
}
// Build URL with token for browser-initiated requests (fonts, images in CSS)
const getDirectFileUrl = (name) => {
if (!name) return null
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
let url = `${baseUrl}/${bookId}/file/${encodedPath}`
if (authToken) {
url += `?token=${encodeURIComponent(authToken)}`
}
return url
}
/**
* Load file as text
*/
const loadText = async (name) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load text: ${name}`, response.status)
return null
}
return await response.text()
} catch (e) {
console.error(`Error loading text ${name}:`, e)
return null
}
}
/**
* Load file as Blob with optional MIME type
*/
const loadBlob = async (name, type) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load blob: ${name}`, response.status)
return null
}
const blob = await response.blob()
// Return with specified type or detected type
if (type) {
return new Blob([blob], {type})
}
return blob
} catch (e) {
console.error(`Error loading blob ${name}:`, e)
return null
}
}
/**
* Get uncompressed size of a file
*/
const getSize = (name) => {
if (!name) return 0
const item = manifestMap.get(name)
return item?.size ?? 0
}
/**
* Get direct URL for a file without fetching it.
* This allows the browser to fetch resources on-demand (fonts, images).
* Note: Uses token in URL since browser-initiated requests can't use headers.
* @param {string} name - File path within the EPUB
* @returns {string|null} Direct URL to the file
*/
const getDirectUrl = (name) => {
if (!name) return null
return getDirectFileUrl(name)
}
return {
loadText,
loadBlob,
getSize,
getDirectUrl, // For lazy loading of fonts/images in CSS
// Expose for debugging
_bookInfo: bookInfo,
_manifestMap: manifestMap
}
}
export default makeStreamingLoader
+20
View File
@@ -2,6 +2,7 @@ import * as CFI from './epubcfi.js'
import {SectionProgress, TOCProgress} from './progress.js'
import {Overlayer} from './overlayer.js'
import {textWalker} from './text-walker.js'
import {makeStreamingLoader} from './streaming-loader.js'
const SEARCH_PREFIX = 'foliate-search:'
@@ -139,6 +140,22 @@ export const makeBook = async file => {
return book
}
/**
* Create an EPUB book using streaming loader instead of ZIP extraction.
* This avoids loading the entire EPUB into memory.
*
* @param {number} bookId - Book ID for API requests
* @param {string} baseUrl - API base URL for EPUB endpoints
* @param {Object} bookInfo - Pre-fetched metadata from /api/v1/epub/{bookId}/info
* @param {string} [authToken] - Optional authentication token
* @returns {Promise<EPUB>} Initialized EPUB book object
*/
export const makeStreamingBook = async (bookId, baseUrl, bookInfo, authToken = null) => {
const loader = makeStreamingLoader(bookId, baseUrl, bookInfo, authToken)
const {EPUB} = await import('./epub.js')
return new EPUB(loader).init()
}
class CursorAutohider {
#timeout
#el
@@ -653,3 +670,6 @@ export class View extends HTMLElement {
}
customElements.define('foliate-view', View)
// Export makeStreamingBook to window for use from Angular
window.makeStreamingBook = makeStreamingBook