@bendyline/squisq-formats 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/__tests__/html.test.js +78 -4
  2. package/dist/__tests__/html.test.js.map +1 -1
  3. package/dist/__tests__/pdfExport.test.js +1 -1
  4. package/dist/__tests__/pdfExport.test.js.map +1 -1
  5. package/dist/__tests__/plainHtml.test.d.ts +5 -0
  6. package/dist/__tests__/plainHtml.test.d.ts.map +1 -0
  7. package/dist/__tests__/plainHtml.test.js +327 -0
  8. package/dist/__tests__/plainHtml.test.js.map +1 -0
  9. package/dist/__tests__/plainHtmlBundle.test.d.ts +11 -0
  10. package/dist/__tests__/plainHtmlBundle.test.d.ts.map +1 -0
  11. package/dist/__tests__/plainHtmlBundle.test.js +210 -0
  12. package/dist/__tests__/plainHtmlBundle.test.js.map +1 -0
  13. package/dist/chunk-33YRFXZZ.js +1187 -0
  14. package/dist/chunk-33YRFXZZ.js.map +1 -0
  15. package/dist/{chunk-EUQQYBZZ.js → chunk-ERZ627GR.js} +4 -4
  16. package/dist/chunk-ERZ627GR.js.map +1 -0
  17. package/dist/{chunk-MEZF76JA.js → chunk-UDS45KUJ.js} +68 -25
  18. package/dist/chunk-UDS45KUJ.js.map +1 -0
  19. package/dist/{chunk-NGWHV77G.js → chunk-VN2KEOYB.js} +7 -6
  20. package/dist/chunk-VN2KEOYB.js.map +1 -0
  21. package/dist/docx/export.d.ts.map +1 -1
  22. package/dist/docx/export.js +153 -22
  23. package/dist/docx/export.js.map +1 -1
  24. package/dist/epub/export.js +3 -3
  25. package/dist/epub/export.js.map +1 -1
  26. package/dist/html/docsHtmlBundle.d.ts +53 -0
  27. package/dist/html/docsHtmlBundle.d.ts.map +1 -0
  28. package/dist/html/docsHtmlBundle.js +299 -0
  29. package/dist/html/docsHtmlBundle.js.map +1 -0
  30. package/dist/html/htmlTemplate.d.ts.map +1 -1
  31. package/dist/html/htmlTemplate.js +43 -0
  32. package/dist/html/htmlTemplate.js.map +1 -1
  33. package/dist/html/index.d.ts +6 -0
  34. package/dist/html/index.d.ts.map +1 -1
  35. package/dist/html/index.js +31 -3
  36. package/dist/html/index.js.map +1 -1
  37. package/dist/html/plainHtml.d.ts +79 -0
  38. package/dist/html/plainHtml.d.ts.map +1 -0
  39. package/dist/html/plainHtml.js +614 -0
  40. package/dist/html/plainHtml.js.map +1 -0
  41. package/dist/html/plainHtmlBundle.d.ts +93 -0
  42. package/dist/html/plainHtmlBundle.d.ts.map +1 -0
  43. package/dist/html/plainHtmlBundle.js +357 -0
  44. package/dist/html/plainHtmlBundle.js.map +1 -0
  45. package/dist/pptx/export.d.ts.map +1 -1
  46. package/dist/pptx/export.js +10 -8
  47. package/dist/pptx/export.js.map +1 -1
  48. package/package.json +3 -2
  49. package/src/__tests__/html.test.ts +82 -4
  50. package/src/__tests__/pdfExport.test.ts +1 -1
  51. package/src/__tests__/plainHtml.test.ts +372 -0
  52. package/src/__tests__/plainHtmlBundle.test.ts +235 -0
  53. package/src/docx/export.ts +163 -22
  54. package/src/epub/export.ts +3 -3
  55. package/src/html/docsHtmlBundle.ts +369 -0
  56. package/src/html/htmlTemplate.ts +40 -0
  57. package/src/html/index.ts +32 -3
  58. package/src/html/plainHtml.ts +736 -0
  59. package/src/html/plainHtmlBundle.ts +419 -0
  60. package/src/pptx/export.ts +10 -9
  61. package/dist/chunk-EUQQYBZZ.js.map +0 -1
  62. package/dist/chunk-MEZF76JA.js.map +0 -1
  63. package/dist/chunk-NGWHV77G.js.map +0 -1
  64. package/dist/chunk-UM5V2XZG.js +0 -242
  65. package/dist/chunk-UM5V2XZG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/html/index.ts","../src/html/htmlTemplate.ts","../src/html/plainHtml.ts","../src/html/plainHtmlBundle.ts","../src/html/docsHtmlBundle.ts"],"sourcesContent":["/**\n * HTML Export Module — @bendyline/squisq-formats/html\n *\n * Exports squisq documents as self-contained HTML files or ZIP archives.\n *\n * Two export modes:\n *\n * 1. **Single HTML** (`docToHtml`) — Everything embedded in one file:\n * - SquisqPlayer IIFE bundle inlined in `<script>`\n * - Images base64-encoded as data URIs\n * - Timer-based playback (no audio — too large for inline)\n *\n * 2. **ZIP Archive** (`docToHtmlZip`) — Multi-file package:\n * - `index.html` referencing external `squisq-player.js`\n * - `squisq-player.js` — the IIFE bundle\n * - `images/` — extracted image files\n * - `audio/` — optional audio segment files (enables full playback)\n *\n * @example\n * ```ts\n * import { PLAYER_BUNDLE } from '@bendyline/squisq-react/standalone-source';\n * import { docToHtml, docToHtmlZip } from '@bendyline/squisq-formats/html';\n *\n * // Single HTML file\n * const html = docToHtml(doc, { playerScript: PLAYER_BUNDLE, images });\n *\n * // ZIP archive\n * const zipBlob = await docToHtmlZip(doc, { playerScript: PLAYER_BUNDLE, images, audio });\n * ```\n */\n\nimport type { Doc } from '@bendyline/squisq/schemas';\nimport JSZip from 'jszip';\nimport {\n generateInlineHtml,\n generateExternalHtml,\n type HtmlExportOptions,\n} from './htmlTemplate.js';\nimport { extractFilename } from './imageUtils.js';\n\n// ── Public Types ───────────────────────────────────────────────────\n\nexport type { HtmlExportOptions };\n\n/**\n * Normalize a doc-referenced path for use as a zip entry name. Strips\n * leading slashes and rejects any path that tries to escape the archive\n * root via `..` segments (a malicious or malformed doc shouldn't be able\n * to write outside the zip when extracted). Backslashes are folded to\n * forward slashes so Windows-authored paths still produce a consistent\n * tree across extractors.\n */\nfunction sanitizeZipPath(path: string): string | null {\n const normalized = path.replace(/\\\\/g, '/').replace(/^\\/+/, '');\n if (!normalized) return null;\n if (normalized.split('/').some((seg) => seg === '..')) return null;\n return normalized;\n}\n\nexport interface HtmlZipExportOptions extends HtmlExportOptions {\n /**\n * Map of audio segment identifiers to binary audio data.\n * Keys should match the audio segment `name` or `url` fields in the Doc.\n * When provided, audio files are included in the ZIP and full playback is enabled.\n */\n audio?: Map<string, ArrayBuffer>;\n}\n\n// ── Single HTML Export ─────────────────────────────────────────────\n\n/**\n * Export a Doc as a single, self-contained HTML file.\n *\n * The player JS is embedded inline, images are base64-encoded as data URIs,\n * and playback uses a timer (no audio) for compact file size.\n *\n * @param doc - The Doc to export\n * @param options - Export options (must include `playerScript`)\n * @returns Complete HTML document as a string\n *\n * @example\n * ```ts\n * const html = docToHtml(myDoc, {\n * playerScript: PLAYER_BUNDLE,\n * images: imageMap,\n * title: 'My Document',\n * mode: 'slideshow',\n * });\n * const blob = new Blob([html], { type: 'text/html' });\n * ```\n */\nexport function docToHtml(doc: Doc, options: HtmlExportOptions): string {\n return generateInlineHtml(doc, options);\n}\n\n// ── ZIP Archive Export ─────────────────────────────────────────────\n\n/**\n * Export a Doc as a ZIP archive containing HTML, JS, images, and optionally audio.\n *\n * The archive structure:\n * ```\n * document.zip\n * ├── index.html # HTML page referencing squisq-player.js\n * ├── squisq-player.js # Standalone IIFE bundle\n * ├── images/ # Extracted image files\n * │ ├── hero.jpg\n * │ └── ...\n * └── audio/ # Optional audio segment files\n * ├── intro.mp3\n * └── ...\n * ```\n *\n * @param doc - The Doc to export\n * @param options - Export options (must include `playerScript`)\n * @returns A Promise resolving to a ZIP Blob\n *\n * @example\n * ```ts\n * const blob = await docToHtmlZip(myDoc, {\n * playerScript: PLAYER_BUNDLE,\n * images: imageMap,\n * audio: audioMap,\n * });\n * // Trigger browser download\n * const url = URL.createObjectURL(blob);\n * ```\n */\nexport async function docToHtmlZip(doc: Doc, options: HtmlZipExportOptions): Promise<Blob> {\n const { playerScript, images, audio, mode = 'slideshow', title, autoPlay } = options;\n\n const zip = new JSZip();\n\n // 1. Add player JS as a separate file\n zip.file('squisq-player.js', playerScript);\n\n // 2. Add images preserving their original relative paths.\n //\n // We used to flatten everything into `images/<basename>`, but that\n // requires the player to rewrite every `<img src>` at render time using\n // the path map — and the static (non-slideshow) renderer doesn't do\n // that, so its emitted `<img>` tags 404'd against the renamed assets.\n // Keeping the original layout means direct `src=\"folder/file.png\"`\n // references just work, and the exported zip mirrors how the source\n // folder is organized (e.g. pandoc-style `notes_files/` sidecars).\n const imagePathMap: Record<string, string> = {};\n if (images) {\n for (const [originalPath, buffer] of images.entries()) {\n const zipPath = sanitizeZipPath(originalPath);\n if (!zipPath) continue;\n zip.file(zipPath, buffer);\n imagePathMap[originalPath] = zipPath;\n }\n }\n\n // 3. Add audio to audio/ folder and build path mapping\n const audioPathMap: Record<string, string> = {};\n if (audio) {\n for (const [segmentKey, buffer] of audio.entries()) {\n const filename = extractFilename(segmentKey);\n // Ensure .mp3 extension\n const finalName = filename.includes('.') ? filename : `${filename}.mp3`;\n const zipPath = `audio/${finalName}`;\n zip.file(zipPath, buffer);\n audioPathMap[segmentKey] = zipPath;\n }\n }\n\n // 4. Generate HTML that references external files\n const html = generateExternalHtml(doc, {\n playerScriptPath: 'squisq-player.js',\n imagePathMap: Object.keys(imagePathMap).length > 0 ? imagePathMap : undefined,\n audioPathMap: Object.keys(audioPathMap).length > 0 ? audioPathMap : undefined,\n mode,\n title,\n autoPlay,\n });\n zip.file('index.html', html);\n\n // 5. Generate ZIP blob\n return zip.generateAsync({\n type: 'blob',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n });\n}\n\n// ── Re-exports ─────────────────────────────────────────────────────\n\nexport { collectImagePaths } from './htmlTemplate.js';\nexport { inferMimeType, arrayBufferToBase64DataUrl, extractFilename } from './imageUtils.js';\nexport { markdownDocToPlainHtml } from './plainHtml.js';\nexport type { PlainHtmlExportOptions } from './plainHtml.js';\nexport { markdownDocsToPlainHtmlBundle, collectLinkRefs } from './plainHtmlBundle.js';\nexport type { PlainHtmlBundleOptions } from './plainHtmlBundle.js';\nexport { markdownDocsToHtmlBundle } from './docsHtmlBundle.js';\nexport type { HtmlBundleOptions } from './docsHtmlBundle.js';\n","/**\n * HTML Template Generation for SquisqPlayer Exports\n *\n * Generates complete, self-contained HTML documents that load the SquisqPlayer\n * IIFE bundle and render a Doc as either an interactive slideshow or a static\n * scrollable document.\n *\n * Two variants:\n * 1. **Inline** — All JS, CSS, and images are embedded in the HTML (single file).\n * 2. **External** — JS is referenced via `<script src>`, images via relative paths.\n */\n\nimport type { Doc, Layer, Block } from '@bendyline/squisq/schemas';\nimport { arrayBufferToBase64DataUrl, inferMimeType } from './imageUtils.js';\n\n// ── Types ──────────────────────────────────────────────────────────\n\nexport interface HtmlExportOptions {\n /** The IIFE player bundle source code (from @bendyline/squisq-react/standalone-source) */\n playerScript: string;\n\n /**\n * Map of relative image paths (as they appear in the Doc) to binary image data.\n * For inline HTML export, these are converted to base64 data URIs.\n * For ZIP export, these are written as separate files.\n */\n images?: Map<string, ArrayBuffer>;\n\n /**\n * Map of audio segment identifiers to binary audio data.\n * Keys should match the audio segment `name` or `url` fields in the Doc.\n * Only used in ZIP exports — single HTML uses timer-based playback.\n */\n audio?: Map<string, ArrayBuffer>;\n\n /** Rendering mode: 'slideshow' (interactive, default) or 'static' (scrollable) */\n mode?: 'slideshow' | 'static';\n\n /** HTML page title (default: 'Squisq Document') */\n title?: string;\n\n /** Auto-play slideshow on load (default: false) */\n autoPlay?: boolean;\n\n /**\n * Squisq theme ID to apply (e.g., 'documentary', 'cinematic').\n * When set, the theme is assigned to the Doc before rendering,\n * so the SquisqPlayer renders with that theme's colors and typography.\n */\n themeId?: string;\n}\n\n// ── Image Path Collection ──────────────────────────────────────────\n\n/**\n * Collect all relative image paths referenced in a Doc's layers and template blocks.\n * Returns a Set of unique relative paths that need to be resolved.\n */\nexport function collectImagePaths(doc: Doc): Set<string> {\n const paths = new Set<string>();\n\n function addIfRelative(src: string | undefined) {\n if (\n !src ||\n src.startsWith('data:') ||\n src.startsWith('blob:') ||\n src.startsWith('http://') ||\n src.startsWith('https://')\n ) {\n return;\n }\n paths.add(src);\n }\n\n function scanLayers(layers: Layer[] | undefined) {\n if (!layers) return;\n for (const layer of layers) {\n if (layer.type === 'image') addIfRelative(layer.content.src);\n if (layer.type === 'video') {\n addIfRelative(layer.content.src);\n addIfRelative(layer.content.posterSrc);\n }\n if (layer.type === 'map') addIfRelative(layer.content.staticSrc);\n }\n }\n\n function scanBlock(block: Block) {\n scanLayers(block.layers);\n if (block.contents) scanMarkdownNodes(block.contents, addIfRelative);\n if (block.children) block.children.forEach(scanBlock);\n }\n\n // Scan all blocks\n doc.blocks.forEach(scanBlock);\n\n // Scan start block hero\n if (doc.startBlock?.heroSrc) addIfRelative(doc.startBlock.heroSrc);\n\n // Scan persistent layers\n if (doc.persistentLayers) {\n for (const pl of doc.persistentLayers.bottomLayers ?? []) {\n if ('src' in pl && typeof pl.src === 'string') addIfRelative(pl.src);\n }\n for (const pl of doc.persistentLayers.topLayers ?? []) {\n if ('src' in pl && typeof pl.src === 'string') addIfRelative(pl.src);\n }\n }\n\n // Scan template block fields that reference images\n for (const block of doc.blocks) {\n scanTemplateImageFields(block as unknown as Record<string, unknown>, paths);\n }\n\n return paths;\n}\n\n/**\n * Walk markdown body nodes for image references. Catches both shorthand\n * `![alt](url)` (type `image`, `url` field) and raw HTML `<img src>` tags\n * (type `htmlBlock`/`htmlInline`, `htmlChildren` sub-tree) — the latter is\n * how the WYSIWYG editor round-trips resized images, since markdown\n * shorthand has no width syntax.\n */\nfunction scanMarkdownNodes(nodes: unknown[], visit: (src: string | undefined) => void): void {\n for (const node of nodes) {\n if (!node || typeof node !== 'object') continue;\n const n = node as Record<string, unknown>;\n if (n.type === 'image' && typeof n.url === 'string') {\n visit(n.url);\n }\n if ((n.type === 'htmlBlock' || n.type === 'htmlInline') && Array.isArray(n.htmlChildren)) {\n scanHtmlNodes(n.htmlChildren, visit);\n }\n if (Array.isArray(n.children)) {\n scanMarkdownNodes(n.children, visit);\n }\n }\n}\n\n/** Walk a parsed HTML sub-tree for `<img>` src attributes. */\nfunction scanHtmlNodes(nodes: unknown[], visit: (src: string | undefined) => void): void {\n for (const node of nodes) {\n if (!node || typeof node !== 'object') continue;\n const n = node as Record<string, unknown>;\n if (n.type !== 'htmlElement') continue;\n if (n.tagName === 'img') {\n const attrs = n.attributes as Record<string, string> | undefined;\n if (attrs && typeof attrs.src === 'string') visit(attrs.src);\n }\n if (Array.isArray(n.children)) {\n scanHtmlNodes(n.children, visit);\n }\n }\n}\n\n/**\n * Recursively scan any object for known image-bearing field names.\n */\nfunction scanTemplateImageFields(obj: Record<string, unknown>, paths: Set<string>): void {\n if (!obj || typeof obj !== 'object') return;\n\n const imageFieldNames = [\n 'imageSrc',\n 'src',\n 'heroSrc',\n 'backgroundImage',\n 'posterSrc',\n 'staticSrc',\n 'videoSrc',\n 'thumbnailSrc',\n ];\n\n for (const key of imageFieldNames) {\n const val = obj[key];\n if (typeof val === 'string' && val && !val.startsWith('data:') && !val.startsWith('http')) {\n paths.add(val);\n }\n // Handle nested objects like { src: '...' }\n if (val && typeof val === 'object' && !Array.isArray(val)) {\n scanTemplateImageFields(val as Record<string, unknown>, paths);\n }\n }\n\n // Handle arrays (e.g., images: [{ src: '...' }])\n if (Array.isArray(obj)) {\n for (const item of obj) {\n if (item && typeof item === 'object') {\n scanTemplateImageFields(item as Record<string, unknown>, paths);\n }\n }\n }\n\n // Recurse into known array/object fields\n for (const key of ['images', 'accentImage', 'backgroundVideo', 'children', 'blocks']) {\n const val = obj[key];\n if (Array.isArray(val)) {\n for (const item of val) {\n if (item && typeof item === 'object') {\n scanTemplateImageFields(item as Record<string, unknown>, paths);\n }\n }\n } else if (val && typeof val === 'object') {\n scanTemplateImageFields(val as Record<string, unknown>, paths);\n }\n }\n}\n\n// ── HTML Generation ────────────────────────────────────────────────\n\n/**\n * Escape a string for safe embedding in a `<script>` tag.\n * Prevents `</script>` from closing the tag prematurely.\n */\nfunction escapeForScript(str: string): string {\n return str.replace(/<\\/(script)/gi, '<\\\\/$1');\n}\n\n/**\n * Generate a complete inline HTML document with all JS and images embedded.\n *\n * @param doc - The Doc to render\n * @param options - Export options\n * @returns Complete HTML string\n */\nexport function generateInlineHtml(doc: Doc, options: HtmlExportOptions): string {\n const {\n playerScript,\n images,\n mode = 'slideshow',\n title = 'Squisq Document',\n autoPlay = false,\n themeId,\n } = options;\n\n // Apply theme to doc if specified (the SquisqPlayer respects doc.themeId at render time)\n if (themeId) {\n doc = { ...doc, themeId };\n }\n\n // Build base64 image map\n const imageMap: Record<string, string> = {};\n if (images) {\n for (const [path, buffer] of images.entries()) {\n const mimeType = inferMimeType(path);\n imageMap[path] = arrayBufferToBase64DataUrl(buffer, mimeType);\n }\n }\n\n const docJson = escapeForScript(JSON.stringify(doc));\n const imageMapJson = escapeForScript(JSON.stringify(imageMap));\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>${escapeHtml(title)}</title>\n<style>\n*,*::before,*::after{box-sizing:border-box}\nhtml,body{margin:0;padding:0;height:100%;background:#1a1a2e;color:#e0e0e0;font-family:system-ui,-apple-system,sans-serif}\n#squisq-root{width:100%;height:100%;display:flex;align-items:center;justify-content:center}\n${mode === 'static' ? '#squisq-root{align-items:flex-start;overflow-y:auto;background:#fff;color:#1f2937}' : ''}\n</style>\n</head>\n<body>\n<div id=\"squisq-root\"></div>\n<script>${escapeForScript(playerScript)}</script>\n<script>\n(function(){\n var doc = JSON.parse(${JSON.stringify(docJson)});\n var images = JSON.parse(${JSON.stringify(imageMapJson)});\n SquisqPlayer.mount(document.getElementById(\"squisq-root\"), doc, {\n mode: ${JSON.stringify(mode)},\n images: images,\n autoPlay: ${JSON.stringify(autoPlay)},\n basePath: \".\"\n });\n})();\n</script>\n</body>\n</html>`;\n}\n\n/**\n * Generate an HTML document that references external JS and image files.\n * Used for ZIP exports where files sit alongside the HTML.\n *\n * @param doc - The Doc to render (image/audio paths should already be rewritten to relative)\n * @param options - Export options (playerScript is not embedded, referenced via src)\n * @returns Complete HTML string\n */\nexport function generateExternalHtml(\n doc: Doc,\n options: Pick<HtmlExportOptions, 'mode' | 'title' | 'autoPlay'> & {\n /** Relative path to the player JS file (e.g., 'squisq-player.js') */\n playerScriptPath: string;\n /** Map of original image paths to their rewritten relative paths in the ZIP */\n imagePathMap?: Record<string, string>;\n /** Map of audio segment IDs to their rewritten relative paths in the ZIP */\n audioPathMap?: Record<string, string>;\n },\n): string {\n const {\n playerScriptPath,\n imagePathMap,\n audioPathMap,\n mode = 'slideshow',\n title = 'Squisq Document',\n autoPlay = false,\n } = options;\n\n const docJson = escapeForScript(JSON.stringify(doc));\n const imageMapJson = imagePathMap ? escapeForScript(JSON.stringify(imagePathMap)) : '{}';\n const audioMapJson = audioPathMap ? escapeForScript(JSON.stringify(audioPathMap)) : 'null';\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>${escapeHtml(title)}</title>\n<style>\n*,*::before,*::after{box-sizing:border-box}\nhtml,body{margin:0;padding:0;height:100%;background:#1a1a2e;color:#e0e0e0;font-family:system-ui,-apple-system,sans-serif}\n#squisq-root{width:100%;height:100%;display:flex;align-items:center;justify-content:center}\n${mode === 'static' ? '#squisq-root{align-items:flex-start;overflow-y:auto;background:#fff;color:#1f2937}' : ''}\n</style>\n</head>\n<body>\n<div id=\"squisq-root\"></div>\n<script src=\"${escapeHtml(playerScriptPath)}\"></script>\n<script>\n(function(){\n var doc = JSON.parse(${JSON.stringify(docJson)});\n var images = JSON.parse(${JSON.stringify(imageMapJson)});\n var audio = ${audioMapJson};\n SquisqPlayer.mount(document.getElementById(\"squisq-root\"), doc, {\n mode: ${JSON.stringify(mode)},\n images: images,\n audio: audio,\n autoPlay: ${JSON.stringify(autoPlay)},\n basePath: \".\"\n });\n})();\n</script>\n</body>\n</html>`;\n}\n\n/**\n * Escape HTML special characters to prevent injection.\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n","/**\n * Plain HTML Export — semantic, player-free\n *\n * Renders a MarkdownDocument to a self-contained HTML string. Unlike\n * `docToHtml` (which bundles the SquisqPlayer IIFE and renders SVG block\n * cards), this output is what a reader-mode tool would produce: semantic\n * `<h1>`/`<p>`/`<ul>`/etc. with a small embedded stylesheet, no JS, no\n * runtime path-rewriting. Drives both the \"Page\" preview tab in the\n * editor and the plain-style branch of the export dialog so what users\n * see live matches the file they download.\n *\n * Image URLs default to the markdown's own paths. Pass `images` to\n * substitute a different value per source URL — typically pre-resolved\n * blob URLs (live preview) or data URIs (single-file export).\n */\n\nimport type { MarkdownDocument, MarkdownNode, HtmlNode } from '@bendyline/squisq/markdown';\nimport type { Theme } from '@bendyline/squisq/schemas';\nimport { resolveFontFamily, buildGoogleFontsUrl, resolveTheme } from '@bendyline/squisq/schemas';\n\n// ── Public Types ───────────────────────────────────────────────────\n\nexport interface PlainHtmlExportOptions {\n /** Document title — populates `<title>` and is HTML-escaped. */\n title?: string;\n /**\n * Substitution map for image `src` URLs. Keys are the URL exactly as\n * it appears in the markdown source; values are the URL to emit in\n * the rendered `<img src>`. URLs not present in the map fall through\n * unchanged (so external `https://…` references still work).\n */\n images?: Map<string, string>;\n /**\n * Substitution map for anchor `href` URLs. Keys are the URL exactly\n * as it appears in the markdown source (e.g. `'resume.md'`,\n * `'resume.md#experience'`); values are the URL to emit. URLs not in\n * the map pass through unchanged. Used by the recursive bundle\n * exporter to rewrite `.md` references to `.html` so a static export\n * of a linked document tree is internally browsable.\n */\n links?: Map<string, string>;\n /**\n * Optional Squisq theme. When provided, the rendered page uses the\n * theme's colors and typography, and any Google-hosted fonts the\n * theme references are loaded via a `<link>` to fonts.googleapis.com\n * so the face renders correctly without host preloads.\n *\n * When omitted, the function falls back (in order) to {@link themeId}\n * and then to `doc.frontmatter.themeId` — so an authored\n * `themeId: warm-earth` in the doc's frontmatter styles the export\n * automatically, without the caller having to wire theme resolution\n * themselves.\n */\n theme?: Theme;\n /**\n * Optional theme id (e.g. `'warm-earth'`, `'gezellig'`). Convenient\n * for hosts whose export dialog tracks themes by id — they can pass\n * the id straight through instead of resolving to a `Theme` object.\n * When both `theme` and `themeId` are provided, `theme` wins.\n */\n themeId?: string;\n /**\n * Optional FontAwesome CSS text to inline into the rendered page,\n * replacing the default cross-origin `<link>` to cdnjs. Required for\n * sandboxed iframe previews where tracking prevention or stricter\n * origin policies can silently drop cross-origin font fetches —\n * inlining keeps the icons resolvable purely from same-origin\n * resources. Hosts typically gather this string by scraping\n * `document.styleSheets` for `@font-face` rules whose family starts\n * with `\"Font Awesome\"`. The CDN `<link>` is only emitted when this\n * option is not provided.\n */\n iconsCss?: string;\n}\n\n/**\n * Internal render context — bundles the substitution maps so adding a\n * new one (e.g. `links`) doesn't require threading another parameter\n * through every node renderer.\n */\ninterface RenderCtx {\n images?: Map<string, string>;\n links?: Map<string, string>;\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Render a parsed markdown document as a complete, semantic HTML page.\n *\n * When `options.theme` is provided, the output adopts the theme's\n * colors and typography. Google-hosted fonts referenced by the theme\n * are loaded via a single `<link>` to fonts.googleapis.com so the page\n * renders consistently when opened standalone.\n */\nexport function markdownDocToPlainHtml(\n doc: MarkdownDocument,\n options: PlainHtmlExportOptions = {},\n): string {\n const { title = 'Document', images, links, themeId, iconsCss } = options;\n // Fall back chain for theme: explicit `theme` → explicit `themeId`\n // option → doc frontmatter `themeId`. Hosts whose export dialog\n // tracks themes by id can pass `themeId` straight through; authored\n // docs with `themeId: warm-earth` in frontmatter get styled\n // automatically when neither is supplied.\n const theme =\n options.theme ??\n (themeId ? resolveTheme(themeId) : undefined) ??\n (typeof doc.frontmatter?.themeId === 'string'\n ? resolveTheme(doc.frontmatter.themeId)\n : undefined);\n const ctx: RenderCtx = { images, links };\n const body = renderTopLevel(doc.children, ctx);\n const fontsLink = theme ? renderFontsLink(theme) : '';\n // Resolve how to load FontAwesome — only when the doc actually uses\n // icons. When the host supplies `iconsCss` (typical for sandboxed\n // iframe previews where cross-origin font fetches get blocked), we\n // inline it as a `<style>` block; otherwise we fall back to the\n // public cdnjs `<link>` which works for standalone HTML files.\n const usesIcons = docUsesIcons(doc);\n let iconsLink = '';\n if (usesIcons) {\n iconsLink = iconsCss ? `<style data-fa-inline>\\n${iconsCss}\\n</style>\\n` : FONT_AWESOME_LINK;\n }\n const themedCss = theme ? renderThemedCss(theme) : DEFAULT_CSS;\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>${escapeHtml(title)}</title>\n${fontsLink}${iconsLink}<style>\n${themedCss}\n${FEATURE_CSS}\n</style>\n</head>\n<body>\n${body}\n</body>\n</html>`;\n}\n\n/**\n * Hosted FontAwesome Free CSS. Pinned to a specific release so the\n * integrity hash stays in sync — bump both fields together when\n * upgrading. Cdnjs serves the matching SRI hash on every release page.\n */\nconst FONT_AWESOME_LINK = `<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css\" integrity=\"sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\">\n`;\n\n/** Walk the doc looking for any `inlineIcon` node. Cheap depth-first\n * traversal — bails out at the first hit. */\nfunction docUsesIcons(doc: MarkdownDocument): boolean {\n function visit(node: unknown): boolean {\n if (!node || typeof node !== 'object') return false;\n const n = node as Record<string, unknown>;\n if (n.type === 'inlineIcon') return true;\n if (Array.isArray(n.children)) {\n for (const child of n.children) if (visit(child)) return true;\n }\n return false;\n }\n return visit(doc);\n}\n\n// ── Top-level walk with feature-section grouping ───────────────────\n\n/**\n * Walk the document's top-level children, grouping headings that carry\n * a `leftFeature` / `rightFeature` template annotation with the body\n * blocks that follow them (up to the next sibling-or-higher heading).\n * Each group renders as a single `<section class=\"squisq-feature ...\">`\n * with a media column and a text column — the plain-HTML analogue of\n * the SVG layer layout produced by `getLayers` for the same templates.\n */\nfunction renderTopLevel(children: MarkdownNode[], ctx: RenderCtx | undefined): string {\n const out: string[] = [];\n for (let i = 0; i < children.length; i++) {\n const node = children[i] as { type?: string };\n if (node && node.type === 'heading') {\n const heading = node as MarkdownHeadingLike;\n const tpl = heading.templateAnnotation?.template;\n if (tpl === 'leftFeature' || tpl === 'rightFeature') {\n const end = findSectionEnd(children, i);\n const sectionBody = children.slice(i + 1, end);\n out.push(renderFeatureSection(heading, sectionBody, tpl, ctx));\n i = end - 1;\n continue;\n }\n }\n out.push(nodeToHtml(node as MarkdownNode, ctx));\n }\n return out.join('\\n');\n}\n\ninterface MarkdownHeadingLike {\n type: 'heading';\n depth: number;\n children?: MarkdownNode[];\n templateAnnotation?: { template?: string };\n}\n\n/**\n * Index of the next heading after `from`; otherwise the array length.\n * Feature sections greedily eat the heading's immediate body content\n * (paragraphs, lists, images) up to the next heading of any depth — a\n * nested sub-heading inside a feature would look chaotic in the\n * side-by-side layout, so we keep features short by design.\n */\nfunction findSectionEnd(nodes: MarkdownNode[], from: number): number {\n for (let i = from + 1; i < nodes.length; i++) {\n const n = nodes[i] as { type?: string };\n if (n && n.type === 'heading') return i;\n }\n return nodes.length;\n}\n\n/**\n * Render a feature section as `<section class=\"squisq-feature ...\">`.\n * The first image found in the body becomes the media column; the\n * heading + remaining content (with the image stripped, so it doesn't\n * appear twice) becomes the text column.\n */\nfunction renderFeatureSection(\n heading: MarkdownHeadingLike,\n bodyNodes: MarkdownNode[],\n side: 'leftFeature' | 'rightFeature',\n ctx: RenderCtx | undefined,\n): string {\n const headingTag = `h${Math.min(Math.max(heading.depth ?? 2, 1), 6)}`;\n const headingHtml = `<${headingTag}>${childrenToHtml({ children: heading.children }, ctx)}</${headingTag}>`;\n\n const featured = takeFirstImage(bodyNodes);\n const media = featured.image\n ? renderFeatureImage(featured.image, ctx)\n : '<div class=\"squisq-feature__media squisq-feature__media--empty\"></div>';\n\n const textHtml = [headingHtml, ...featured.remaining.map((n) => nodeToHtml(n, ctx))]\n .filter((s) => s.length > 0)\n .join('\\n');\n\n const sideClass = side === 'leftFeature' ? 'squisq-feature--left' : 'squisq-feature--right';\n\n return `<section class=\"squisq-feature ${sideClass}\">\n${media}\n<div class=\"squisq-feature__body\">\n${textHtml}\n</div>\n</section>`;\n}\n\ninterface FeaturedImage {\n src: string;\n alt: string;\n width?: number;\n height?: number;\n}\n\nfunction renderFeatureImage(img: FeaturedImage, ctx: RenderCtx | undefined): string {\n const resolved = ctx?.images?.get(img.src) ?? img.src;\n const attrs = [`src=\"${escapeAttr(resolved)}\"`, `alt=\"${escapeAttr(img.alt)}\"`];\n // Emit `width` / `height` attributes only when the source HTML had\n // them. The CSS rules then know to honor those values rather than\n // stretching the image to fill the column.\n if (typeof img.width === 'number') attrs.push(`width=\"${img.width}\"`);\n if (typeof img.height === 'number') attrs.push(`height=\"${img.height}\"`);\n const sizedClass =\n typeof img.width === 'number' || typeof img.height === 'number'\n ? ' squisq-feature__media--sized'\n : '';\n return `<div class=\"squisq-feature__media${sizedClass}\"><img ${attrs.join(' ')} /></div>`;\n}\n\n/**\n * Pull the first image reference out of a section's body — either a\n * markdown `image` node (possibly nested inside a paragraph) or a raw\n * HTML `<img>` (the WYSIWYG editor emits these for resized images).\n * Returns the image plus the body with that image removed (so it's not\n * rendered a second time inside the text column).\n */\nfunction takeFirstImage(nodes: MarkdownNode[]): {\n image: FeaturedImage | null;\n remaining: MarkdownNode[];\n} {\n for (let i = 0; i < nodes.length; i++) {\n const found = extractFirstImageFromBlock(nodes[i]);\n if (!found) continue;\n const remaining = [...nodes];\n if (found.replacement === null) {\n remaining.splice(i, 1);\n } else {\n remaining[i] = found.replacement;\n }\n return { image: found.image, remaining };\n }\n return { image: null, remaining: nodes };\n}\n\n/**\n * Look for the first image inside a single block node. If the block is\n * a paragraph that contains only the image (with optional whitespace),\n * we drop the whole paragraph; if there's surrounding text, we strip\n * the image from the paragraph's inline children and keep the rest.\n * For raw `<img>` html blocks we drop the block entirely.\n */\nfunction extractFirstImageFromBlock(\n block: MarkdownNode,\n): { image: FeaturedImage; replacement: MarkdownNode | null } | null {\n if (!block || typeof block !== 'object') return null;\n const b = block as unknown as Record<string, unknown>;\n if (b.type === 'paragraph' && Array.isArray(b.children)) {\n const kids = b.children as MarkdownNode[];\n const imgIdx = kids.findIndex(\n (k) =>\n (k as { type?: string }).type === 'image' &&\n typeof (k as { url?: unknown }).url === 'string',\n );\n if (imgIdx >= 0) {\n const img = kids[imgIdx] as { url: string; alt?: string };\n const remainingKids = [...kids.slice(0, imgIdx), ...kids.slice(imgIdx + 1)].filter(\n (k) => !isBlankInline(k),\n );\n const replacement =\n remainingKids.length === 0\n ? null\n : ({ ...(b as object), children: remainingKids } as MarkdownNode);\n return {\n image: { src: img.url, alt: img.alt ?? '' },\n replacement,\n };\n }\n }\n if (b.type === 'htmlBlock' && Array.isArray(b.htmlChildren)) {\n const hit = findHtmlImg(b.htmlChildren as HtmlNode[]);\n if (hit) return { image: hit, replacement: null };\n }\n return null;\n}\n\nfunction isBlankInline(node: MarkdownNode): boolean {\n if (!node || typeof node !== 'object') return false;\n const n = node as { type?: string; value?: unknown };\n return n.type === 'text' && typeof n.value === 'string' && n.value.trim().length === 0;\n}\n\nfunction findHtmlImg(nodes: HtmlNode[]): FeaturedImage | null {\n for (const n of nodes) {\n if (n.type !== 'htmlElement') continue;\n if (n.tagName.toLowerCase() === 'img') {\n const src = n.attributes.src;\n if (typeof src === 'string' && src) {\n return {\n src,\n alt: typeof n.attributes.alt === 'string' ? n.attributes.alt : '',\n width: parseHtmlDim(n.attributes.width),\n height: parseHtmlDim(n.attributes.height),\n };\n }\n }\n const nested = findHtmlImg(n.children);\n if (nested) return nested;\n }\n return null;\n}\n\nfunction parseHtmlDim(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = parseFloat(raw);\n return Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\nconst FEATURE_CSS = ` .squisq-feature {\n display: flex;\n flex-wrap: wrap;\n gap: 1.5em;\n align-items: center;\n margin: 1.75em 0;\n }\n .squisq-feature--right { flex-direction: row-reverse; }\n .squisq-feature__media {\n flex: 0 0 42%;\n min-width: 0;\n }\n .squisq-feature__media--empty { display: none; }\n /* Default: image fills the media column. */\n .squisq-feature__media img {\n width: 100%;\n height: auto;\n display: block;\n border-radius: 6px;\n }\n /* \"Sized\" media: the image carried explicit width/height attrs (the\n WYSIWYG editor wrote them after a resize). Honor the attribute\n values and center the image inside the media column with padding. */\n .squisq-feature__media--sized {\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 1em;\n box-sizing: border-box;\n }\n /* Leave width and height untouched here -- the HTML attributes set\n the intrinsic dimensions, and CSS overrides would silently discard\n the author's sizing. max-width: 100% still keeps the image from\n overflowing the column on narrow viewports; HTML5 derives the\n aspect ratio from the width/height pair so the scale stays right. */\n .squisq-feature__media--sized img {\n max-width: 100%;\n display: block;\n border-radius: 6px;\n }\n .squisq-feature__body {\n flex: 1 1 0;\n min-width: 0;\n }\n .squisq-feature__body > :first-child { margin-top: 0; }\n .squisq-feature__body > :last-child { margin-bottom: 0; }\n @media (max-width: 600px) {\n .squisq-feature, .squisq-feature--right { flex-direction: column; }\n .squisq-feature__media { flex-basis: auto; width: 100%; }\n }`;\n\n// ── Theme-driven CSS ───────────────────────────────────────────────\n\nconst DEFAULT_CSS = ` body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 2em auto; padding: 0 1em; line-height: 1.6; color: #1f2937; }\n h1, h2, h3, h4, h5, h6 { margin-top: 1.5em; margin-bottom: 0.5em; }\n pre { background: #f3f4f6; padding: 1em; border-radius: 4px; overflow-x: auto; }\n code { background: #f3f4f6; padding: 0.15em 0.3em; border-radius: 3px; font-size: 0.9em; }\n pre code { background: none; padding: 0; }\n blockquote { border-left: 3px solid #d1d5db; margin-left: 0; padding-left: 1em; color: #6b7280; }\n /* Images: cap at the container width so nothing overflows, but only\n force aspect-ratio height when the author didn't set explicit\n dimensions on the <img> tag. The WYSIWYG editor writes width/height\n attributes after a resize — overriding them here would silently\n ignore the user's sizing. */\n img { max-width: 100%; }\n img:not([width]):not([height]) { height: auto; }\n a { color: #3b82f6; }\n table { border-collapse: collapse; width: 100%; margin: 1em 0; }\n th, td { border: 1px solid #d1d5db; padding: 6px 10px; text-align: left; }\n th { background: #f3f4f6; font-weight: 600; }\n hr { border: none; border-top: 1px solid #d1d5db; margin: 1.5em 0; }`;\n\n/**\n * Build the stylesheet for a themed page. We resolve fonts and colors\n * to CSS-ready strings up front (rather than emitting `--squisq-*`\n * custom properties everywhere) so the output works in environments\n * that strip CSS variables.\n */\nfunction renderThemedCss(theme: Theme): string {\n const bodyFamily = resolveFontFamily(theme.typography.bodyFont, 'system-ui, sans-serif');\n const titleFamily = resolveFontFamily(theme.typography.titleFont, 'Georgia, serif');\n const monoFamily = resolveFontFamily(theme.typography.monoFont, 'Consolas, monospace');\n const lineHeight = theme.typography.lineHeight ?? 1.6;\n const titleLineHeight = theme.typography.titleLineHeight ?? 1.25;\n const titleWeight = theme.typography.titleWeight === 'normal' ? 400 : 700;\n const c = theme.colors;\n // A few derived colors so the page doesn't end up unreadable on\n // themes that swing dark (most code/table chrome reads as \"dim panel\n // on background\"). We do this in CSS, not in JS, by mixing with\n // `color-mix` so older browsers without it still get a sensible look.\n return ` :root {\n --plain-bg: ${c.background};\n --plain-text: ${c.text};\n --plain-muted: ${c.textMuted};\n --plain-primary: ${c.primary};\n --plain-secondary: ${c.secondary};\n --plain-accent: ${c.highlight};\n --plain-bg-light: ${c.backgroundLight};\n --plain-body-font: ${bodyFamily};\n --plain-title-font: ${titleFamily};\n --plain-mono-font: ${monoFamily};\n }\n body {\n font-family: var(--plain-body-font);\n max-width: 800px;\n margin: 2em auto;\n padding: 0 1em;\n line-height: ${lineHeight};\n color: var(--plain-text);\n background: var(--plain-bg);\n }\n h1, h2, h3, h4, h5, h6 {\n font-family: var(--plain-title-font);\n color: var(--plain-text);\n margin-top: 1.5em;\n margin-bottom: 0.5em;\n line-height: ${titleLineHeight};\n font-weight: ${titleWeight};\n }\n p { margin: 0.75em 0; }\n pre {\n background: var(--plain-bg-light);\n padding: 1em;\n border-radius: 4px;\n overflow-x: auto;\n font-family: var(--plain-mono-font);\n }\n code {\n background: var(--plain-bg-light);\n padding: 0.15em 0.3em;\n border-radius: 3px;\n font-size: 0.9em;\n font-family: var(--plain-mono-font);\n }\n pre code { background: none; padding: 0; }\n blockquote {\n border-left: 3px solid var(--plain-primary);\n margin-left: 0;\n padding-left: 1em;\n color: var(--plain-muted);\n }\n /* See DEFAULT_CSS comment: only auto-scale height when the author\n didn't set explicit width/height attributes. */\n img { max-width: 100%; }\n img:not([width]):not([height]) { height: auto; }\n /* Blend the theme primary toward the body text color so links stay\n theme-flavored but read clearly on every theme's background — some\n themes (e.g. Gezellig) pick a mid-tone primary that's almost\n invisible on a dark page when used neat. Underline makes the link\n unambiguous independent of the color contrast. */\n a {\n color: color-mix(in srgb, var(--plain-primary) 65%, var(--plain-text));\n text-decoration: underline;\n text-decoration-thickness: 1px;\n text-underline-offset: 2px;\n }\n a:hover { color: var(--plain-accent); }\n table { border-collapse: collapse; width: 100%; margin: 1em 0; }\n th, td {\n border: 1px solid color-mix(in srgb, var(--plain-muted) 30%, transparent);\n padding: 6px 10px;\n text-align: left;\n }\n th {\n background: var(--plain-bg-light);\n color: var(--plain-text);\n font-family: var(--plain-title-font);\n font-weight: 600;\n }\n hr {\n border: none;\n border-top: 1px solid color-mix(in srgb, var(--plain-muted) 40%, transparent);\n margin: 1.5em 0;\n }`;\n}\n\n/**\n * Emit the `<link rel=\"stylesheet\">` line(s) needed to load the theme's\n * fonts. Empty string when nothing in the theme is hosted on Google\n * Fonts (system stacks, custom self-hosted faces).\n */\nfunction renderFontsLink(theme: Theme): string {\n const url = buildGoogleFontsUrl([\n theme.typography.bodyFont,\n theme.typography.titleFont,\n theme.typography.monoFont,\n ]);\n if (!url) return '';\n // Preconnect to Google's CDN to shave a roundtrip off the font load.\n return `<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n<link rel=\"stylesheet\" href=\"${escapeAttr(url)}\">\n`;\n}\n\n// ── Node → HTML ────────────────────────────────────────────────────\n\nfunction nodeToHtml(node: MarkdownNode | undefined | null, ctx?: RenderCtx): string {\n if (!node) return '';\n switch (node.type) {\n case 'heading': {\n const depth = Math.min(Math.max(node.depth ?? 1, 1), 6);\n return `<h${depth}>${childrenToHtml(node, ctx)}</h${depth}>`;\n }\n case 'paragraph':\n return `<p>${childrenToHtml(node, ctx)}</p>`;\n case 'text':\n return escapeHtml(node.value ?? '');\n case 'strong':\n return `<strong>${childrenToHtml(node, ctx)}</strong>`;\n case 'emphasis':\n return `<em>${childrenToHtml(node, ctx)}</em>`;\n case 'delete':\n return `<del>${childrenToHtml(node, ctx)}</del>`;\n case 'inlineCode':\n return `<code>${escapeHtml(node.value ?? '')}</code>`;\n case 'code': {\n const lang = node.lang ? ` class=\"language-${escapeAttr(node.lang)}\"` : '';\n return `<pre><code${lang}>${escapeHtml(node.value ?? '')}</code></pre>`;\n }\n case 'blockquote':\n return `<blockquote>${childrenToHtml(node, ctx)}</blockquote>`;\n case 'list': {\n const tag = node.ordered ? 'ol' : 'ul';\n const start =\n node.ordered && typeof node.start === 'number' && node.start !== 1\n ? ` start=\"${node.start}\"`\n : '';\n return `<${tag}${start}>${childrenToHtml(node, ctx)}</${tag}>`;\n }\n case 'listItem':\n return `<li>${childrenToHtml(node, ctx)}</li>`;\n case 'link': {\n const original = node.url ?? '';\n const rewritten = ctx?.links?.get(original) ?? original;\n return `<a href=\"${escapeAttr(rewritten)}\">${childrenToHtml(node, ctx)}</a>`;\n }\n case 'image': {\n const original = node.url ?? '';\n const resolved = ctx?.images?.get(original) ?? original;\n return `<img src=\"${escapeAttr(resolved)}\" alt=\"${escapeAttr(node.alt ?? '')}\" />`;\n }\n case 'thematicBreak':\n return '<hr />';\n case 'table':\n return tableToHtml(node, ctx);\n case 'inlineIcon': {\n // Render via FontAwesome's `fa-<family> fa-<name>` class pair.\n // The `<link>` to the FA CSS is injected into <head> by\n // `markdownDocToPlainHtml` when the doc contains any icon.\n const family = escapeAttr(node.family ?? 'solid');\n const name = escapeAttr(node.name ?? '');\n const token = escapeAttr(node.token ?? `${node.family}:${node.name}`);\n return `<i class=\"fa-${family} fa-${name}\" data-icon=\"${token}\" aria-hidden=\"true\"></i>`;\n }\n case 'htmlBlock':\n case 'htmlInline':\n // Resized images and other authored HTML survive the round-trip\n // as parsed `htmlChildren` — rewriting `<img src>` through the\n // image map keeps the preview consistent with the markdown-image\n // path. Other tags pass through unmodified.\n return htmlChildrenToHtml(node.htmlChildren, ctx);\n default: {\n // Unknown / unhandled node — recurse into children if any so we\n // don't drop content (e.g. directives, footnotes).\n const withChildren = node as { children?: unknown; value?: unknown };\n if (Array.isArray(withChildren.children)) {\n return childrenToHtml(node as { children: MarkdownNode[] }, ctx);\n }\n if (typeof withChildren.value === 'string') {\n return escapeHtml(withChildren.value);\n }\n return '';\n }\n }\n}\n\nfunction childrenToHtml(\n node: { children?: MarkdownNode[]; value?: string },\n ctx?: RenderCtx,\n): string {\n if (!node.children) return node.value ? escapeHtml(node.value) : '';\n return node.children.map((child) => nodeToHtml(child, ctx)).join('');\n}\n\nfunction tableToHtml(\n node: { children: { children: { children: MarkdownNode[]; isHeader?: boolean }[] }[] },\n ctx?: RenderCtx,\n): string {\n const [headerRow, ...bodyRows] = node.children;\n const parts: string[] = ['<table>'];\n if (headerRow) {\n parts.push('<thead><tr>');\n for (const cell of headerRow.children) {\n parts.push(`<th>${childrenToHtml(cell, ctx)}</th>`);\n }\n parts.push('</tr></thead>');\n }\n if (bodyRows.length > 0) {\n parts.push('<tbody>');\n for (const row of bodyRows) {\n parts.push('<tr>');\n for (const cell of row.children) {\n parts.push(`<td>${childrenToHtml(cell, ctx)}</td>`);\n }\n parts.push('</tr>');\n }\n parts.push('</tbody>');\n }\n parts.push('</table>');\n return parts.join('');\n}\n\nfunction htmlChildrenToHtml(nodes: HtmlNode[] | undefined, ctx?: RenderCtx): string {\n if (!nodes || nodes.length === 0) return '';\n const out: string[] = [];\n for (const node of nodes) {\n if (node.type === 'htmlText') {\n // HtmlText already represents authored HTML — emit verbatim so\n // entity references the user wrote (e.g. `&amp;`) survive.\n out.push(node.value);\n continue;\n }\n if (node.type === 'htmlComment') {\n out.push(`<!--${node.value}-->`);\n continue;\n }\n // htmlElement\n const tag = node.tagName.toLowerCase();\n const attrs = { ...node.attributes };\n // Route media `src` attrs through the export's `ctx.images` URL\n // map (which is actually a generic media map — see header comment).\n // Without this, raw <video>/<audio> tags inserted by the recorder\n // ship as relative paths that resolve against the export host, not\n // the original ContentContainer.\n if (\n (tag === 'img' || tag === 'video' || tag === 'audio' || tag === 'source') &&\n typeof attrs.src === 'string'\n ) {\n attrs.src = ctx?.images?.get(attrs.src) ?? attrs.src;\n }\n if ((tag === 'video' || tag === 'audio') && typeof attrs.poster === 'string') {\n attrs.poster = ctx?.images?.get(attrs.poster) ?? attrs.poster;\n }\n const attrStr = Object.entries(attrs)\n .map(([k, v]) => ` ${k}=\"${escapeAttr(v)}\"`)\n .join('');\n if (node.selfClosing) {\n out.push(`<${tag}${attrStr} />`);\n } else {\n out.push(`<${tag}${attrStr}>${htmlChildrenToHtml(node.children, ctx)}</${tag}>`);\n }\n }\n return out.join('');\n}\n\n// ── Escaping ───────────────────────────────────────────────────────\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nfunction escapeAttr(s: string): string {\n return escapeHtml(s).replace(/\"/g, '&quot;');\n}\n","/**\n * Recursive plain-HTML bundle export.\n *\n * `markdownDocsToPlainHtmlBundle` starts from a single entry markdown\n * file, walks its relative `[…](other.md)` links, recursively pulls in\n * any sibling/child documents (scope-limited to the entry doc's\n * directory tree), renders every visited file via\n * `markdownDocToPlainHtml`, rewrites cross-doc references from `.md`\n * to `.html`, and ships everything as a single ZIP.\n *\n * The function is provider-agnostic — callers pass `readDocument` and\n * `readBinary` callbacks that resolve relative paths against whatever\n * storage they use (`FileSystemContentContainer`, `MemoryContent-\n * Container`, in-memory map for tests, …). Failure to read any\n * discovered file aborts the whole export with a thrown error.\n */\n\nimport JSZip from 'jszip';\nimport { parseMarkdown, inferDocumentTitle } from '@bendyline/squisq/markdown';\nimport type { MarkdownDocument, HtmlNode } from '@bendyline/squisq/markdown';\nimport type { Theme } from '@bendyline/squisq/schemas';\nimport { resolveTheme } from '@bendyline/squisq/schemas';\nimport { markdownDocToPlainHtml } from './plainHtml.js';\n\n// ── Public Types ───────────────────────────────────────────────────\n\nexport interface PlainHtmlBundleOptions {\n /** Entry document path relative to the container root (e.g. `'home.md'`). */\n entryPath: string;\n /** Reads a UTF-8 markdown file from the container. Returns null when absent. */\n readDocument: (path: string) => Promise<string | null>;\n /** Reads a binary asset (image) from the container. Returns null when absent. */\n readBinary: (path: string) => Promise<ArrayBuffer | null>;\n /** Optional document title for the entry. Others derive from filename. */\n title?: string;\n /** Optional theme applied uniformly to every page. Overrides {@link themeId}. */\n theme?: Theme;\n /**\n * Optional theme id (e.g. `'warm-earth'`, `'gezellig'`). Resolved via\n * `resolveTheme` and applied to every page. Convenient for callers\n * that track themes by id (like the host export dialog) without\n * having to resolve to a `Theme` object first. When both `theme` and\n * `themeId` are supplied, `theme` wins.\n */\n themeId?: string;\n /** Maximum recursion depth (default: unlimited; cycles always handled). */\n maxDepth?: number;\n /**\n * Emit the entry doc as `index.html` (preserving its parent directory)\n * instead of `<basename>.html`. Cross-doc links pointing at the entry\n * also rewrite to `index.html`, so a sibling `resume.md → home.md`\n * link doesn't 404 after the rename. Convenient for static-site\n * deploys where the landing page must be named `index.html`.\n * Default: false.\n */\n entryAsIndex?: boolean;\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Render an entry markdown document and every reachable sibling/child\n * `.md` document it links to, bundled as a single ZIP with plain-HTML\n * pages, per-document asset folders, and cross-doc `<a href>`\n * references rewritten from `.md` to `.html`.\n */\nexport async function markdownDocsToPlainHtmlBundle(\n options: PlainHtmlBundleOptions,\n): Promise<Blob> {\n const {\n entryPath,\n readDocument,\n readBinary,\n title,\n theme,\n themeId,\n maxDepth = Infinity,\n entryAsIndex = false,\n } = options;\n const resolvedTheme = theme ?? (themeId ? resolveTheme(themeId) : undefined);\n const entry = normalizePath(entryPath);\n if (!entry) {\n throw new Error('markdownDocsToPlainHtmlBundle: entryPath is required');\n }\n const scopeRoot = posixDirname(entry); // '' for root-level files\n // When `entryAsIndex`, the entry doc writes to `<entryDir>/index.html`\n // and every cross-doc link pointing at it rewrites to that path too.\n // Other docs keep the `<basename>.html` convention.\n const entryHtmlPath = entryAsIndex\n ? scopeRoot\n ? `${scopeRoot}/index.html`\n : 'index.html'\n : entry.slice(0, -3) + '.html';\n const htmlPathFor = (mdPath: string): string =>\n mdPath === entry ? entryHtmlPath : mdPath.slice(0, -3) + '.html';\n\n const zip = new JSZip();\n const visited = new Set<string>();\n const queue: Array<{ path: string; depth: number }> = [{ path: entry, depth: 0 }];\n\n while (queue.length > 0) {\n const { path, depth } = queue.shift()!;\n if (visited.has(path)) continue;\n visited.add(path);\n\n const source = await readDocument(path);\n if (source === null) {\n throw new Error(`markdownDocsToPlainHtmlBundle: failed to read \"${path}\"`);\n }\n const mdDoc = parseMarkdown(source);\n\n // Discover this doc's relative .md links — both for enqueueing new\n // targets and for building the per-doc link rewrite map. We resolve\n // each link to a canonical container-relative path so the same doc\n // referenced two different ways (./resume.md vs resume.md) is\n // visited once and rewritten consistently.\n const docDir = posixDirname(path);\n const linkMap = new Map<string, string>();\n for (const raw of collectLinkRefs(mdDoc)) {\n const parsed = parseLinkRef(raw);\n if (!parsed) continue;\n const resolved = resolveRelative(docDir, parsed.path);\n if (resolved === null) continue; // escaped via ..\n if (!isInScope(resolved, scopeRoot)) continue;\n if (!resolved.toLowerCase().endsWith('.md')) continue;\n\n // Compute the .html replacement relative to the current doc so\n // the rewritten href stays local (e.g. `subdir/notes.html`, not\n // an absolute container path). `htmlPathFor` also handles the\n // entry-as-index case so a sibling linking to the entry lands\n // on `index.html` after rename.\n const htmlTarget = htmlPathFor(resolved);\n const relHref = relativeFrom(docDir, htmlTarget) + parsed.fragment;\n linkMap.set(raw, relHref);\n\n if (depth + 1 <= maxDepth && !visited.has(resolved)) {\n queue.push({ path: resolved, depth: depth + 1 });\n }\n }\n\n // Walk images, fetch each one, write at the original relative path\n // resolved against the container root (so `resume_files/hero.png`\n // sits next to `resume.html` in the zip). Failures here are *not*\n // fatal — images can be missing without breaking the document\n // structure — but we surface them as console warnings.\n const images = await readImagesForDoc(mdDoc, docDir, readBinary);\n for (const [, { data, zipPath }] of images) {\n const safe = sanitizeZipPath(zipPath);\n if (!safe) continue;\n zip.file(safe, data);\n }\n\n // Render the document. The image rewrite map keys are the URLs\n // exactly as authored (so `markdownDocToPlainHtml` can match them\n // verbatim), and the values are paths relative to the rendered\n // doc's own location — so `<img src>` works after unzip without\n // any post-processing.\n const imageRewriteMap = new Map<string, string>();\n for (const [authored, { zipPath }] of images) {\n imageRewriteMap.set(authored, relativeFrom(docDir, zipPath));\n }\n\n const docTitle = depth === 0 ? title : undefined;\n const html = markdownDocToPlainHtml(mdDoc, {\n title: docTitle ?? titleForFilename(path, mdDoc),\n images: imageRewriteMap,\n links: linkMap,\n theme: resolvedTheme,\n });\n\n const htmlPath = htmlPathFor(path);\n zip.file(htmlPath, html);\n }\n\n return zip.generateAsync({\n type: 'blob',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n });\n}\n\n// ── Link discovery ─────────────────────────────────────────────────\n\n/**\n * Collect every `<a>`-style link URL referenced in a document. Markdown\n * `link` nodes plus any raw HTML `<a href>` tags. Returns the raw URLs\n * as authored, so callers can use them as both the linkMap *key* and\n * the basis for resolution.\n */\nexport function collectLinkRefs(doc: MarkdownDocument): Set<string> {\n const refs = new Set<string>();\n\n function visitHtml(nodes: HtmlNode[]): void {\n for (const n of nodes) {\n if (n.type !== 'htmlElement') continue;\n if (n.tagName.toLowerCase() === 'a') {\n const href = n.attributes.href;\n if (typeof href === 'string' && href) refs.add(href);\n }\n visitHtml(n.children);\n }\n }\n\n function visit(node: unknown): void {\n if (!node || typeof node !== 'object') return;\n const n = node as Record<string, unknown>;\n if (n.type === 'link' && typeof n.url === 'string' && n.url) {\n refs.add(n.url);\n }\n if ((n.type === 'htmlBlock' || n.type === 'htmlInline') && Array.isArray(n.htmlChildren)) {\n visitHtml(n.htmlChildren as HtmlNode[]);\n }\n if (Array.isArray(n.children)) {\n for (const child of n.children) visit(child);\n }\n }\n\n for (const child of doc.children) visit(child);\n return refs;\n}\n\nfunction collectImageRefs(doc: MarkdownDocument): Set<string> {\n const refs = new Set<string>();\n function visitHtml(nodes: HtmlNode[]): void {\n for (const n of nodes) {\n if (n.type !== 'htmlElement') continue;\n const tag = n.tagName.toLowerCase();\n // <img>/<video>/<audio>/<source> all reference media via `src`;\n // we feed them into the same `images` map (effectively a generic\n // media map — see header comment) so the export pipeline rewrites\n // and bundles each one the same way.\n if (tag === 'img' || tag === 'video' || tag === 'audio' || tag === 'source') {\n const src = n.attributes.src;\n if (typeof src === 'string' && src) refs.add(src);\n }\n if (tag === 'video' || tag === 'audio') {\n const poster = n.attributes.poster;\n if (typeof poster === 'string' && poster) refs.add(poster);\n }\n visitHtml(n.children);\n }\n }\n function visit(node: unknown): void {\n if (!node || typeof node !== 'object') return;\n const n = node as Record<string, unknown>;\n if (n.type === 'image' && typeof n.url === 'string' && n.url) refs.add(n.url);\n if ((n.type === 'htmlBlock' || n.type === 'htmlInline') && Array.isArray(n.htmlChildren)) {\n visitHtml(n.htmlChildren as HtmlNode[]);\n }\n if (Array.isArray(n.children)) for (const c of n.children) visit(c);\n }\n for (const child of doc.children) visit(child);\n return refs;\n}\n\ninterface ParsedLinkRef {\n /** Pathname portion before any `#` or `?`. */\n path: string;\n /** `#fragment` suffix (with leading `#`) or empty string. */\n fragment: string;\n}\n\n/**\n * Split an authored URL into path + fragment, returning null for\n * external / non-document references (http(s), mailto, data, blob,\n * absolute paths, fragment-only). The fragment is preserved so a\n * link like `resume.md#experience` rewrites cleanly to\n * `resume.html#experience`.\n */\nfunction parseLinkRef(url: string): ParsedLinkRef | null {\n if (!url) return null;\n if (url.startsWith('#')) return null; // intra-doc anchor\n if (\n /^[a-z][a-z0-9+.-]*:/.test(url) || // http:, https:, mailto:, ftp:, …\n url.startsWith('//') ||\n url.startsWith('/')\n ) {\n return null;\n }\n const hashIdx = url.indexOf('#');\n const queryIdx = url.indexOf('?');\n const cut =\n hashIdx >= 0 && queryIdx >= 0 ? Math.min(hashIdx, queryIdx) : hashIdx >= 0 ? hashIdx : queryIdx;\n const path = cut >= 0 ? url.slice(0, cut) : url;\n const fragment = hashIdx >= 0 ? url.slice(hashIdx) : '';\n return { path, fragment };\n}\n\n// ── Image gathering ────────────────────────────────────────────────\n\n/**\n * Resolve every image referenced by a document to container-relative\n * paths and fetch their bytes. The returned map keys are the authored\n * URLs (so the renderer's `images` map can substitute them); the values\n * are tuples of `[bytes, zipPath]` where `zipPath` is the path used\n * inside the zip.\n *\n * Images that can't be read are silently dropped — the rendered HTML\n * will keep its `<img src>` pointing at the authored URL, which a\n * reader's browser will 404. That matches the user-facing \"abort on\n * missing linked doc\" rule which applies to `.md` links only.\n */\nasync function readImagesForDoc(\n mdDoc: MarkdownDocument,\n docDir: string,\n readBinary: (path: string) => Promise<ArrayBuffer | null>,\n): Promise<Map<string, { data: ArrayBuffer; zipPath: string }>> {\n const out = new Map<string, { data: ArrayBuffer; zipPath: string }>();\n for (const authored of collectImageRefs(mdDoc)) {\n if (/^[a-z][a-z0-9+.-]*:/.test(authored) || authored.startsWith('//')) continue;\n const cleanAuthored = authored.replace(/[#?].*$/, '');\n const resolved = resolveRelative(docDir, cleanAuthored);\n if (resolved === null) continue;\n const data = await readBinary(resolved);\n if (!data) continue;\n out.set(authored, { data, zipPath: resolved });\n }\n return out;\n}\n\n// ── Path helpers (POSIX-style, no Node `path`) ─────────────────────\n\n/**\n * Strip a path to its parent directory (POSIX-style). Returns `''`\n * for root-level files so subsequent joins read like a fresh path.\n */\nexport function posixDirname(p: string): string {\n const idx = p.lastIndexOf('/');\n return idx < 0 ? '' : p.slice(0, idx);\n}\n\n/**\n * Normalize a POSIX path: collapse `./`, resolve `..`, drop trailing\n * slashes, never produce a leading `/`. Returns null when the path\n * escapes the start (\"..\").\n */\nexport function normalizePath(p: string): string | null {\n const parts = p.split('/');\n const out: string[] = [];\n for (const segment of parts) {\n if (segment === '' || segment === '.') continue;\n if (segment === '..') {\n if (out.length === 0) return null;\n out.pop();\n continue;\n }\n out.push(segment);\n }\n return out.join('/');\n}\n\n/**\n * Resolve `rel` against `baseDir`. Returns null when the result\n * escapes the container root via `..`.\n */\nexport function resolveRelative(baseDir: string, rel: string): string | null {\n if (rel.startsWith('/')) return null; // absolute paths are out of scope\n const joined = baseDir ? `${baseDir}/${rel}` : rel;\n return normalizePath(joined);\n}\n\n/**\n * True when `target` is inside `root` (or equal to it). Empty root\n * means \"entire container is in scope\".\n */\nexport function isInScope(target: string, root: string): boolean {\n if (!root) return true;\n return target === root || target.startsWith(root + '/');\n}\n\n/**\n * Compute a relative path from `fromDir` to `toPath` (both POSIX-\n * normalized, container-relative). Used to emit hrefs that work after\n * unzipping anywhere — `home.md → subfolder/notes.md` becomes\n * `subfolder/notes.html`; `subfolder/intro.md → resume.md` becomes\n * `../resume.html`.\n */\nexport function relativeFrom(fromDir: string, toPath: string): string {\n const fromParts = fromDir ? fromDir.split('/') : [];\n const toParts = toPath.split('/');\n let common = 0;\n while (\n common < fromParts.length &&\n common < toParts.length - 1 &&\n fromParts[common] === toParts[common]\n ) {\n common++;\n }\n const up = fromParts.length - common;\n const down = toParts.slice(common);\n const prefix = Array(up).fill('..').join('/');\n if (!prefix) return down.join('/');\n return `${prefix}/${down.join('/')}`;\n}\n\n/**\n * Sanitize a path for use as a zip entry. Strips leading slashes,\n * normalizes backslashes (Windows-authored paths), and rejects any\n * path containing `..` segments after normalization (defensive — the\n * resolver above already filters those out for links).\n */\nfunction sanitizeZipPath(path: string): string | null {\n const normalized = path.replace(/\\\\/g, '/').replace(/^\\/+/, '');\n if (!normalized) return null;\n if (normalized.split('/').some((seg) => seg === '..')) return null;\n return normalized;\n}\n\n/**\n * Derive a default page title for a non-entry doc: prefer frontmatter\n * `title`, fall back to the shallowest heading text, then the filename\n * without extension.\n */\nfunction titleForFilename(path: string, mdDoc: MarkdownDocument): string {\n const inferred = inferDocumentTitle(mdDoc);\n if (inferred) return inferred;\n const base = path.split('/').pop() ?? path;\n return base.replace(/\\.md$/i, '');\n}\n","/**\n * Recursive rendered-HTML bundle export.\n *\n * `markdownDocsToHtmlBundle` is the rendered-pipeline counterpart of\n * `markdownDocsToPlainHtmlBundle`. Starting from a single entry markdown\n * file, it walks every relative `[…](other.md)` link, builds a Doc for\n * each visited page via `markdownToDoc`, rewrites cross-doc link URLs\n * inside the Doc tree from `.md` → relative `.html`, then renders each\n * Doc to a SquisqPlayer-backed HTML page sharing one `squisq-player.js`.\n * Images preserve their authored relative paths so per-doc folders\n * (`resume_files/hero.png`, etc.) sit beside the rendered HTML.\n *\n * The rewrite happens on the Doc, *before* JSON serialization, because\n * the rendered HTML embeds the Doc as JSON and SquisqPlayer emits the\n * `<a href>` at runtime — there is no post-render link rewrite hook in\n * the player path.\n */\n\nimport JSZip from 'jszip';\nimport { parseMarkdown, inferDocumentTitle } from '@bendyline/squisq/markdown';\nimport type {\n MarkdownDocument,\n MarkdownBlockNode,\n MarkdownInlineNode,\n HtmlNode,\n} from '@bendyline/squisq/markdown';\nimport { markdownToDoc } from '@bendyline/squisq/doc';\nimport type { Block, Doc } from '@bendyline/squisq/schemas';\nimport { generateExternalHtml } from './htmlTemplate.js';\nimport {\n collectLinkRefs,\n isInScope,\n normalizePath,\n posixDirname,\n relativeFrom,\n resolveRelative,\n} from './plainHtmlBundle.js';\n\n// ── Public Types ───────────────────────────────────────────────────\n\nexport interface HtmlBundleOptions {\n /** Entry document path relative to the container root (e.g. `'home.md'`). */\n entryPath: string;\n /** Reads a UTF-8 markdown file from the container. Returns null when absent. */\n readDocument: (path: string) => Promise<string | null>;\n /** Reads a binary asset (image) from the container. Returns null when absent. */\n readBinary: (path: string) => Promise<ArrayBuffer | null>;\n /** SquisqPlayer IIFE bundle. Written once as `squisq-player.js` in the zip. */\n playerScript: string;\n /** Optional document title for the entry. Other pages derive from filename. */\n title?: string;\n /** Theme id applied uniformly to every page. */\n themeId?: string;\n /** Rendering mode for every page (default: 'static' — scrollable, link-friendly). */\n mode?: 'slideshow' | 'static';\n /** Maximum recursion depth (default: unlimited; cycles always handled). */\n maxDepth?: number;\n /**\n * Emit the entry doc as `index.html` (preserving its parent directory)\n * instead of `<basename>.html`. Cross-doc links pointing at the entry\n * also rewrite to `index.html`, so a sibling `resume.md → home.md`\n * link doesn't 404 after the rename. Convenient for static-site\n * deploys where the landing page must be named `index.html`.\n * Default: false.\n */\n entryAsIndex?: boolean;\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Render an entry markdown document and every reachable sibling/child\n * `.md` document it links to, bundled as a single ZIP with one rendered\n * HTML page per doc, per-document asset folders, a shared\n * `squisq-player.js`, and cross-doc `<a href>` references rewritten\n * from `.md` to `.html` inside each Doc's serialized AST.\n */\nexport async function markdownDocsToHtmlBundle(options: HtmlBundleOptions): Promise<Blob> {\n const {\n entryPath,\n readDocument,\n readBinary,\n playerScript,\n title,\n themeId,\n mode = 'static',\n maxDepth = Infinity,\n entryAsIndex = false,\n } = options;\n\n const entry = normalizePath(entryPath);\n if (!entry) {\n throw new Error('markdownDocsToHtmlBundle: entryPath is required');\n }\n const scopeRoot = posixDirname(entry);\n // When `entryAsIndex`, the entry doc writes to `<entryDir>/index.html`\n // and every cross-doc link pointing at it rewrites to that path too.\n // Other docs keep the `<basename>.html` convention.\n const entryHtmlPath = entryAsIndex\n ? scopeRoot\n ? `${scopeRoot}/index.html`\n : 'index.html'\n : entry.slice(0, -3) + '.html';\n const htmlPathFor = (mdPath: string): string =>\n mdPath === entry ? entryHtmlPath : mdPath.slice(0, -3) + '.html';\n\n const zip = new JSZip();\n zip.file('squisq-player.js', playerScript);\n\n const visited = new Set<string>();\n const queue: Array<{ path: string; depth: number }> = [{ path: entry, depth: 0 }];\n\n while (queue.length > 0) {\n const { path, depth } = queue.shift()!;\n if (visited.has(path)) continue;\n visited.add(path);\n\n const source = await readDocument(path);\n if (source === null) {\n throw new Error(`markdownDocsToHtmlBundle: failed to read \"${path}\"`);\n }\n const mdDoc = parseMarkdown(source);\n\n const docDir = posixDirname(path);\n const linkMap = new Map<string, string>();\n for (const raw of collectLinkRefs(mdDoc)) {\n const parsed = parseInternalRef(raw);\n if (!parsed) continue;\n const resolved = resolveRelative(docDir, parsed.path);\n if (resolved === null) continue;\n if (!isInScope(resolved, scopeRoot)) continue;\n if (!resolved.toLowerCase().endsWith('.md')) continue;\n\n const htmlTarget = htmlPathFor(resolved);\n const relHref = relativeFrom(docDir, htmlTarget) + parsed.fragment;\n linkMap.set(raw, relHref);\n\n if (depth + 1 <= maxDepth && !visited.has(resolved)) {\n queue.push({ path: resolved, depth: depth + 1 });\n }\n }\n\n // Gather and stash images per doc. Same convention as the plain\n // bundle: keep authored relative paths so `<img src>` paths inside\n // the Doc still resolve after unzip. Missing assets are non-fatal.\n const imageRewriteMap = new Map<string, string>();\n for (const authored of collectImageRefs(mdDoc)) {\n if (/^[a-z][a-z0-9+.-]*:/i.test(authored) || authored.startsWith('//')) continue;\n const clean = authored.replace(/[#?].*$/, '');\n const resolvedImg = resolveRelative(docDir, clean);\n if (resolvedImg === null) continue;\n const data = await readBinary(resolvedImg);\n if (!data) continue;\n const safe = sanitizeZipPath(resolvedImg);\n if (!safe) continue;\n zip.file(safe, data);\n imageRewriteMap.set(authored, relativeFrom(docDir, resolvedImg));\n }\n\n // markdownToDoc embeds the markdown AST in `block.contents`, so the\n // link rewrite must walk that tree on every Doc before we serialize\n // it into the rendered HTML.\n let doc = markdownToDoc(mdDoc);\n if (themeId) doc = { ...doc, themeId };\n if (linkMap.size > 0) {\n doc = rewriteDocLinks(doc, linkMap);\n }\n\n const pageTitle = depth === 0 ? (title ?? titleForDoc(path, mdDoc)) : titleForDoc(path, mdDoc);\n const htmlPath = htmlPathFor(path);\n const playerScriptPath = relativeFrom(docDir, 'squisq-player.js');\n\n const html = generateExternalHtml(doc, {\n playerScriptPath,\n // Convert Map → plain record for the template (which expects a\n // record). The renderer reads this map at runtime to swap image\n // sources before rendering each block.\n imagePathMap:\n imageRewriteMap.size > 0 ? Object.fromEntries(imageRewriteMap.entries()) : undefined,\n mode,\n title: pageTitle,\n });\n zip.file(htmlPath, html);\n }\n\n return zip.generateAsync({\n type: 'blob',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n });\n}\n\n// ── Link rewriting ─────────────────────────────────────────────────\n\n/**\n * Return a deep-cloned Doc with every `[text](url)` link URL inside\n * `block.contents` rewritten through `linkMap`, including raw HTML\n * `<a href=\"…\">` tags carried inside `htmlBlock`/`htmlInline` nodes.\n * Authoring keys that aren't in the map pass through untouched.\n */\nfunction rewriteDocLinks(doc: Doc, linkMap: Map<string, string>): Doc {\n if (linkMap.size === 0) return doc;\n\n function rewriteHtmlNodes(nodes: HtmlNode[]): HtmlNode[] {\n return nodes.map((n) => {\n if (n.type !== 'htmlElement') return n;\n const tag = n.tagName.toLowerCase();\n const nextAttrs =\n tag === 'a' && typeof n.attributes.href === 'string' && linkMap.has(n.attributes.href)\n ? { ...n.attributes, href: linkMap.get(n.attributes.href)! }\n : n.attributes;\n return {\n ...n,\n attributes: nextAttrs,\n children: rewriteHtmlNodes(n.children),\n };\n });\n }\n\n function rewriteInline(node: MarkdownInlineNode): MarkdownInlineNode {\n if (node.type === 'link') {\n const nextUrl = linkMap.get(node.url) ?? node.url;\n return {\n ...node,\n url: nextUrl,\n children: node.children.map(rewriteInline),\n };\n }\n if (node.type === 'htmlInline') {\n const withChildren = node as MarkdownInlineNode & { htmlChildren?: HtmlNode[] };\n if (Array.isArray(withChildren.htmlChildren)) {\n return {\n ...node,\n htmlChildren: rewriteHtmlNodes(withChildren.htmlChildren),\n } as MarkdownInlineNode;\n }\n return node;\n }\n if ('children' in node && Array.isArray((node as { children?: unknown }).children)) {\n const children = (node as { children: MarkdownInlineNode[] }).children.map(rewriteInline);\n return { ...node, children } as MarkdownInlineNode;\n }\n return node;\n }\n\n function rewriteBlockNode(node: MarkdownBlockNode): MarkdownBlockNode {\n if (node.type === 'htmlBlock') {\n const withChildren = node as MarkdownBlockNode & { htmlChildren?: HtmlNode[] };\n if (Array.isArray(withChildren.htmlChildren)) {\n return {\n ...node,\n htmlChildren: rewriteHtmlNodes(withChildren.htmlChildren),\n } as MarkdownBlockNode;\n }\n return node;\n }\n if ('children' in node && Array.isArray((node as { children?: unknown }).children)) {\n const rewritten = (node as { children: unknown[] }).children.map((c) => {\n const child = c as { type?: string };\n if (child && typeof child === 'object' && 'type' in child) {\n if (isBlockNodeType(child.type as string)) {\n return rewriteBlockNode(c as MarkdownBlockNode);\n }\n return rewriteInline(c as MarkdownInlineNode);\n }\n return c;\n });\n return { ...node, children: rewritten } as MarkdownBlockNode;\n }\n return node;\n }\n\n function rewriteBlock(block: Block): Block {\n const next: Block = { ...block };\n if (Array.isArray(block.contents)) {\n next.contents = block.contents.map(rewriteBlockNode);\n }\n if (Array.isArray(block.children)) {\n next.children = block.children.map(rewriteBlock);\n }\n return next;\n }\n\n return {\n ...doc,\n blocks: doc.blocks.map(rewriteBlock),\n };\n}\n\n/** Block-level markdown node `type` discriminator. Inline node types are\n * everything else (text, link, emphasis, strong, image, etc.). Keeps\n * the recursive rewrite from mistakenly applying block logic to inline\n * link descendants. */\nfunction isBlockNodeType(t: string): boolean {\n return (\n t === 'paragraph' ||\n t === 'heading' ||\n t === 'list' ||\n t === 'listItem' ||\n t === 'blockquote' ||\n t === 'code' ||\n t === 'thematicBreak' ||\n t === 'table' ||\n t === 'tableRow' ||\n t === 'tableCell' ||\n t === 'htmlBlock'\n );\n}\n\n// ── Helpers (kept local to avoid widening plainHtmlBundle's API) ───\n\ninterface ParsedRef {\n path: string;\n fragment: string;\n}\n\nfunction parseInternalRef(url: string): ParsedRef | null {\n if (!url) return null;\n if (url.startsWith('#')) return null;\n if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//') || url.startsWith('/')) {\n return null;\n }\n const hashIdx = url.indexOf('#');\n const queryIdx = url.indexOf('?');\n const cut =\n hashIdx >= 0 && queryIdx >= 0 ? Math.min(hashIdx, queryIdx) : hashIdx >= 0 ? hashIdx : queryIdx;\n const path = cut >= 0 ? url.slice(0, cut) : url;\n const fragment = hashIdx >= 0 ? url.slice(hashIdx) : '';\n return { path, fragment };\n}\n\nfunction collectImageRefs(doc: MarkdownDocument): Set<string> {\n const refs = new Set<string>();\n function visitHtml(nodes: HtmlNode[]): void {\n for (const n of nodes) {\n if (n.type !== 'htmlElement') continue;\n if (n.tagName.toLowerCase() === 'img') {\n const src = n.attributes.src;\n if (typeof src === 'string' && src) refs.add(src);\n }\n visitHtml(n.children);\n }\n }\n function visit(node: unknown): void {\n if (!node || typeof node !== 'object') return;\n const n = node as Record<string, unknown>;\n if (n.type === 'image' && typeof n.url === 'string' && n.url) refs.add(n.url);\n if ((n.type === 'htmlBlock' || n.type === 'htmlInline') && Array.isArray(n.htmlChildren)) {\n visitHtml(n.htmlChildren as HtmlNode[]);\n }\n if (Array.isArray(n.children)) for (const c of n.children) visit(c);\n }\n for (const child of doc.children) visit(child);\n return refs;\n}\n\nfunction sanitizeZipPath(path: string): string | null {\n const normalized = path.replace(/\\\\/g, '/').replace(/^\\/+/, '');\n if (!normalized) return null;\n if (normalized.split('/').some((seg) => seg === '..')) return null;\n return normalized;\n}\n\nfunction titleForDoc(path: string, mdDoc: MarkdownDocument): string {\n const inferred = inferDocumentTitle(mdDoc);\n if (inferred) return inferred;\n const base = path.split('/').pop() ?? path;\n return base.replace(/\\.md$/i, '');\n}\n"],"mappings":";;;;;;;AAgCA,OAAOA,YAAW;;;AC0BX,SAAS,kBAAkB,KAAuB;AACvD,QAAM,QAAQ,oBAAI,IAAY;AAE9B,WAAS,cAAc,KAAyB;AAC9C,QACE,CAAC,OACD,IAAI,WAAW,OAAO,KACtB,IAAI,WAAW,OAAO,KACtB,IAAI,WAAW,SAAS,KACxB,IAAI,WAAW,UAAU,GACzB;AACA;AAAA,IACF;AACA,UAAM,IAAI,GAAG;AAAA,EACf;AAEA,WAAS,WAAW,QAA6B;AAC/C,QAAI,CAAC,OAAQ;AACb,eAAW,SAAS,QAAQ;AAC1B,UAAI,MAAM,SAAS,QAAS,eAAc,MAAM,QAAQ,GAAG;AAC3D,UAAI,MAAM,SAAS,SAAS;AAC1B,sBAAc,MAAM,QAAQ,GAAG;AAC/B,sBAAc,MAAM,QAAQ,SAAS;AAAA,MACvC;AACA,UAAI,MAAM,SAAS,MAAO,eAAc,MAAM,QAAQ,SAAS;AAAA,IACjE;AAAA,EACF;AAEA,WAAS,UAAU,OAAc;AAC/B,eAAW,MAAM,MAAM;AACvB,QAAI,MAAM,SAAU,mBAAkB,MAAM,UAAU,aAAa;AACnE,QAAI,MAAM,SAAU,OAAM,SAAS,QAAQ,SAAS;AAAA,EACtD;AAGA,MAAI,OAAO,QAAQ,SAAS;AAG5B,MAAI,IAAI,YAAY,QAAS,eAAc,IAAI,WAAW,OAAO;AAGjE,MAAI,IAAI,kBAAkB;AACxB,eAAW,MAAM,IAAI,iBAAiB,gBAAgB,CAAC,GAAG;AACxD,UAAI,SAAS,MAAM,OAAO,GAAG,QAAQ,SAAU,eAAc,GAAG,GAAG;AAAA,IACrE;AACA,eAAW,MAAM,IAAI,iBAAiB,aAAa,CAAC,GAAG;AACrD,UAAI,SAAS,MAAM,OAAO,GAAG,QAAQ,SAAU,eAAc,GAAG,GAAG;A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K,cAAc,IAAI;AAG3B,SAAO,IAAI,cAAc;AAAA,IACvB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,oBAAoB,EAAE,OAAO,EAAE;AAAA,EACjC,CAAC;AACH;","names":["JSZip","escapeHtml","resolveTheme","resolveTheme","JSZip","parseMarkdown","inferDocumentTitle","JSZip","parseMarkdown","collectImageRefs","sanitizeZipPath","inferDocumentTitle","sanitizeZipPath","JSZip"]}
