import JSZip from 'jszip' import { splitByChapters } from './tiptap-to-html.js' const EPUB_CSS = ` body{font-family:Georgia,"Times New Roman",serif;font-size:1em;line-height:1.8;max-width:34em;margin:0 auto;padding:1em 1.5em} h1{font-size:1.5em;margin-top:2.5em;padding-bottom:0.3em;border-bottom:1px solid #ccc;page-break-before:always} h1:first-of-type{page-break-before:avoid} h2{font-size:1.2em;margin-top:1.5em} h3{font-size:1.05em;font-style:italic} p{margin:0.5em 0;text-indent:1.4em} p:first-child,h1+p,h2+p,h3+p{text-indent:0} blockquote{border-left:3px solid #aaa;padding-left:1em;margin:1em 0;font-style:italic;color:#444} img{max-width:100%;display:block;margin:1em auto} ` function xhtml(title, body) { return ` ${title} ${body} ` } export async function generateEpub(story) { const zip = new JSZip() const doc = typeof story.content === 'string' ? JSON.parse(story.content) : (story.content || {}) const title = story.title || 'Untitled' const chapters = splitByChapters(doc, title) const uid = `story-${story.id}` zip.file('mimetype', 'application/epub+zip', { compression: 'STORE' }) zip.file('META-INF/container.xml', ` `) zip.file('EPUB/styles.css', EPUB_CSS.trim()) const items = [] const itemrefs = [] const navEntries = [] chapters.forEach((ch, i) => { const n = String(i + 1).padStart(3, '0') const fname = `ch${n}.xhtml` zip.file(`EPUB/${fname}`, xhtml(ch.title, ch.html)) items.push(` `) itemrefs.push(` `) navEntries.push(`
  • ${ch.title}
  • `) }) zip.file('EPUB/nav.xhtml', ` Contents `) zip.file('EPUB/package.opf', ` ${uid} ${title} en ${new Date().toISOString()} ${items.join('\n')} ${itemrefs.join('\n')} `) return zip.generateAsync({ type: 'nodebuffer' }) }