Open History to see the last commit
1import { sha1 } from "@noble/hashes/legacy";
2import { parseUrl } from "@t3tools/shared/url";
3import type JSZip from "jszip";
4import {
5 archivePath,
6 escape,
7 find,
8 previewImageSize,
9 parseXml,
10 text,
11 type XmlNode,
12} from "./documentPreviewXml";
13import { officeXmlDecoder } from "./officeArchive";
14import { externalUrl } from "./office/links";
15import { mediaFragment, mediaTime, ttmlCaptions } from "./epubMedia";
16import type { EpubLocation, EpubNarrationCue, EpubPage } from "./officePreviewProtocol";
17import { isPreviewError, PreviewError } from "./previewFailure";
18
19const htmlTags = new Set(
20 "a abbr acronym address article aside audio b bdi bdo big blockquote canvas caption center cite code col colgroup dd del details dfn div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hgroup i ins kbd li main mark nav ol p pre q rp rt ruby s samp section small span strike strong sub summary sup table tbody td tfoot th thead time tr tt u ul var video".split(
21 " ",
22 ),
23);
24const voidTags = new Set(["br", "hr", "wbr", "img", "col", "input", "source", "track"]);
25const formTags = new Set(
26 "button datalist fieldset form input label legend meter optgroup option output progress select textarea".split(
27 " ",
28 ),
29);
30const staticControls = new Set(["button", "input", "select", "textarea"]);
31const svgTags = new Set(
32 (
33 "svg g a defs desc title path rect circle ellipse line polyline polygon text tspan image use symbol switch textPath clipPath mask pattern marker linearGradient radialGradient stop " +
34 "filter feGaussianBlur feColorMatrix feSpecularLighting feDiffuseLighting feDistantLight fePointLight feSpotLight feComposite feOffset feComponentTransfer feFuncA feFuncR feFuncG feFuncB feFlood feBlend feMerge feMergeNode feDropShadow " +
35 "feMorphology feTurbulence feDisplacementMap feConvolveMatrix feTile"
36 ).split(" "),
37);
38const mathTags = new Set(
39 (
40 "math mrow mi mn mo mtext ms mspace mfrac msqrt mroot mstyle merror mpadded mphantom mfenced menclose " +
41 "msub msup msubsup munder mover munderover mmultiscripts mprescripts none mtable mtr mtd semantics " +
42 "mlongdiv mstack msgroup msrow msline mscarries mscarry"
43 ).split(" "),
44);
45const omitted = new Set([
46 "head",
47 "script",
48 "style",
49 "iframe",
50 "embed",
51 "foreignObject",
52 "annotation",
53 "annotation-xml",
54 "template",
55 "noscript",
56]);
57const commonAttrs = [
58 "id",
59 "class",
60 "lang",
61 "dir",
62 "title",
63 "role",
64 "aria-label",
65 "aria-labelledby",
66 "aria-describedby",
67 "aria-hidden",
68 "epub:type",
69 "hidden",
70];
71const htmlAttrs = [
72 "align",
73 "alt",
74 "border",
75 "cellpadding",
76 "cellspacing",
77 "valign",
78 "name",
79 "colspan",
80 "rowspan",
81 "scope",
82 "type",
83 "headers",
84 "start",
85 "value",
86 "open",
87 "width",
88 "height",
89];
90const formAttrs = [
91 ...htmlAttrs,
92 "checked",
93 "cols",
94 "disabled",
95 "for",
96 "high",
97 "label",
98 "list",
99 "low",
100 "max",
101 "min",
102 "multiple",
103 "optimum",
104 "placeholder",
105 "rows",
106 "selected",
107 "size",
108 "step",
109];
110const svgAttrs = (
111 "x y x1 x2 y1 y2 cx cy r rx ry dx dy width height viewBox preserveAspectRatio transform d points " +
112 "fill fill-rule fill-opacity stroke stroke-width stroke-opacity stroke-dasharray stroke-dashoffset " +
113 "stroke-linecap stroke-linejoin stroke-miterlimit opacity display visibility color font-size " +
114 "font-family font-weight font-style text-anchor textLength lengthAdjust dominant-baseline letter-spacing word-spacing text-decoration rotate " +
115 "gradientUnits gradientTransform spreadMethod fx fy fr offset stop-color stop-opacity clip-path " +
116 "clip-rule clipPathUnits mask maskUnits maskContentUnits patternUnits patternContentUnits patternTransform startOffset " +
117 "marker-start marker-mid marker-end markerWidth markerHeight markerUnits refX refY orient " +
118 "filter filterUnits primitiveUnits stdDeviation in in2 result type values color-interpolation-filters flood-color flood-opacity mode " +
119 "kernelUnitLength surfaceScale specularExponent specularConstant lighting-color azimuth elevation operator slope intercept tableValues amplitude exponent " +
120 "diffuseConstant z pointsAtX pointsAtY pointsAtZ limitingConeAngle k1 k2 k3 k4 " +
121 "radius baseFrequency numOctaves seed stitchTiles scale xChannelSelector yChannelSelector order kernelMatrix divisor bias targetX targetY edgeMode preserveAlpha"
122).split(" ");
123const mathAttrs = (
124 "display displaystyle mathvariant mathsize mathcolor mathbackground accent accentunder columnalign " +
125 "columnlines columnspacing rowalign rowlines rowspacing rowspan columnspan depth height width " +
126 "linethickness lspace rspace stretchy fence separator symmetric minsize maxsize movablelimits " +
127 "notation scriptlevel largeop form open close separators frame longdivstyle position shift length crossout"
128).split(" ");
129
130const images: Record<string, string> = {
131 png: "image/png",
132 jpg: "image/jpeg",
133 jpeg: "image/jpeg",
134 gif: "image/gif",
135 webp: "image/webp",
136};
137const rasterMimeByFirstByte: Partial<Record<number, string>> = {
138 0x89: images.png,
139 0xff: images.jpg,
140 0x47: images.gif,
141 0x52: images.webp,
142};
143const imageTypes = new Set([...Object.values(images), "image/svg+xml"]);
144const fonts: Record<string, string> = {
145 otf: "font/otf",
146 ttf: "font/ttf",
147 woff: "font/woff",
148 woff2: "font/woff2",
149};
150const fontMimeBySignature = new Map([
151 ["OTTO", fonts.otf],
152 ["\0\x01\0\0", fonts.ttf],
153 ["wOFF", fonts.woff],
154 ["wOF2", fonts.woff2],
155]);
156const legacyFonts: Record<string, string> = {
157 "application/vnd.ms-opentype": "font/otf",
158 "application/font-sfnt": "font/ttf",
159 "application/font-woff": "font/woff",
160};
161const audiovisual: Record<string, string> = {
162 mp3: "audio/mpeg",
163 m4a: "audio/mp4",
164 ogg: "audio/ogg",
165 opus: "audio/ogg",
166 mp4: "video/mp4",
167 webm: "video/webm",
168 ogv: "video/ogg",
169 wav: "audio/wav",
170};
171const xhtmlTypes = new Set(["application/xhtml+xml", "text/html"]);
172const tagName = (node: XmlNode) => node.name.replace(/^\{[^}]*\}|^(?:svg|math):/, "");
173const attr = (name: string, value: string | undefined) =>
174 value === undefined ? "" : ` ${name}="${escape(value)}"`;
175const urlFragment = (href: string) => /#.*/s.exec(href.trim())?.[0] ?? "";
176const extension = (path: string) => path.split(".").at(-1)?.toLowerCase() ?? "";
177const shortTitle = (value: string) =>
178 value
179 .replace(/\s+/g, " ")
180 .trim()
181 .slice(0, 120)
182 .replace(/[\uD800-\uDBFF]$/, "") || undefined;
183
184async function readXmlText(archive: JSZip, path: string) {
185 const bytes = await archive.file(path)?.async("uint8array");
186 if (!bytes || bytes.length > 8 * 1024 * 1024) throw new PreviewError({ code: "xml-invalid" });
187 try {
188 return officeXmlDecoder(bytes).decode(bytes);
189 } catch (cause) {
190 if (cause instanceof RangeError) throw new PreviewError({ code: "xml-invalid" });
191 throw cause;
192 }
193}
194
195async function readChapter(archive: JSZip, path: string, mime: string): Promise<XmlNode> {
196 const source = await readXmlText(archive, path);
197 if (mime !== "text/html") {
198 try {
199 return parseXml(source);
200 } catch (cause) {
201 if (
202 mime !== "application/xhtml+xml" ||
203 !isPreviewError(cause) ||
204 cause.code !== "xml-invalid"
205 )
206 throw cause;
207 }
208 }
209 // Some legacy books ship tag soup in XHTML spine items. Recover with the browser's
210 // parsing rules, then pass the tree through the same allowlist as a well-formed chapter.
211 if (source.length > 2 * 1024 * 1024) throw new PreviewError({ code: "xml-invalid" });
212 const { parse, defaultTreeAdapter: tree } = await import("parse5");
213 let count = 0;
214 function convert(node: import("parse5").DefaultTreeAdapterMap["node"], depth: number): XmlNode[] {
215 if (depth > 100) throw new PreviewError({ code: "xml-too-deep" });
216 if (++count > 100_000) throw new PreviewError({ code: "xml-too-much-content" });
217 if (tree.isTextNode(node))
218 return [{ name: "#text", attrs: {}, children: [], text: node.value }];
219 if (!tree.isElementNode(node)) return [];
220 return [
221 {
222 // parse5 8.0.1 omits feDropShadow from its SVG tag-name adjustment table.
223 name: node.tagName === "fedropshadow" ? "feDropShadow" : node.tagName,
224 attrs: Object.fromEntries(
225 node.attrs.map(({ name, prefix, value }) => [prefix ? `${prefix}:${name}` : name, value]),
226 ),
227 children: node.childNodes.flatMap((child) => convert(child, depth + 1)),
228 text: "",
229 },
230 ];
231 }
232 return {
233 name: "root",
234 attrs: {},
235 children: parse(source, { scriptingEnabled: false }).childNodes.flatMap((node) =>
236 convert(node, 0),
237 ),
238 text: "",
239 };
240}
241
242function cssUnescape(value: string) {
243 return value.replace(
244 /\\(?:([\da-f]{1,6})(?:\r\n|[ \t\r\n\f])?|\r\n|[\r\n\f]|([\s\S]))/gi,
245 (_, hex: string | undefined, char: string | undefined) => {
246 if (!hex) return char ?? "";
247 const code = Number.parseInt(hex, 16);
248 const valid = code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff);
249 return String.fromCodePoint(valid ? code : 0xfffd);
250 },
251 );
252}
253
254function localPath(archive: JSZip, base: string, href: string) {
255 const path = archivePath(base, href.trim());
256 if (path && archive.file(path)) return path;
257 const literal = archivePath(base, href.trim().replaceAll("%", "%25"));
258 return literal && archive.file(literal) ? literal : null;
259}
260
261function dimensions(width: number, height: number) {
262 return width >= 1 && height >= 1 && width <= 16_384 && height <= 16_384
263 ? { width, height }
264 : undefined;
265}
266
267function viewport(root: XmlNode) {
268 const content = find(root, "meta").find((node) => node.attrs.name === "viewport")?.attrs.content;
269 if (!content) return;
270 return dimensions(
271 Number(/\bwidth\s*=\s*([\d.]+)/i.exec(content)?.[1]),
272 Number(/\bheight\s*=\s*([\d.]+)/i.exec(content)?.[1]),
273 );
274}
275
276function svgViewport(node: XmlNode) {
277 const [, , width, height] = (node.attrs.viewBox ?? "")
278 .trim()
279 .split(/[\s,]+/)
280 .map(Number);
281 return (
282 dimensions(
283 Number(node.attrs.width?.replace(/px$/i, "")),
284 Number(node.attrs.height?.replace(/px$/i, "")),
285 ) ?? dimensions(width ?? 0, height ?? 0)
286 );
287}
288
289function toBase64(bytes: Uint8Array) {
290 let binary = "";
291 for (let offset = 0; offset < bytes.length; offset += 8192)
292 binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
293 return btoa(binary);
294}
295
296const idpfObfuscation = "http://www.idpf.org/2008/embedding";
297const adobeObfuscation = "http://ns.adobe.com/pdf/enc#RC";
298
299export async function openEpub(archive: JSZip) {
300 if (archive.file("META-INF/license.lcpl")) throw new PreviewError({ code: "epub-drm" });
301 const algorithms = new Map<string, string>();
302 const encryption = await optionalXml("META-INF/encryption.xml");
303 if (encryption) {
304 const ns = "{http://www.w3.org/2001/04/xmlenc#}";
305 for (const node of find(encryption, ns + "EncryptedData")) {
306 const algorithm = find(node, ns + "EncryptionMethod")[0]?.attrs.Algorithm;
307 if (!algorithm) continue;
308 if (algorithm !== idpfObfuscation && algorithm !== adobeObfuscation)
309 throw new PreviewError({ code: "epub-drm" });
310 const uri = find(node, ns + "CipherReference")[0]?.attrs.URI;
311 const path = uri && localPath(archive, "", uri);
312 if (path) algorithms.set(path, algorithm);
313 }
314 }
315 if (!archive.file("META-INF/container.xml")) throw new PreviewError({ code: "epub-no-package" });
316 const container = parseXml(await readXmlText(archive, "META-INF/container.xml"));
317 const fullPath = find(container, "rootfile")[0]?.attrs["full-path"] ?? "";
318 const rootfile = localPath(archive, "", fullPath);
319 if (!rootfile) throw new PreviewError({ code: "epub-no-package" });
320 const packageRoot = parseXml(await readXmlText(archive, rootfile));
321 const pkg = find(packageRoot, "package")[0];
322 const spine = find(packageRoot, "spine")[0];
323 const refs = spine ? find(spine, "itemref") : [];
324 if (!refs.length || refs.length > 4096) throw new PreviewError({ code: "epub-chapter-count" });
325
326 const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item.attrs]));
327 const media = new Map<string, string>();
328 const spineSources = new Map<
329 string,
330 { path: string; mime: string; narrationPath: string | null } | null
331 >();
332 for (const [id, item] of manifest) {
333 const path = localPath(archive, rootfile, item.href ?? "");
334 const mime = item["media-type"];
335 if (path && mime) {
336 media.set(path, mime);
337 if (
338 id &&
339 (xhtmlTypes.has(mime) || mime === "image/svg+xml" || Object.values(images).includes(mime))
340 ) {
341 const overlay = item["media-overlay"] ? manifest.get(item["media-overlay"]) : undefined;
342 const narrationPath =
343 overlay?.["media-type"] === "application/smil+xml"
344 ? localPath(archive, rootfile, overlay.href ?? "")
345 : null;
346 spineSources.set(id, { path, mime, narrationPath });
347 }
348 }
349 }
350 function resolveSpineSource(id: string | undefined) {
351 const visited = new Set<string>();
352 let source = null;
353 while (id && !visited.has(id)) {
354 const cached = spineSources.get(id);
355 if (cached !== undefined) {
356 source = cached;
357 break;
358 }
359 visited.add(id);
360 id = manifest.get(id)?.fallback;
361 }
362 for (const id of visited) spineSources.set(id, source);
363 return source;
364 }
365 const layout = find(packageRoot, "meta").find(
366 (node) => node.attrs.property === "rendition:layout",
367 );
368 const fixed = layout ? text(layout).trim() === "pre-paginated" : false;
369 const chapters = refs.flatMap(({ attrs }) => {
370 const source = resolveSpineSource(attrs.idref);
371 if (!source) return [];
372 const properties = attrs.properties?.split(/\s+/) ?? [];
373 return [
374 {
375 ...source,
376 linear: attrs.linear !== "no",
377 fixed:
378 !properties.includes("rendition:layout-reflowable") &&
379 (fixed || properties.includes("rendition:layout-pre-paginated")),
380 },
381 ];
382 });
383 if (!chapters.length) throw new PreviewError({ code: "epub-no-chapters" });
384
385 const guide = find(packageRoot, "guide")[0];
386 const coverReference =
387 guide && find(guide, "reference").find((node) => node.attrs.type === "cover");
388 const coverPath = coverReference && localPath(archive, rootfile, coverReference.attrs.href ?? "");
389
390 const chapterIndex = new Map<string, number>();
391 for (const [index, chapter] of chapters.entries())
392 if (!chapterIndex.has(chapter.path)) chapterIndex.set(chapter.path, index);
393 function resolve(base: string, href: string): EpubLocation | undefined {
394 const [path, fragment] = href.trim().split(/#(.*)/s);
395 const target = path && !path.startsWith("?") ? localPath(archive, base, path) : base;
396 const index = target ? chapterIndex.get(target) : undefined;
397 if (index === undefined) return;
398 let anchor = fragment;
399 if (anchor) {
400 try {
401 anchor = decodeURIComponent(anchor);
402 } catch {
403 // Some books use unescaped percent signs in IDs.
404 }
405 }
406 return { index, ...(anchor ? { anchor } : {}) };
407 }
408
409 const chapterTitles: (string | undefined)[] = Array.from({ length: chapters.length });
410 const contents = new Map<string, EpubLocation & { title: string }>();
411 function addContents(base: string, href: string | undefined, label: XmlNode | undefined) {
412 const location = href && resolve(base, href);
413 const title = label && shortTitle(text(label));
414 if (!location || !title) return;
415 const key = `${location.index}:${location.anchor ?? ""}`;
416 if (contents.size < 4096 && !contents.has(key)) contents.set(key, { ...location, title });
417 chapterTitles[location.index] ??= title;
418 }
419 const nav = [...manifest.values()].find((item) => item.properties?.split(/\s+/).includes("nav"));
420 const ncx = spine?.attrs.toc ? manifest.get(spine.attrs.toc) : undefined;
421 for (const item of [nav, ncx]) {
422 const path = item && localPath(archive, rootfile, item.href ?? "");
423 if (!path) continue;
424 const navPath = path;
425 const root = await optionalXml(navPath);
426 if (!root) continue;
427 if (item === nav) {
428 const toc = find(root, "nav").find((node) =>
429 node.attrs["epub:type"]?.split(/\s+/).includes("toc"),
430 );
431 if (toc) for (const link of find(toc, "a")) addContents(path, link.attrs.href, link);
432 } else {
433 function walk(node: XmlNode) {
434 if (node.name === "navPoint")
435 addContents(
436 navPath,
437 node.children.find((child) => child.name === "content")?.attrs.src,
438 node.children.find((child) => child.name === "navLabel"),
439 );
440 for (const child of node.children) walk(child);
441 }
442 const toc = find(root, "navMap")[0];
443 if (toc) walk(toc);
444 }
445 if (contents.size) break;
446 }
447
448 async function optionalXml(path: string) {
449 if (!archive.file(path)) return;
450 try {
451 return parseXml(await readXmlText(archive, path));
452 } catch (cause) {
453 if (!isPreviewError(cause)) throw cause;
454 }
455 }
456 const identifier = find(packageRoot, "identifier").find(
457 (node) => node.attrs.id === pkg?.attrs["unique-identifier"],
458 );
459 // DC elements use an expanded namespace in the shared XML parser.
460 const dcIdentifier =
461 pkg &&
462 find(pkg, "metadata")[0]?.children.find(
463 (node) =>
464 node.name === "{http://purl.org/dc/elements/1.1/}identifier" &&
465 node.attrs.id === pkg.attrs["unique-identifier"],
466 );
467 const id = identifier ?? dcIdentifier;
468 const bookId = id ? text(id).replace(/[\t\n\r ]/g, "") : "";
469 const idpfKey = bookId ? sha1(new TextEncoder().encode(bookId)) : undefined;
470 const uuid = /^(?:urn:uuid:)?([\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})$/i.exec(
471 bookId,
472 )?.[1];
473 const adobeKey = uuid
474 ? Uint8Array.from(uuid.replaceAll("-", "").match(/../g)!, (byte) => parseInt(byte, 16))
475 : undefined;
476
477 async function page(index: number): Promise<EpubPage & { assets: string[] }> {
478 const chapter = chapters[index];
479 if (!chapter) throw new PreviewError({ code: "epub-no-chapters" });
480 const { path, mime, fixed, narrationPath } = chapter;
481 let markupSize = 0;
482 let resourceSize = 0;
483 let resourceCount = 0;
484 let svgDepth = 0;
485 const resources = new Map<string, string>();
486 const assets: string[] = [];
487 let imagePageSize: EpubPage["fixed"];
488 let linkBase: string | undefined;
489
490 function asset(bytes: Uint8Array<ArrayBuffer>, mime: string) {
491 if (resourceSize + bytes.length > 32 * 1024 * 1024) return "";
492 resourceSize += bytes.length;
493 // SVG images need self-contained assets. The desktop font policy also allows data fonts.
494 if (svgDepth || mime.startsWith("font/")) return `data:${mime};base64,${toBase64(bytes)}`;
495 const url = URL.createObjectURL(new Blob([bytes], { type: mime }));
496 assets.push(url);
497 return url;
498 }
499 function bounded(value: string) {
500 markupSize += value.length;
501 if (markupSize > 48 * 1024 * 1024) throw new PreviewError({ code: "rendered-too-large" });
502 return value;
503 }
504
505 function embeddedAsset(source: string, kind: "raster" | "font"): string {
506 const header = /^data:([\w.+-]+\/[\w.+-]+)?;base64,/i.exec(source);
507 if (!header) return "";
508 const declared = header[1]?.toLowerCase();
509 const expectedMime =
510 declared && (Object.hasOwn(legacyFonts, declared) ? legacyFonts[declared] : declared);
511 if (expectedMime && !Object.values(kind === "font" ? fonts : images).includes(expectedMime))
512 return "";
513 const cacheKey = `${kind}:${svgDepth ? "embedded:" : "blob:"}${source}`;
514 const existing = resources.get(cacheKey);
515 if (existing !== undefined) return existing;
516 if (++resourceCount > 2048) return "";
517 resources.set(cacheKey, "");
518 const maxBytes = Math.min(
519 (kind === "font" ? 24 : 8) * 1024 * 1024,
520 32 * 1024 * 1024 - resourceSize,
521 );
522 const base64 = source.slice(header[0].length).replace(/[\t\n\f\r ]/g, "");
523 if (base64.length > Math.ceil(maxBytes / 3) * 4) return "";
524 let decoded: string;
525 try {
526 decoded = atob(base64);
527 } catch {
528 return "";
529 }
530 if (decoded.length > maxBytes) return "";
531 const bytes = Uint8Array.from(decoded, (char) => char.charCodeAt(0));
532 let mime: string | undefined;
533 if (kind === "font" && decoded.length >= 12)
534 mime = fontMimeBySignature.get(decoded.slice(0, 4));
535 else if (kind === "raster" && previewImageSize(bytes))
536 mime = rasterMimeByFirstByte[bytes[0]!];
537 if (!mime || (expectedMime && expectedMime !== mime)) return "";
538 const url = asset(bytes, mime);
539 resources.set(cacheKey, url);
540 return url;
541 }
542
543 async function resource(target: string | null): Promise<string> {
544 if (!target) return "";
545 const cacheKey = `${svgDepth ? "embedded:" : "blob:"}${target}`;
546 const existing = resources.get(cacheKey);
547 if (existing !== undefined) return existing;
548 if (++resourceCount > 2048 || resourceSize >= 32 * 1024 * 1024) return "";
549 // Mark the resource before descending into an SVG so references cannot cycle.
550 resources.set(cacheKey, "");
551 const ext = extension(target);
552 const imageType = Object.hasOwn(images, ext) ? images[ext] : undefined;
553 const fontType = Object.hasOwn(fonts, ext) ? fonts[ext] : undefined;
554 const type = media.get(target);
555 if (ext === "svg" || type === "image/svg+xml") {
556 if (svgDepth >= 8) return "";
557 const svg = (await optionalXml(target))?.children.find((node) => tagName(node) === "svg");
558 if (!svg) return "";
559 svgDepth++;
560 let markup = await render(svg, target);
561 let css = "";
562 for (const style of find(svg, "svg:style")) {
563 const source = text(style).replace(/^\uFEFF/, "");
564 if (source.length <= 256 * 1024)
565 css += `<style${attr("media", style.attrs.media)}>${escape(await cssUrls(source, target))}</style>`;
566 }
567 svgDepth--;
568 if (css) markup = `${markup.slice(0, -6)}${css}</svg>`;
569 const url = asset(new TextEncoder().encode(markup), "image/svg+xml");
570 resources.set(cacheKey, url);
571 return url;
572 }
573 const raster = type && Object.values(images).includes(type) ? type : imageType;
574 const font =
575 (type && Object.hasOwn(legacyFonts, type) ? legacyFonts[type] : undefined) ??
576 (type && Object.values(fonts).includes(type) ? type : fontType);
577 const playback =
578 type && Object.values(audiovisual).includes(type)
579 ? type
580 : Object.hasOwn(audiovisual, ext)
581 ? audiovisual[ext]
582 : undefined;
583 const mimeType = raster ?? font ?? playback;
584 const entry = mimeType && archive.file(target);
585 if (!entry) return "";
586 const bytes = new Uint8Array(await entry.async("arraybuffer"));
587 if (bytes.length > (raster ? 8 : 24) * 1024 * 1024) return "";
588 if (raster) {
589 const size = previewImageSize(bytes);
590 if (!size) return "";
591 if (target === path) imagePageSize = dimensions(size.width, size.height);
592 }
593 const algorithm = algorithms.get(target);
594 if (algorithm) {
595 const key =
596 algorithm === idpfObfuscation
597 ? idpfKey
598 : algorithm === adobeObfuscation
599 ? adobeKey
600 : undefined;
601 if (!font || !key) return "";
602 const length = Math.min(bytes.length, key === idpfKey ? 1040 : 1024);
603 for (let i = 0; i < length; i++) bytes[i] = bytes[i]! ^ key[i % key.length]!;
604 }
605 const url = asset(bytes, mimeType);
606 resources.set(cacheKey, url);
607 return url;
608 }
609
610 async function captions(target: string | null) {
611 if (!target) return "";
612 const key = `caption:${target}`;
613 const cached = resources.get(key);
614 if (cached !== undefined) return cached;
615 resources.set(key, "");
616 const entry = archive.file(target);
617 if (!entry || ++resourceCount > 2048) return "";
618 const bytes = await entry.async("uint8array");
619 if (bytes.length > 1024 * 1024) return "";
620 const type = media.get(target);
621 const ext = extension(target);
622 let content;
623 if (
624 type === "application/ttml+xml" ||
625 type === "application/ttaf+xml" ||
626 ext === "ttml" ||
627 ext === "dfxp"
628 ) {
629 try {
630 content = ttmlCaptions(parseXml(officeXmlDecoder(bytes).decode(bytes)));
631 } catch (cause) {
632 if (!isPreviewError(cause) && !(cause instanceof RangeError)) throw cause;
633 return "";
634 }
635 } else {
636 content = new TextDecoder().decode(bytes);
637 }
638 if (!/^WEBVTT(?:[ \t\r\n]|$)/.test(content)) return "";
639 const url = asset(new TextEncoder().encode(content), "text/vtt");
640 resources.set(key, url);
641 return url;
642 }
643
644 async function narration() {
645 if (!narrationPath) return [];
646 const overlay = await optionalXml(narrationPath);
647 if (!overlay) return [];
648 const cues: EpubNarrationCue[] = [];
649 for (const par of find(overlay, "smil:par").slice(0, 4096)) {
650 const audio = par.children.find((child) => child.name === "smil:audio");
651 const target = par.children.find((child) => child.name === "smil:text")?.attrs.src;
652 const textPath = target?.split("#", 1)[0];
653 if (!textPath || localPath(archive, narrationPath, textPath) !== path || !audio) continue;
654 const begin = mediaTime(audio.attrs.clipBegin) ?? 0;
655 const end = mediaTime(audio.attrs.clipEnd);
656 if (end !== undefined && end <= begin) continue;
657 const src = await resource(localPath(archive, narrationPath, audio.attrs.src ?? ""));
658 if (!src) continue;
659 const anchor = target && resolve(narrationPath, target)?.anchor;
660 cues.push({
661 src,
662 begin,
663 ...(end === undefined ? {} : { end }),
664 ...(anchor ? { anchor } : {}),
665 });
666 }
667 return cues;
668 }
669
670 async function cssUrls(css: string, base: string) {
671 let result = "";
672 let end = 0;
673 for (const match of css.matchAll(
674 /\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\burl\(\s*(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)'|((?:\\(?:[\da-f]{6}|[\da-f]{1,5}(?![\da-f]))(?:\r\n|[ \t\r\n\f])?|\\[^\da-f]|[^\s()\\])*))\s*\)/gi,
675 )) {
676 const raw = match[1] ?? match[2] ?? match[3];
677 if (raw === undefined) continue;
678 const href = /^data:/i.test(raw) ? raw : cssUnescape(raw);
679 if (href.startsWith("#")) continue;
680 const data = /^data:/i.test(href)
681 ? embeddedAsset(
682 href.replace(/\\(?:\r\n|[\r\n\f])/g, ""),
683 /^data:image\//i.test(href) ? "raster" : "font",
684 )
685 : await resource(localPath(archive, base, href));
686 const fragment = /^data:/i.test(href)
687 ? ""
688 : urlFragment(href).replace(/["\\\s]/g, encodeURIComponent);
689 result += bounded(
690 css.slice(end, match.index) + (data ? `url("${data}${fragment}")` : "url(about:blank)"),
691 );
692 end = match.index + match[0].length;
693 }
694 return result + bounded(css.slice(end));
695 }
696
697 const styles: { css: string; media: string }[] = [];
698 const stylePaths = new Set<string>();
699 let styleBytes = 0;
700 async function addStyle(css: string, base: string, query = "", depth = 0): Promise<void> {
701 styleBytes += css.length;
702 if (depth >= 8 || styleBytes > 1024 * 1024 || styles.length >= 64) return;
703 css = css.replace(/^\uFEFF/, "").replace(/^\s*@charset\s+["'][^"']+["']\s*;/i, "");
704 // `(?=(x))\1` makes the target and the tail atomic; backtracking into them is quadratic.
705 const prelude =
706 /^\s*(?:\/\*[\s\S]*?\*\/\s*)*@import\s+(?:url\(\s*)?(?:"(?=((?:\\[\s\S]|[^"\\])+))\1"|'(?=((?:\\[\s\S]|[^'\\])+))\2'|(?=((?:\\(?:[\da-f]{6}|[\da-f]{1,5}(?![\da-f]))(?:\r\n|[ \t\r\n\f])?|\\[^\da-f]|[^\s;)\\])+))\3)(?=(\s*\)?\s*([^;]*)))\4;/i;
707 for (let match = prelude.exec(css); match; match = prelude.exec(css)) {
708 css = css.slice(match[0].length);
709 const target = localPath(
710 archive,
711 base,
712 cssUnescape(match[1] ?? match[2] ?? match[3] ?? ""),
713 );
714 const condition = match[5]?.trim() ?? "";
715 if (target && !stylePaths.has(target)) {
716 stylePaths.add(target);
717 const imported = await archive.file(target)!.async("string");
718 await addStyle(
719 imported,
720 target,
721 query && condition ? `${query} and ${condition}` : condition || query,
722 depth + 1,
723 );
724 stylePaths.delete(target);
725 }
726 }
727 if (css.trim())
728 styles.push({
729 css: (await cssUrls(css, base))
730 .replaceAll(/\bepub\|type\b/g, "epub\\:type")
731 .replaceAll(/<(?=\/style)/gi, "\\3c "),
732 media: query,
733 });
734 }
735
736 async function attributes(node: XmlNode, attrs: readonly string[], base: string) {
737 let result = commonAttrs.map((key) => attr(key, node.attrs[key])).join("");
738 if (!node.attrs.lang) result += attr("lang", node.attrs["xml:lang"]);
739 for (const key of attrs) {
740 if (commonAttrs.includes(key)) continue;
741 const value = node.attrs[key];
742 if (value === undefined) continue;
743 result += attr(key, value.includes("url(") ? await cssUrls(value, base) : value);
744 }
745 if (node.attrs.style) result += attr("style", await cssUrls(node.attrs.style, base));
746 return result;
747 }
748
749 async function render(
750 node: XmlNode,
751 base: string,
752 mode?: "svg" | "math",
753 insideLink = false,
754 ): Promise<string> {
755 if (node.name === "#text") return bounded(escape(node.text));
756 const tag = tagName(node);
757 if (omitted.has(tag)) return "";
758 const namespace = tag === "svg" ? "svg" : tag === "math" ? "math" : mode;
759 const formTag = namespace === undefined && formTags.has(tag);
760 if (tag === "object" && namespace === undefined) {
761 const target = localPath(archive, base, node.attrs.data ?? "");
762 const type = node.attrs.type?.trim().toLowerCase();
763 const ext = target ? extension(target) : "";
764 const imageObject =
765 target &&
766 (!type || imageTypes.has(type)) &&
767 (ext === "svg" || Object.hasOwn(images, ext) || imageTypes.has(media.get(target) ?? ""));
768 const src = imageObject ? await resource(target) : "";
769 if (src) {
770 // Images use the sanitized image path. Other objects keep their authored fallback.
771 const props = await attributes(node, htmlAttrs, base);
772 const alt = node.attrs.alt === undefined ? attr("alt", shortTitle(text(node)) ?? "") : "";
773 return bounded(
774 `<img${props}${alt}${attr("src", src + urlFragment(node.attrs.data ?? ""))}>`,
775 );
776 }
777 }
778 const allowed =
779 namespace === "svg"
780 ? svgTags.has(tag)
781 : namespace === "math"
782 ? mathTags.has(tag)
783 : formTag || htmlTags.has(tag) || voidTags.has(tag);
784 let props = allowed
785 ? await attributes(
786 node,
787 namespace === "svg"
788 ? svgAttrs
789 : namespace === "math"
790 ? mathAttrs
791 : formTag
792 ? formAttrs
793 : htmlAttrs,
794 base,
795 )
796 : "";
797 if (formTag && staticControls.has(tag) && node.attrs.disabled === undefined)
798 props += " disabled";
799 if (tag === "svg")
800 props +=
801 ' xmlns="http://www.w3.org/2000/svg"' +
802 (svgDepth ? ' xmlns:epub="http://www.idpf.org/2007/ops"' : "") +
803 attr("xml:space", node.attrs["xml:space"]);
804 if (tag === "math") props += ' xmlns="http://www.w3.org/1998/Math/MathML"';
805 if (tag === "table" && node.children.some((child) => tagName(child) === "tr"))
806 props += ' data-epub-direct-rows=""';
807 if (tag === "tbody") props += ' data-epub-authored=""';
808 const imageControl = formTag && tag === "input" && node.attrs.type?.toLowerCase() === "image";
809 const svgImage = namespace === "svg" && tag === "image";
810 if (tag === "img" || imageControl || svgImage) {
811 const source = (node.attrs.src ?? node.attrs.href ?? node.attrs["xlink:href"] ?? "").trim();
812 const embedded = /^data:/i.test(source);
813 const src = embedded
814 ? embeddedAsset(source, "raster")
815 : await resource(localPath(archive, base, source));
816 if (!src && !imageControl)
817 return tag === "img" ? bounded(escape(node.attrs.alt ?? "")) : "";
818 const fragment = embedded ? "" : urlFragment(source);
819 if (src) props += attr(svgImage ? "href" : "src", src + fragment);
820 }
821 if (
822 namespace === "svg" &&
823 ["use", "textPath", "linearGradient", "radialGradient", "pattern"].includes(tag)
824 ) {
825 const href = node.attrs.href ?? node.attrs["xlink:href"];
826 if (href?.startsWith("#")) props += attr("href", href);
827 }
828 if (namespace === undefined && (tag === "video" || tag === "audio" || tag === "source")) {
829 const href = node.attrs.src ?? "";
830 const src = await resource(localPath(archive, base, href));
831 if (tag === "source" && !src) return "";
832 if (src) props += attr("src", src + mediaFragment(href));
833 if (tag !== "source") props += " controls" + attr("preload", node.attrs.preload);
834 if (tag !== "source" && node.attrs.loop !== undefined) props += " loop";
835 if (tag !== "source" && node.attrs.muted !== undefined) props += " muted";
836 if (tag === "video") {
837 props += " playsinline";
838 const posterHref = node.attrs.poster ?? "";
839 const poster = await resource(localPath(archive, base, posterHref));
840 if (poster) props += attr("poster", poster + urlFragment(posterHref));
841 }
842 }
843 if (namespace === undefined && tag === "track") {
844 const src = await captions(localPath(archive, base, node.attrs.src ?? ""));
845 if (!src) return "";
846 props += attr("src", src);
847 for (const key of ["kind", "srclang", "label"]) props += attr(key, node.attrs[key]);
848 if (node.attrs.default !== undefined) props += " default";
849 }
850 if (tag === "a") {
851 const href = node.attrs.href ?? node.attrs["xlink:href"];
852 const target = href && linkBase && base === path ? parseUrl(href, linkBase)?.href : href;
853 const location = target ? resolve(base, target) : undefined;
854 const external = target && !location ? externalUrl(target) : undefined;
855 if (location)
856 props +=
857 ' href="#"' +
858 attr("data-epub-index", String(location.index)) +
859 attr("data-epub-anchor", location.anchor);
860 else if (external) props += ' href="#"' + attr("data-epub-external", external);
861 else if (href && (/^ftp:\/\//i.test(href) || !/^(?:[a-z][a-z\d+.-]*:|[/\\])/i.test(href)))
862 props += ' href="#" aria-disabled="true" tabindex="-1"';
863 }
864 if (namespace === undefined && voidTags.has(tag)) return bounded(`<${tag}${props}>`);
865 const htmlLink = namespace === undefined && tag === "a";
866 let children = "";
867 for (const child of node.children)
868 children += await render(child, base, namespace, insideLink || htmlLink);
869 if (!allowed) return children;
870 const element = htmlLink && insideLink ? "epub-nested-link" : tag;
871 // The HTML parser removes a leading line break that XHTML keeps.
872 const lineBreak =
873 (tag === "pre" || tag === "textarea") && /^[\r\n]/.test(children) ? "\n" : "";
874 bounded(`<${element}${props}>${lineBreak}</${element}>`);
875 return `<${element}${props}>${lineBreak}${children}</${element}>`;
876 }
877
878 async function renderPage(): Promise<EpubPage> {
879 if (!xhtmlTypes.has(mime) && mime !== "image/svg+xml") {
880 const data = await resource(path);
881 if (!data) throw new PreviewError({ code: "epub-no-chapters" });
882 return { html: `<img src="${data}" alt="">`, imagePage: true, fixed: imagePageSize };
883 }
884 const root = await readChapter(archive, path, mime);
885 if (mime === "image/svg+xml") {
886 const svg = root.children.find((node) => tagName(node) === "svg");
887 if (!svg) throw new PreviewError({ code: "xml-invalid" });
888 for (const instruction of root.children) {
889 if (instruction.name !== "?xml-stylesheet") continue;
890 const target = localPath(archive, path, instruction.attrs.href ?? "");
891 if (target)
892 await addStyle(
893 await archive.file(target)!.async("string"),
894 target,
895 instruction.attrs.media,
896 );
897 }
898 for (const node of find(svg, "svg:style"))
899 await addStyle(text(node), path, node.attrs.media);
900 const label = find(svg, "svg:title")[0];
901 const size = svgViewport(svg);
902 return {
903 html: await render(svg, path),
904 title: label && shortTitle(text(label)),
905 styles,
906 fixed: size,
907 imagePage: true,
908 };
909 }
910 const html = find(root, "html")[0];
911 const head = html?.children.find((node) => node.name === "head");
912 const body = html?.children.find((node) => node.name === "body");
913 if (head) {
914 const base = head.children.find(
915 (node) => node.name === "base" && node.attrs.href !== undefined,
916 )?.attrs.href;
917 const url = base ? parseUrl(base) : null;
918 if (url?.protocol === "http:" || url?.protocol === "https:") linkBase = url.href;
919 for (const node of head.children) {
920 const rel = node.attrs.rel?.toLowerCase().split(/\s+/) ?? [];
921 if (node.name === "link" && rel.includes("stylesheet") && !rel.includes("alternate")) {
922 const target = localPath(archive, path, node.attrs.href ?? "");
923 if (target)
924 await addStyle(await archive.file(target)!.async("string"), target, node.attrs.media);
925 } else if (node.name === "style") await addStyle(text(node), path, node.attrs.media);
926 }
927 }
928 // XHTML producers also place styles in the body. Keep the cascade in source order.
929 if (body)
930 for (const node of find(body, "style")) await addStyle(text(node), path, node.attrs.media);
931 const title = [...(head ? find(head, "title") : []), ...find(body ?? root, "h1")]
932 .map((heading) => shortTitle(text(heading)))
933 .find(Boolean);
934 const content = body ?? html ?? root;
935 let markup = "";
936 for (const node of content.children) markup += await render(node, path);
937 const cover = path === coverPath || body?.attrs["epub:type"]?.split(/\s+/).includes("cover");
938 const coverSvg = cover && body && find(body, "svg:svg")[0];
939 const authoredSize = fixed ? viewport(root) : undefined;
940 const imageSize = !authoredSize && coverSvg ? svgViewport(coverSvg) : undefined;
941 return {
942 html: markup,
943 title,
944 styles,
945 htmlAttrs: html ? bounded(await attributes(html, [], path)) : undefined,
946 bodyAttrs: body ? bounded(await attributes(body, [], path)) : undefined,
947 fixed: authoredSize ?? imageSize,
948 };
949 }
950 try {
951 const page = await renderPage();
952 const cues = await narration();
953 return { ...page, ...(cues.length ? { narration: cues } : {}), assets };
954 } catch (cause) {
955 for (const url of assets) URL.revokeObjectURL(url);
956 throw cause;
957 }
958 }
959
960 const first = chapters.findIndex((chapter) => chapter.linear);
961 return {
962 first: Math.max(0, first),
963 rtl: spine?.attrs["page-progression-direction"] === "rtl",
964 chapters: chapters.map((chapter, index) => ({
965 title: chapterTitles[index],
966 linear: chapter.linear,
967 })),
968 contents: [...contents.values()],
969 page,
970 };
971}