@@ -8,7 +8,7 @@ import {
8
8
 
9
9
  // src/epub/export.ts
10
10
  import JSZip from "jszip";
11
- import { resolveTheme } from "@bendyline/squisq/schemas";
11
+ import { resolveTheme, resolveFontFamily } from "@bendyline/squisq/schemas";
12
12
  async function markdownDocToEpub(doc, options = {}) {
13
13
  const fmTitle = doc.frontmatter?.title;
14
14
  const fmAuthor = doc.frontmatter?.author;
@@ -529,8 +529,8 @@ function generateStylesheet(themeId) {
529
529
  --epub-bg: ${theme.colors.background};
530
530
  --epub-text: ${theme.colors.text};
531
531
  --epub-primary: ${theme.colors.primary};
532
- --epub-heading-font: ${theme.typography.titleFontFamily};
533
- --epub-body-font: ${theme.typography.bodyFontFamily};`;
532
+ --epub-heading-font: ${resolveFontFamily(theme.typography.titleFont, "serif")};
533
+ --epub-body-font: ${resolveFontFamily(theme.typography.bodyFont, "sans-serif")};`;
534
534
  }
535
535
  return `/* Squisq EPUB Stylesheet */
536
536
  :root {${themeVars}
@@ -644,4 +644,4 @@ export {
644
644
  markdownDocToEpub,
645
645
  docToEpub
646
646
  };
647
- //# sourceMappingURL=chunk-EUQQYBZZ.js.map
647
+ //# sourceMappingURL=chunk-ERZ627GR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/epub/export.ts"],"sourcesContent":["/**\n * EPUB 3 Export\n *\n * Converts a MarkdownDocument (or Doc) to an EPUB 3 file (.epub).\n *\n * An EPUB is a ZIP archive containing XHTML chapter files, images,\n * a package manifest (content.opf), and a navigation document (toc.xhtml).\n * Content is split into chapters at H1/H2 heading boundaries.\n *\n * Uses JSZip for packaging (already a dependency), escapeXml from the\n * OOXML utils, and image utilities from the HTML exporter.\n *\n * @example\n * ```ts\n * import { markdownDocToEpub } from '@bendyline/squisq-formats/epub';\n *\n * const epub = await markdownDocToEpub(markdownDoc, {\n * title: 'My Book',\n * author: 'Jane Doe',\n * });\n * ```\n */\n\nimport JSZip from 'jszip';\nimport type { Doc, AudioSegment } from '@bendyline/squisq/schemas';\nimport { resolveTheme, resolveFontFamily } from '@bendyline/squisq/schemas';\nimport type {\n MarkdownDocument,\n MarkdownBlockNode,\n MarkdownInlineNode,\n MarkdownHeading,\n MarkdownParagraph,\n MarkdownListItem,\n MarkdownTable,\n MarkdownTableRow,\n MarkdownTableCell,\n} from '@bendyline/squisq/markdown';\nimport { escapeXml } from '../ooxml/xmlUtils.js';\nimport { inferMimeType, extractFilename } from '../html/imageUtils.js';\n\n// ── Public API ────────────────────────────────────────────────────\n\nexport interface EpubExportOptions {\n /** Book title (default: 'Untitled') */\n title?: string;\n /** Author name */\n author?: string;\n /** Book description / summary */\n description?: string;\n /** BCP-47 language code (default: 'en') */\n language?: string;\n /** Publisher name */\n publisher?: string;\n /** Squisq theme ID for CSS styling */\n themeId?: string;\n /** Pre-resolved image data keyed by relative path as it appears in the markdown */\n images?: Map<string, ArrayBuffer>;\n /** Cover image data (JPEG or PNG) */\n coverImage?: ArrayBuffer;\n /**\n * Audio narration data keyed by segment src/name.\n * When provided alongside audioSegments, EPUB 3 Media Overlays (SMIL)\n * are generated for synchronized audio playback.\n */\n audio?: Map<string, ArrayBuffer>;\n /**\n * Audio segment metadata (from Doc.audio.segments).\n * Required together with `audio` to generate Media Overlays.\n * Each segment's duration and startTime are used to build SMIL timing.\n */\n audioSegments?: AudioSegment[];\n /** Total document duration in seconds (used for Media Overlay metadata) */\n totalDuration?: number;\n}\n\n/**\n * Convert a MarkdownDocument to an EPUB 3 file.\n *\n * Chapters are split at H1/H2 heading boundaries. All referenced images\n * (provided via `options.images`) are embedded in the archive.\n */\nexport async function markdownDocToEpub(\n doc: MarkdownDocument,\n options: EpubExportOptions = {},\n): Promise<ArrayBuffer> {\n const fmTitle = doc.frontmatter?.title;\n const fmAuthor = doc.frontmatter?.author;\n const title = options.title ?? (typeof fmTitle === 'string' ? fmTitle : 'Untitled');\n const author = options.author ?? (typeof fmAuthor === 'string' ? fmAuthor : '');\n const language = options.language ?? 'en';\n const description = options.description ?? '';\n const publisher = options.publisher ?? '';\n const uuid = crypto.randomUUID();\n\n // Split document into chapters\n const chapters = splitIntoChapters(doc.children);\n\n // Collect images referenced in the document, deduplicating filenames\n const imageEntries = collectDocImages(doc.children);\n const resolvedImages = new Map<string, { data: ArrayBuffer; mime: string; filename: string }>();\n if (options.images) {\n const usedNames = new Set<string>();\n for (const src of imageEntries) {\n const data = options.images.get(src);\n if (data) {\n let filename = extractFilename(src);\n // Deduplicate: if two paths share a basename (e.g. a/hero.png and b/hero.png)\n if (usedNames.has(filename)) {\n const dot = filename.lastIndexOf('.');\n const base = dot > 0 ? filename.slice(0, dot) : filename;\n const ext = dot > 0 ? filename.slice(dot) : '';\n let counter = 2;\n while (usedNames.has(`${base}-${counter}${ext}`)) counter++;\n filename = `${base}-${counter}${ext}`;\n }\n usedNames.add(filename);\n resolvedImages.set(src, { data, mime: inferMimeType(filename), filename });\n }\n }\n }\n\n // Generate theme CSS\n const css = generateStylesheet(options.themeId);\n\n // Build the ZIP\n const zip = new JSZip();\n\n // mimetype must be first entry, stored (not compressed)\n zip.file('mimetype', 'application/epub+zip', { compression: 'STORE' });\n\n // META-INF/container.xml\n zip.file('META-INF/container.xml', CONTAINER_XML);\n\n // OEBPS/styles.css\n zip.file('OEBPS/styles.css', css);\n\n // OEBPS/images/*\n for (const [, img] of resolvedImages) {\n zip.file(`OEBPS/images/${img.filename}`, img.data);\n }\n\n // Cover image — detect PNG vs JPEG from magic bytes.\n // When provided, generates a cover.xhtml page in the spine so e-readers\n // (especially Kindle) display the cover as both thumbnail and first page.\n let coverFilename: string | undefined;\n if (options.coverImage) {\n const bytes = new Uint8Array(options.coverImage);\n const isPng =\n bytes.length >= 4 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47;\n coverFilename = isPng ? 'cover.png' : 'cover.jpg';\n zip.file(`OEBPS/images/${coverFilename}`, options.coverImage);\n\n // Generate cover XHTML page — full-bleed image, no margins\n const coverXhtml = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n<head>\n <meta charset=\"UTF-8\"/>\n <title>Cover</title>\n <style>\n body { margin: 0; padding: 0; text-align: center; }\n img { max-width: 100%; max-height: 100%; }\n </style>\n</head>\n<body>\n <img src=\"../images/${escapeXml(coverFilename)}\" alt=\"Cover\"/>\n</body>\n</html>`;\n zip.file('OEBPS/chapters/cover.xhtml', coverXhtml);\n }\n\n // ── Audio narration ──────────────────────────────────────────────\n const audioMap = options.audio;\n const audioSegments = options.audioSegments;\n const hasAudio = audioMap && audioSegments && audioSegments.length > 0;\n // Per-segment audio file info, indexed by segment index (null if data missing)\n const segmentAudioFiles: ({ filename: string; mime: string } | null)[] = [];\n const allAudioFiles: { filename: string; mime: string }[] = [];\n\n if (hasAudio) {\n for (const seg of audioSegments) {\n const data = audioMap.get(seg.src) ?? audioMap.get(seg.name);\n if (data) {\n const filename = extractFilename(seg.src);\n const finalName = filename.includes('.') ? filename : `${filename}.mp3`;\n zip.file(`OEBPS/audio/${finalName}`, data);\n const info = { filename: finalName, mime: inferMimeType(finalName) };\n segmentAudioFiles.push(info);\n allAudioFiles.push(info);\n } else {\n segmentAudioFiles.push(null);\n }\n }\n }\n\n // Build chapter-to-audio mapping for SMIL overlays\n const chapterAudio: (ChapterAudioInfo | null)[] = [];\n if (hasAudio && allAudioFiles.length > 0) {\n if (chapters.length !== audioSegments.length) {\n console.warn(\n `EPUB: ${chapters.length} chapters but ${audioSegments.length} audio segments — ` +\n `extra chapters will reuse the last segment's audio`,\n );\n }\n for (let i = 0; i < chapters.length; i++) {\n const segIdx = Math.min(i, audioSegments.length - 1);\n const seg = audioSegments[segIdx];\n const audioFile = segmentAudioFiles[segIdx];\n if (audioFile) {\n chapterAudio.push({\n audioFilename: audioFile.filename,\n clipStart: 0,\n clipEnd: seg.duration,\n duration: seg.duration,\n });\n } else {\n chapterAudio.push(null);\n }\n }\n }\n\n // OEBPS/chapters/*.xhtml + optional SMIL overlays\n const chapterFiles: ChapterFileInfo[] = [];\n for (let i = 0; i < chapters.length; i++) {\n const chap = chapters[i];\n const num = String(i + 1).padStart(3, '0');\n const id = `chapter-${num}`;\n const filename = `${id}.xhtml`;\n const audioInfo = chapterAudio[i] ?? null;\n\n // Render XHTML with element IDs for SMIL references when audio is present\n const xhtml = renderChapterXhtml(chap.nodes, title, resolvedImages, audioInfo !== null);\n zip.file(`OEBPS/chapters/${filename}`, xhtml);\n\n let smilFilename: string | undefined;\n if (audioInfo) {\n smilFilename = `${id}.smil`;\n const smil = generateSmil(filename, audioInfo, chap.nodes);\n zip.file(`OEBPS/chapters/${smilFilename}`, smil);\n }\n\n chapterFiles.push({\n id,\n filename,\n title: chap.title,\n smilFilename,\n duration: audioInfo?.duration,\n });\n }\n\n // OEBPS/toc.xhtml (EPUB 3 nav)\n zip.file('OEBPS/toc.xhtml', generateTocXhtml(chapterFiles, title));\n\n // OEBPS/content.opf\n zip.file(\n 'OEBPS/content.opf',\n generateContentOpf({\n uuid,\n title,\n author,\n language,\n description,\n publisher,\n chapters: chapterFiles,\n images: resolvedImages,\n coverFilename,\n audioFiles: allAudioFiles,\n totalDuration: options.totalDuration,\n }),\n );\n\n const blob = await zip.generateAsync({\n type: 'arraybuffer',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n // mimetype was already set to STORE above; JSZip respects per-file options\n });\n\n return blob;\n}\n\n/**\n * Convert a squisq Doc to an EPUB 3 file.\n *\n * Convenience wrapper: Doc → MarkdownDocument → EPUB.\n * When the Doc has audio segments and `options.audio` is provided,\n * EPUB 3 Media Overlays are generated for narrated playback.\n */\nexport async function docToEpub(doc: Doc, options: EpubExportOptions = {}): Promise<ArrayBuffer> {\n const { docToMarkdown } = await import('@bendyline/squisq/doc');\n const markdownDoc = docToMarkdown(doc);\n\n // Thread audio segment metadata from the Doc into options\n const epubOptions: EpubExportOptions = { ...options };\n if (doc.audio?.segments?.length && !epubOptions.audioSegments) {\n epubOptions.audioSegments = doc.audio.segments;\n }\n if (doc.duration && !epubOptions.totalDuration) {\n epubOptions.totalDuration = doc.duration;\n }\n\n return markdownDocToEpub(markdownDoc, epubOptions);\n}\n\n// ── Chapter Splitting ─────────────────────────────────────────────\n\ninterface Chapter {\n title: string;\n nodes: MarkdownBlockNode[];\n}\n\ninterface ChapterFileInfo {\n id: string;\n filename: string;\n title: string;\n smilFilename?: string;\n duration?: number;\n}\n\ninterface ChapterAudioInfo {\n audioFilename: string;\n clipStart: number;\n clipEnd: number;\n duration: number;\n}\n\nfunction splitIntoChapters(nodes: MarkdownBlockNode[]): Chapter[] {\n const chapters: Chapter[] = [];\n let currentNodes: MarkdownBlockNode[] = [];\n let currentTitle = 'Untitled';\n\n for (const node of nodes) {\n if (node.type === 'heading' && node.depth <= 2) {\n // Flush previous chapter\n if (currentNodes.length > 0) {\n chapters.push({ title: currentTitle, nodes: currentNodes });\n }\n currentTitle = extractHeadingText(node);\n currentNodes = [node];\n } else {\n currentNodes.push(node);\n }\n }\n\n // Flush remaining\n if (currentNodes.length > 0) {\n chapters.push({ title: currentTitle, nodes: currentNodes });\n }\n\n // If no chapters were created, wrap everything as one\n if (chapters.length === 0) {\n chapters.push({ title: 'Untitled', nodes: [] });\n }\n\n return chapters;\n}\n\nfunction extractHeadingText(heading: MarkdownHeading): string {\n return heading.children.map(inlineToText).join('');\n}\n\nfunction inlineToText(node: MarkdownInlineNode): string {\n switch (node.type) {\n case 'text':\n return node.value;\n case 'emphasis':\n case 'strong':\n case 'delete':\n return node.children.map(inlineToText).join('');\n case 'inlineCode':\n return node.value;\n case 'link':\n return node.children.map(inlineToText).join('');\n case 'image':\n return node.alt ?? '';\n case 'break':\n return ' ';\n default:\n return '';\n }\n}\n\n// ── Image Collection ──────────────────────────────────────────────\n\nfunction collectDocImages(nodes: MarkdownBlockNode[]): Set<string> {\n const images = new Set<string>();\n\n function walkBlock(node: MarkdownBlockNode): void {\n switch (node.type) {\n case 'paragraph':\n case 'heading':\n node.children.forEach(walkInline);\n break;\n case 'blockquote':\n node.children.forEach(walkBlock);\n break;\n case 'list':\n node.children.forEach((item) => item.children.forEach(walkBlock));\n break;\n case 'table':\n node.children.forEach((row) =>\n row.children.forEach((cell) => cell.children.forEach(walkInline)),\n );\n break;\n default:\n break;\n }\n }\n\n function walkInline(node: MarkdownInlineNode): void {\n if (node.type === 'image' && node.url && !node.url.startsWith('data:')) {\n images.add(node.url);\n }\n if ('children' in node && Array.isArray(node.children)) {\n (node.children as MarkdownInlineNode[]).forEach(walkInline);\n }\n }\n\n nodes.forEach(walkBlock);\n return images;\n}\n\n// ── XHTML Rendering ───────────────────────────────────────────────\n\ntype ImageMap = Map<string, { data: ArrayBuffer; mime: string; filename: string }>;\n\nfunction renderChapterXhtml(\n nodes: MarkdownBlockNode[],\n bookTitle: string,\n images: ImageMap,\n addIds = false,\n): string {\n let elementCounter = 0;\n const nextId = () => `p${++elementCounter}`;\n const body = nodes.map((n) => blockToXhtml(n, images, addIds ? nextId : undefined)).join('\\n');\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n<head>\n <meta charset=\"UTF-8\"/>\n <title>${escapeXml(bookTitle)}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../styles.css\"/>\n</head>\n<body>\n${body}\n</body>\n</html>`;\n}\n\nfunction blockToXhtml(node: MarkdownBlockNode, images: ImageMap, nextId?: () => string): string {\n const idAttr = nextId ? ` id=\"${nextId()}\"` : '';\n\n switch (node.type) {\n case 'heading': {\n const tag = `h${node.depth}`;\n return `<${tag}${idAttr}>${inlinesToXhtml(node.children, images)}</${tag}>`;\n }\n\n case 'paragraph':\n return `<p${idAttr}>${inlinesToXhtml(node.children, images)}</p>`;\n\n case 'blockquote':\n return `<blockquote${idAttr}>\\n${node.children.map((c) => blockToXhtml(c, images, nextId)).join('\\n')}\\n</blockquote>`;\n\n case 'list': {\n const tag = node.ordered ? 'ol' : 'ul';\n const startAttr =\n node.ordered && node.start && node.start !== 1 ? ` start=\"${node.start}\"` : '';\n const items = node.children.map((item) => listItemToXhtml(item, images)).join('\\n');\n return `<${tag}${idAttr}${startAttr}>\\n${items}\\n</${tag}>`;\n }\n\n case 'code': {\n const langAttr = node.lang ? ` class=\"language-${escapeXml(node.lang)}\"` : '';\n return `<pre${idAttr}><code${langAttr}>${escapeXml(node.value)}</code></pre>`;\n }\n\n case 'thematicBreak':\n return `<hr${idAttr}/>`;\n\n case 'table':\n return tableToXhtml(node as MarkdownTable, images, idAttr);\n\n case 'htmlBlock':\n // Strip HTML tags for XHTML safety — raw HTML may not be well-formed XML\n return `<p${idAttr}>${escapeXml(node.rawHtml.replace(/<[^>]+>/g, ''))}</p>`;\n\n case 'math':\n return `<p${idAttr} class=\"math\">${escapeXml(node.value)}</p>`;\n\n default:\n return '';\n }\n}\n\nfunction listItemToXhtml(item: MarkdownListItem, images: ImageMap): string {\n const content = item.children.map((c) => blockToXhtml(c, images)).join('\\n');\n // Unwrap single <p> inside <li> for cleaner output\n const unwrapped =\n item.children.length === 1 && item.children[0].type === 'paragraph'\n ? inlinesToXhtml((item.children[0] as MarkdownParagraph).children, images)\n : content;\n return `<li>${unwrapped}</li>`;\n}\n\nfunction tableToXhtml(table: MarkdownTable, images: ImageMap, idAttr = ''): string {\n const rows = table.children;\n if (rows.length === 0) return `<table${idAttr}></table>`;\n\n const headerRow = rows[0];\n const bodyRows = rows.slice(1);\n const align = table.align ?? [];\n\n function cellToXhtml(cell: MarkdownTableCell, tag: 'th' | 'td', colIndex: number): string {\n const a = align[colIndex];\n const style = a ? ` style=\"text-align: ${a}\"` : '';\n return `<${tag}${style}>${inlinesToXhtml(cell.children, images)}</${tag}>`;\n }\n\n const thead = `<thead><tr>${headerRow.children.map((c, i) => cellToXhtml(c, 'th', i)).join('')}</tr></thead>`;\n const tbody =\n bodyRows.length > 0\n ? `<tbody>${bodyRows.map((row: MarkdownTableRow) => `<tr>${row.children.map((c, i) => cellToXhtml(c, 'td', i)).join('')}</tr>`).join('')}</tbody>`\n : '';\n\n return `<table${idAttr}>${thead}${tbody}</table>`;\n}\n\nfunction inlinesToXhtml(nodes: MarkdownInlineNode[], images: ImageMap): string {\n return nodes.map((n) => inlineToXhtml(n, images)).join('');\n}\n\nfunction inlineToXhtml(node: MarkdownInlineNode, images: ImageMap): string {\n switch (node.type) {\n case 'text':\n return escapeXml(node.value);\n\n case 'strong':\n return `<strong>${inlinesToXhtml(node.children, images)}</strong>`;\n\n case 'emphasis':\n return `<em>${inlinesToXhtml(node.children, images)}</em>`;\n\n case 'delete':\n return `<del>${inlinesToXhtml(node.children, images)}</del>`;\n\n case 'inlineCode':\n return `<code>${escapeXml(node.value)}</code>`;\n\n case 'link': {\n const titleAttr = node.title ? ` title=\"${escapeXml(node.title)}\"` : '';\n return `<a href=\"${escapeXml(node.url)}\"${titleAttr}>${inlinesToXhtml(node.children, images)}</a>`;\n }\n\n case 'image': {\n const alt = escapeXml(node.alt ?? '');\n const resolved = images.get(node.url);\n const src = resolved ? `../images/${resolved.filename}` : escapeXml(node.url);\n return `<img src=\"${src}\" alt=\"${alt}\"/>`;\n }\n\n case 'break':\n return '<br/>';\n\n case 'inlineMath':\n return `<span class=\"math\">${escapeXml(node.value)}</span>`;\n\n case 'htmlInline':\n // Strip tags for XHTML safety\n return escapeXml(node.rawHtml.replace(/<[^>]+>/g, ''));\n\n default:\n return '';\n }\n}\n\n// ── SMIL Media Overlays ───────────────────────────────────────────\n\n/**\n * Generate an EPUB 3 Media Overlay (SMIL) file for a chapter.\n * Maps block-level elements to audio clip ranges for synchronized narration.\n */\nfunction generateSmil(\n chapterFilename: string,\n audioInfo: ChapterAudioInfo,\n nodes: MarkdownBlockNode[],\n): string {\n // Count block elements to match the IDs generated by blockToXhtml.\n // Must mirror blockToXhtml's recursion: each block gets an ID,\n // blockquote children recurse (they pass nextId), but list items do not.\n let elementCount = 0;\n function countBlocks(node: MarkdownBlockNode): void {\n elementCount++;\n if (node.type === 'blockquote') node.children.forEach(countBlocks);\n }\n nodes.forEach(countBlocks);\n\n if (elementCount === 0) elementCount = 1;\n\n // Distribute audio duration evenly across elements (best effort without word-level timing)\n const clipDuration = audioInfo.duration / elementCount;\n const pars: string[] = [];\n\n for (let i = 0; i < elementCount; i++) {\n const clipStart = formatTime(audioInfo.clipStart + i * clipDuration, true);\n const clipEnd = formatTime(audioInfo.clipStart + (i + 1) * clipDuration, true);\n pars.push(\n ` <par id=\"par-${i + 1}\">` +\n `\\n <text src=\"${chapterFilename}#p${i + 1}\"/>` +\n `\\n <audio src=\"../audio/${escapeXml(audioInfo.audioFilename)}\" clipBegin=\"${clipStart}\" clipEnd=\"${clipEnd}\"/>` +\n `\\n </par>`,\n );\n }\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<smil xmlns=\"http://www.w3.org/ns/SMIL\" xmlns:epub=\"http://www.idpf.org/2007/ops\" version=\"3.0\">\n <body>\n <seq id=\"seq-1\" epub:textref=\"${chapterFilename}\">\n${pars.join('\\n')}\n </seq>\n </body>\n</smil>`;\n}\n\nfunction formatTime(seconds: number, fractional = false): string {\n const h = Math.floor(seconds / 3600);\n const m = Math.floor((seconds % 3600) / 60);\n const s = seconds % 60;\n const sPart = fractional ? s.toFixed(3).padStart(6, '0') : String(Math.floor(s)).padStart(2, '0');\n return `${h}:${String(m).padStart(2, '0')}:${sPart}`;\n}\n\n// ── Package Documents ─────────────────────────────────────────────\n\nconst CONTAINER_XML = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n <rootfiles>\n <rootfile full-path=\"OEBPS/content.opf\" media-type=\"application/oebps-package+xml\"/>\n </rootfiles>\n</container>`;\n\ninterface OpfParams {\n uuid: string;\n title: string;\n author: string;\n language: string;\n description: string;\n publisher: string;\n chapters: ChapterFileInfo[];\n images: ImageMap;\n coverFilename?: string;\n audioFiles?: { filename: string; mime: string }[];\n totalDuration?: number;\n}\n\nfunction generateContentOpf(params: OpfParams): string {\n const {\n uuid,\n title,\n author,\n language,\n description,\n publisher,\n chapters,\n images,\n coverFilename,\n audioFiles,\n totalDuration,\n } = params;\n const modified = new Date().toISOString().replace(/\\.\\d+Z$/, 'Z');\n const hasOverlays = chapters.some((c) => c.smilFilename);\n\n // Manifest items\n const manifestItems: string[] = [\n ' <item id=\"toc\" href=\"toc.xhtml\" media-type=\"application/xhtml+xml\" properties=\"nav\"/>',\n ' <item id=\"css\" href=\"styles.css\" media-type=\"text/css\"/>',\n ];\n\n if (coverFilename) {\n const mime = inferMimeType(coverFilename);\n manifestItems.push(\n ` <item id=\"cover-image\" href=\"images/${escapeXml(coverFilename)}\" media-type=\"${mime}\" properties=\"cover-image\"/>`,\n );\n manifestItems.push(\n ' <item id=\"cover-page\" href=\"chapters/cover.xhtml\" media-type=\"application/xhtml+xml\"/>',\n );\n }\n\n for (const chap of chapters) {\n const overlayAttr = chap.smilFilename ? ` media-overlay=\"${chap.id}-overlay\"` : '';\n manifestItems.push(\n ` <item id=\"${chap.id}\" href=\"chapters/${escapeXml(chap.filename)}\" media-type=\"application/xhtml+xml\"${overlayAttr}/>`,\n );\n if (chap.smilFilename) {\n manifestItems.push(\n ` <item id=\"${chap.id}-overlay\" href=\"chapters/${escapeXml(chap.smilFilename)}\" media-type=\"application/smil+xml\"/>`,\n );\n }\n }\n\n // Audio files in manifest\n if (audioFiles) {\n const usedAudioNames = new Set<string>();\n for (const af of audioFiles) {\n if (usedAudioNames.has(af.filename)) continue;\n usedAudioNames.add(af.filename);\n const audioId = `audio-${af.filename.replace(/[^a-zA-Z0-9]/g, '-')}`;\n manifestItems.push(\n ` <item id=\"${audioId}\" href=\"audio/${escapeXml(af.filename)}\" media-type=\"${af.mime}\"/>`,\n );\n }\n }\n\n const usedFilenames = new Set<string>();\n for (const [, img] of images) {\n if (usedFilenames.has(img.filename)) continue;\n usedFilenames.add(img.filename);\n const imgId = `img-${img.filename.replace(/[^a-zA-Z0-9]/g, '-')}`;\n manifestItems.push(\n ` <item id=\"${imgId}\" href=\"images/${escapeXml(img.filename)}\" media-type=\"${img.mime}\"/>`,\n );\n }\n\n // Spine — cover page first (if present), then chapters\n const spineEntries: string[] = [];\n if (coverFilename) {\n spineEntries.push(' <itemref idref=\"cover-page\"/>');\n }\n for (const chap of chapters) {\n spineEntries.push(` <itemref idref=\"${chap.id}\"/>`);\n }\n const spineItems = spineEntries.join('\\n');\n\n // Metadata\n const metaParts = [\n ` <dc:identifier id=\"uid\">urn:uuid:${uuid}</dc:identifier>`,\n ` <dc:title>${escapeXml(title)}</dc:title>`,\n ` <dc:language>${escapeXml(language)}</dc:language>`,\n ` <meta property=\"dcterms:modified\">${modified}</meta>`,\n ];\n if (author) metaParts.push(` <dc:creator>${escapeXml(author)}</dc:creator>`);\n if (description) metaParts.push(` <dc:description>${escapeXml(description)}</dc:description>`);\n if (publisher) metaParts.push(` <dc:publisher>${escapeXml(publisher)}</dc:publisher>`);\n\n // Media Overlay metadata\n if (hasOverlays && totalDuration) {\n metaParts.push(` <meta property=\"media:duration\">${formatTime(totalDuration)}</meta>`);\n metaParts.push(' <meta property=\"media:active-class\">epub-media-overlay-active</meta>');\n }\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"uid\">\n <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n${metaParts.join('\\n')}\n </metadata>\n <manifest>\n${manifestItems.join('\\n')}\n </manifest>\n <spine>\n${spineItems}\n </spine>\n</package>`;\n}\n\nfunction generateTocXhtml(chapters: ChapterFileInfo[], bookTitle: string): string {\n const navItems = chapters\n .map(\n (chap) =>\n ` <li><a href=\"chapters/${escapeXml(chap.filename)}\">${escapeXml(chap.title)}</a></li>`,\n )\n .join('\\n');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n<head>\n <meta charset=\"UTF-8\"/>\n <title>${escapeXml(bookTitle)}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\"/>\n</head>\n<body>\n <nav epub:type=\"toc\">\n <h1>Table of Contents</h1>\n <ol>\n${navItems}\n </ol>\n </nav>\n</body>\n</html>`;\n}\n\n// ── Stylesheet ────────────────────────────────────────────────────\n\nfunction generateStylesheet(themeId?: string): string {\n let themeVars = '';\n if (themeId) {\n const theme = resolveTheme(themeId);\n themeVars = `\n --epub-bg: ${theme.colors.background};\n --epub-text: ${theme.colors.text};\n --epub-primary: ${theme.colors.primary};\n --epub-heading-font: ${resolveFontFamily(theme.typography.titleFont, 'serif')};\n --epub-body-font: ${resolveFontFamily(theme.typography.bodyFont, 'sans-serif')};`;\n }\n\n return `/* Squisq EPUB Stylesheet */\n:root {${themeVars}\n}\n\nbody {\n font-family: var(--epub-body-font, Georgia, 'Times New Roman', serif);\n color: var(--epub-text, #1a1a1a);\n line-height: 1.7;\n margin: 1em 2em;\n max-width: 40em;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: var(--epub-heading-font, system-ui, sans-serif);\n color: var(--epub-primary, #1a1a1a);\n margin-top: 1.5em;\n margin-bottom: 0.5em;\n line-height: 1.3;\n}\n\nh1 { font-size: 2em; }\nh2 { font-size: 1.5em; }\nh3 { font-size: 1.25em; }\n\np {\n margin: 0.8em 0;\n}\n\na {\n color: var(--epub-primary, #2563eb);\n}\n\nimg {\n max-width: 100%;\n height: auto;\n}\n\npre {\n background: #f5f5f5;\n padding: 1em;\n overflow-x: auto;\n border-radius: 4px;\n font-size: 0.9em;\n line-height: 1.4;\n}\n\ncode {\n font-family: 'Courier New', Courier, monospace;\n font-size: 0.9em;\n}\n\np > code, li > code {\n background: #f0f0f0;\n padding: 0.1em 0.3em;\n border-radius: 3px;\n}\n\nblockquote {\n border-left: 3px solid var(--epub-primary, #d1d5db);\n margin: 1em 0;\n padding: 0.5em 1em;\n color: #4b5563;\n}\n\ntable {\n border-collapse: collapse;\n width: 100%;\n margin: 1em 0;\n}\n\nth, td {\n border: 1px solid #d1d5db;\n padding: 0.5em 0.75em;\n text-align: left;\n}\n\nth {\n background: #f3f4f6;\n font-weight: 600;\n}\n\nhr {\n border: none;\n border-top: 1px solid #d1d5db;\n margin: 2em 0;\n}\n\nul, ol {\n margin: 0.8em 0;\n padding-left: 1.5em;\n}\n\nli {\n margin: 0.3em 0;\n}\n\n.math {\n font-family: 'Courier New', Courier, monospace;\n font-style: italic;\n}\n\n/* Media Overlay active highlight (narration sync) */\n.epub-media-overlay-active {\n background-color: rgba(37, 99, 235, 0.12);\n}\n`;\n}\n"],"mappings":";;;;;;;;;AAuBA,OAAO,WAAW;AAElB,SAAS,cAAc,yBAAyB;AAwDhD,eAAsB,kBACpB,KACA,UAA6B,CAAC,GACR;AACtB,QAAM,UAAU,IAAI,aAAa;AACjC,QAAM,WAAW,IAAI,aAAa;AAClC,QAAM,QAAQ,QAAQ,UAAU,OAAO,YAAY,WAAW,UAAU;AACxE,QAAM,SAAS,QAAQ,WAAW,OAAO,aAAa,WAAW,WAAW;AAC5E,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,OAAO,OAAO,WAAW;AAG/B,QAAM,WAAW,kBAAkB,I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