Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: prose series export — manuscript + ePub + print PDF (#2181)
Adam Eivy480439639ade
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 52fafcbdba..abd1bf51b4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,7 @@## Creative Writing Quality Engine+- **[issue-2181] Prose series can now be exported as a compiled manuscript, an ePub, or a print-interior PDF.** A prose-format series had no shipping step — once the quality-engine phases produced publishable prose the pipeline dead-ended at "text in stages" (comic series already had `comicPdf`/`volumePdf`, prose had nothing). A new **Export** tab on the series page (deep-linkable `/pipeline/series/:id/export`, registered in the nav manifest) offers three downloads, each assembled on demand and streamed straight to disk: (1) a **compiled manuscript** (Markdown with YAML front matter, volume breaks, and chapter headings) that reuses the same arc-ordered, drafted-prose-only `collectManuscriptSections` stitching the editorial passes use, so the exported prose matches what the editor and LLM see; (2) an **ePub** — an OCF container (mimetype + container.xml + OPF manifest + nav doc + per-volume XHTML chapters + CSS + the cover image from the existing cover stage) packaged in-repo with the existing `zipWriter.createZip` (no epub dependency added, per the dependency policy — `mimetype` stays entry #0, stored, per spec); (3) a **print-interior PDF** — a trade-format interior (trim size, margins, running heads, title page, chapter openers) built on the same `pdf-lib` plumbing as `volumePdf.js`. Per-series export settings (trim size, interior font, title-page/subtitle/author/copyright/dedication) persist on the series record under a new `exportSettings` field (`sanitizeProseExportSettings`, wire-gated at `pipelineSeries` v12 + `ADDITIVE_SERIES_FIELDS` so an older peer can't strip-then-LWW it). Issues group into volume breaks by `seasonId`. (`server/services/pipeline/proseExport.js`, `server/lib/proseExportSettings.js`, `server/routes/pipeline/proseExport.js`, `client/src/pages/PipelineExport.jsx`)- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.- **[issue-2166] Editorial review now flags an issue whose narrative voice statistically drifts from the rest of the series.** A new deterministic `style.voice-drift` check measures each issue's prose fingerprint — sentence-length rhythm (mean, spread, variation), fragment and long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun and simile density, and how often sentences open the same way — then compares every issue against the series average and flags the outliers (e.g. "Issue 7's sentence-length variation is 0.18 vs the series 0.41 — prose has gone metronomic"). It's the cheap, deterministic complement to the existing LLM voice-consistency check: no model cost, and it names the exact issue and metric that drifted. You can tune the sensitivity (σ threshold), and optionally declare vocabulary "wells" — register categories like `trade: forge, anvil; body: pulse, sinew` — so it also flags an issue that drops a register the series leans on. It stays off until at least 4 issues are drafted (with fewer, the statistics are too small to distinguish real drift from a normal series).- **[issue-2172] The draft prompts now carry a craft anti-pattern corpus, so first drafts avoid recognizable "AI prose" tells before the editorial pass ever runs.** A shared `craft-anti-patterns` prompt block — injected into the prose-draft stage and the Writers Room live-continuation suggestions — encodes hard rules the model must follow while writing: no triadic sensory lists, a cap on "did not [verb]" and "the way X did Y" similes, no "thought about X" constructions or over-explaining after showing, varied paragraph lengths, at least 70% in-scene (not summary), speech that sounds like speech, and at least one genuinely surprising moment per chapter. The same block carries "Stability Trap" countermeasures (from the Rettberg & Wigers 2025 finding that AI stories favor stability over change): characters must end truly different, bad things are allowed to stay bad, some losses are irreversible, information is withheld rather than dumped, and every real choice has a real cost. Preventing these in the draft is far cheaper than detecting them in editorial. Existing installs auto-upgrade their prose/writers-room prompts (customized prompts are left untouched and flagged).diff --git a/client/src/App.jsx b/client/src/App.jsxindex e30432a4fd..4f033550dc 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -111,6 +111,7 @@ const PipelineReverseOutline = lazyWithReload(() => import('./pages/PipelineReveconst PipelineVoiceFingerprint = lazyWithReload(() => import('./pages/PipelineVoiceFingerprint'));const PipelineContinuityBible = lazyWithReload(() => import('./pages/PipelineContinuityBible'));const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));+const PipelineExport = lazyWithReload(() => import('./pages/PipelineExport'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));const Login = lazyWithReload(() => import('./pages/Login'));@@ -363,6 +364,7 @@ export default function App() {{/* Splat (not a :param route) so navigating between issues reuses thesame component instance instead of remounting + refetching. */}<Route path="pipeline/series/:seriesId/manuscript/*" element={<PipelineManuscriptEditor />} />+ <Route path="pipeline/series/:seriesId/export" element={<PipelineExport />} /><Route path="pipeline/series/:seriesId/sync" element={<SyncView kind="series" param="seriesId" backPath="/pipeline" />} /><Route path="pipeline/issues/:issueId" element={<Navigate to="idea" replace />} /><Route path="pipeline/issues/:issueId/:stage" element={<PipelineIssue />} />diff --git a/client/src/pages/PipelineExport.jsx b/client/src/pages/PipelineExport.jsxnew file mode 100644index 0000000000..c4eaf873d8--- /dev/null+++ b/client/src/pages/PipelineExport.jsx@@ -0,0 +1,265 @@+/**+ * Pipeline — Prose Series Export (#2181).+ *+ * The shipping step for a prose series: configure per-series export settings+ * (trim size, interior font, title-page fields) and download the compiled+ * manuscript (Markdown), an ePub, or a print-interior PDF. Settings persist on+ * the series record via PATCH; the three downloads are plain <a href> links to+ * server routes that stream the artifact (they read the SAVED settings, so the+ * download buttons gate on the form being clean — a dirty form must be saved+ * first, mirroring the "Run Now gates on saved state" rule).+ */++import { useEffect, useMemo, useState } from 'react';+import { Link, useParams, useNavigate } from 'react-router-dom';+import { Loader2, ArrowLeft, Download, Save, BookText, FileText, FileType } from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ getPipelineSeries,+ updatePipelineSeries,+ proseExportManuscriptUrl,+ proseExportEpubUrl,+ proseExportPdfUrl,+} from '../services/api';+import { useAsyncAction } from '../hooks/useAsyncAction';++// Kept in sync with server/lib/proseExportSettings.js (allow-lists + defaults).+const TRIM_SIZE_OPTIONS = [+ { value: 'us-trade', label: 'US Trade (6" × 9")' },+ { value: 'digest', label: 'Digest (5.5" × 8.5")' },+ { value: 'mass-market', label: 'Mass Market (4.25" × 6.75")' },+ { value: 'us-letter', label: 'US Letter (8.5" × 11")' },+ { value: 'a5', label: 'A5' },+];+const FONT_OPTIONS = [+ { value: 'times', label: 'Times (serif)' },+ { value: 'helvetica', label: 'Helvetica (sans)' },+ { value: 'courier', label: 'Courier (mono)' },+];+const DEFAULT_TRIM = 'us-trade';+const DEFAULT_FONT = 'times';++const emptyForm = {+ trimSize: DEFAULT_TRIM,+ interiorFont: DEFAULT_FONT,+ titlePageTitle: '',+ titlePageSubtitle: '',+ titlePageAuthor: '',+ copyright: '',+ dedication: '',+};++// Shape the stored (possibly-null) exportSettings into a fully-populated form,+// filling blank title-page fields from the series so the inputs show the same+// values the export would use.+const formFromSeries = (series) => {+ const es = series?.exportSettings || {};+ return {+ trimSize: es.trimSize || DEFAULT_TRIM,+ interiorFont: es.interiorFont || DEFAULT_FONT,+ titlePageTitle: es.titlePageTitle || series?.name || '',+ titlePageSubtitle: es.titlePageSubtitle || series?.logline || '',+ titlePageAuthor: es.titlePageAuthor || series?.author || '',+ copyright: es.copyright || '',+ dedication: es.dedication || '',+ };+};++export default function PipelineExport() {+ const { seriesId } = useParams();+ const navigate = useNavigate();+ const [series, setSeries] = useState(null);+ const [loading, setLoading] = useState(true);+ const [form, setForm] = useState(emptyForm);+ const [savedForm, setSavedForm] = useState(emptyForm);++ useEffect(() => {+ let canceled = false;+ setLoading(true);+ getPipelineSeries(seriesId)+ .then((s) => {+ if (canceled) return;+ setSeries(s);+ const f = formFromSeries(s);+ setForm(f);+ setSavedForm(f);+ })+ .catch((err) => {+ if (canceled) return;+ toast.error(err.message || 'Failed to load series');+ navigate('/pipeline');+ })+ .finally(() => { if (!canceled) setLoading(false); });+ return () => { canceled = true; };+ }, [seriesId, navigate]);++ const dirty = useMemo(+ () => JSON.stringify(form) !== JSON.stringify(savedForm),+ [form, savedForm],+ );++ const [saveSettings, saving] = useAsyncAction(async () => {+ const updated = await updatePipelineSeries(seriesId, { exportSettings: form }, { silent: true });+ setSeries(updated);+ setSavedForm(form);+ toast.success('Export settings saved');+ }, { errorMessage: 'Failed to save export settings' });++ const setField = (key) => (e) => setForm((prev) => ({ ...prev, [key]: e.target.value }));++ if (loading) {+ return (+ <div className="h-full flex items-center justify-center text-gray-400">+ <Loader2 className="animate-spin" size={20} />+ </div>+ );+ }++ const downloads = [+ { key: 'md', label: 'Manuscript (.md)', desc: 'Compiled Markdown — front matter, volume breaks, chapter headings.', url: proseExportManuscriptUrl(seriesId), Icon: FileText },+ { key: 'epub', label: 'ePub (.epub)', desc: 'Reflowable e-book — chapters, table of contents, cover.', url: proseExportEpubUrl(seriesId), Icon: BookText },+ { key: 'pdf', label: 'Print Interior (.pdf)', desc: 'Trade-format interior — trim size, running heads, chapter openers.', url: proseExportPdfUrl(seriesId), Icon: FileType },+ ];++ return (+ <div className="h-full overflow-y-auto p-4 md:p-6">+ <header className="flex flex-wrap items-center gap-2 mb-6">+ <Link+ to={`/pipeline/series/${seriesId}`}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"+ title="Back to series"+ >+ <ArrowLeft size={12} /> Series+ </Link>+ <h1 className="text-lg font-semibold text-white flex items-center gap-2">+ <Download size={18} className="text-port-accent" /> Export+ </h1>+ {series?.name ? <span className="text-sm text-gray-400 truncate">— {series.name}</span> : null}+ </header>++ <div className="grid gap-6 lg:grid-cols-2 max-w-5xl">+ {/* Settings */}+ <section className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-4">+ <h2 className="text-sm font-semibold text-white">Export settings</h2>++ <div className="grid grid-cols-2 gap-3">+ <div>+ <label htmlFor="export-trim" className="block text-xs text-gray-400 mb-1">Trim size</label>+ <select+ id="export-trim"+ value={form.trimSize}+ onChange={setField('trimSize')}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ {TRIM_SIZE_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="export-font" className="block text-xs text-gray-400 mb-1">Interior font</label>+ <select+ id="export-font"+ value={form.interiorFont}+ onChange={setField('interiorFont')}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ {FONT_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </select>+ </div>+ </div>++ <div>+ <label htmlFor="export-title" className="block text-xs text-gray-400 mb-1">Title-page title</label>+ <input+ id="export-title"+ type="text"+ value={form.titlePageTitle}+ onChange={setField('titlePageTitle')}+ placeholder={series?.name || 'Title'}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ <div>+ <label htmlFor="export-subtitle" className="block text-xs text-gray-400 mb-1">Subtitle</label>+ <input+ id="export-subtitle"+ type="text"+ value={form.titlePageSubtitle}+ onChange={setField('titlePageSubtitle')}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ <div>+ <label htmlFor="export-author" className="block text-xs text-gray-400 mb-1">Author</label>+ <input+ id="export-author"+ type="text"+ value={form.titlePageAuthor}+ onChange={setField('titlePageAuthor')}+ placeholder={series?.author || 'Author'}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ <div>+ <label htmlFor="export-copyright" className="block text-xs text-gray-400 mb-1">Copyright line</label>+ <input+ id="export-copyright"+ type="text"+ value={form.copyright}+ onChange={setField('copyright')}+ placeholder="© 2026 …"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ <div>+ <label htmlFor="export-dedication" className="block text-xs text-gray-400 mb-1">Dedication</label>+ <textarea+ id="export-dedication"+ value={form.dedication}+ onChange={setField('dedication')}+ rows={2}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white resize-y"+ />+ </div>++ <div className="flex items-center gap-3">+ <button+ type="button"+ onClick={saveSettings}+ disabled={!dirty || saving}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving…' : 'Save settings'}+ </button>+ {dirty ? <span className="text-xs text-port-warning">Unsaved changes — save before downloading.</span> : null}+ </div>+ </section>++ {/* Downloads */}+ <section className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-3">+ <h2 className="text-sm font-semibold text-white">Download</h2>+ <p className="text-xs text-gray-500">+ Each export stitches the drafted issue prose in arc order (volume breaks + chapter headings).+ Requires at least one issue with drafted prose.+ </p>+ {downloads.map(({ key, label, desc, url, Icon }) => (+ <a+ key={key}+ href={dirty ? undefined : url}+ download+ aria-disabled={dirty}+ onClick={(e) => { if (dirty) { e.preventDefault(); toast.warning('Save your export settings first'); } }}+ className={`flex items-start gap-3 p-3 rounded-lg border border-port-border bg-port-bg transition ${dirty ? 'opacity-50 cursor-not-allowed' : 'hover:border-port-accent'}`}+ >+ <Icon size={18} className="text-port-accent mt-0.5 shrink-0" />+ <span className="flex flex-col">+ <span className="text-sm text-white font-medium">{label}</span>+ <span className="text-xs text-gray-500">{desc}</span>+ </span>+ </a>+ ))}+ </section>+ </div>+ </div>+ );+}diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 56b8ad3a24..7335efe6a2 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -15,7 +15,7 @@ import { Link, useParams, useNavigate } from 'react-router-dom';import {ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass, BookMarked,- Fingerprint, Plus, Trash2, Wand2, Check, X,+ Fingerprint, Plus, Trash2, Wand2, Check, X, Download,} from 'lucide-react';import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';@@ -250,6 +250,13 @@ export default function PipelineSeries() {><FileInput size={12} /> Import</Link>+ <Link+ to={`/pipeline/series/${series.id}/export`}+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"+ title="Export the compiled manuscript, an ePub, or a print-interior PDF"+ >+ <Download size={12} /> Export+ </Link><buttontype="button"onClick={handleSave}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 40ba7632f8..59fe32af2c 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -322,6 +322,16 @@ export const pipelineVolumePdfUrl = (seriesId, seasonId, { size } = {}) => {return `/api/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/volume.pdf${qs}`;};+// Prose-series export download URLs (#2181). Used as <a href> so the browser+// streams each artifact straight to disk (no in-app blob handling). All three+// read the persisted per-series export settings server-side.+export const proseExportManuscriptUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/export/manuscript.md`;+export const proseExportEpubUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/export/book.epub`;+export const proseExportPdfUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/export/interior.pdf`;+// Patch one comic page's raw markdown — the server re-parses panels from the// edited rawText so subsequent renders still get a structured prompt.// Returns { issue, stage, page }.diff --git a/server/lib/README.md b/server/lib/README.mdindex a51513cf5d..9c1b4296a2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -60,6 +60,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). || `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |+| `proseExportSettings.js` | Per-series prose-export settings (#2181): `sanitizeProseExportSettings` + `resolveExportSettings` + `TRIM_SIZES`/`INTERIOR_FONTS` for the manuscript/ePub/PDF exports. || `shotGrammar.js` | Pure shot-grammar vocabularies (`SHOT_TYPES`, `SCREEN_DIRECTIONS`) + normalizers (`normalizeShotType`, `normalizeScreenDirection`) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the `visual.shot-continuity` editorial check (#1315). || `seasonStructure.js` | Season/episode structure recommendation. || `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 4a85db345e..cb99d81c05 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -57,6 +57,7 @@ export * from './creativeDirectorPrompts.js';export * as editorial from './editorial/index.js';export * from './sceneExtractor.js';export * from './scenePrompt.js';+export * from './proseExportSettings.js';export * from './shotGrammar.js';export * from './seasonStructure.js';export * from './seriesCharacterArc.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 52075e51b4..1e507be7d9 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -31,6 +31,7 @@ export const NAV_COMMANDS = [{ id: 'nav.create.pipeline.editorial-checks', path: '/pipeline/editorial-checks', label: 'Editorial Checks', section: 'Create', aliases: ['editorial-checks', 'editorial', 'checks', 'editorial-review', 'content-checks', 'manuscript-checks'], keywords: ['editorial', 'check', 'review', 'naming', 'exposition', 'info-dumping', 'continuity', 'quality', 'lint', 'triage', 'findings', 'deterministic', 'llm'] },{ id: 'nav.create.pipeline-continuity-bible', path: '/pipeline', label: 'Series Continuity', section: 'Create', aliases: ['continuity-bible', 'continuity', 'series-continuity', 'facts-ledger', 'established-facts', 'canon-ledger'], keywords: ['continuity', 'bible', 'facts', 'ledger', 'established', 'knowledge-leak', 'contradiction', 'timeline', 'wardrobe', 'prop', 'physical-traits', 'who-knows-what'] },{ id: 'nav.create.pipeline-voice-fingerprint', path: '/pipeline', label: 'Voice Fingerprint', section: 'Create', aliases: ['voice-fingerprint', 'voice-drift', 'fingerprint', 'voice-matrix', 'prose-fingerprint'], keywords: ['voice', 'drift', 'fingerprint', 'matrix', 'style', 'prose', 'sentence-rhythm', 'outlier', 'metrics', 'deterministic', 'editorial', 'consistency', 'register', 'vocabulary-wells'] },+ { id: 'nav.create.pipeline-export', path: '/pipeline', label: 'Prose Series Export', section: 'Create', aliases: ['export', 'prose-export', 'series-export', 'manuscript-export', 'epub', 'ebook', 'publish'], keywords: ['export', 'manuscript', 'epub', 'ebook', 'pdf', 'print', 'interior', 'trade paperback', 'compiled', 'download', 'publish', 'trim size', 'title page', 'book'] },{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },{ id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },{ id: 'nav.create.start-story', path: '/start-story', label: 'Start a Story', section: 'Create', aliases: ['start-story', 'start-a-story', 'start', 'begin-story', 'create-story', 'onramp'], keywords: ['start here', 'begin', 'idea', 'import', 'prose', 'story builder', 'writers room', 'importer', 'how to start', 'new', 'front door', 'choose'] },diff --git a/server/lib/proseExportSettings.js b/server/lib/proseExportSettings.jsnew file mode 100644index 0000000000..1a66ca88e8--- /dev/null+++ b/server/lib/proseExportSettings.js@@ -0,0 +1,83 @@+/**+ * proseExportSettings.js — per-series prose-export settings sanitizer + presets.+ *+ * A prose series can be exported as a compiled manuscript (Markdown), an ePub,+ * or a print-interior PDF (issue #2181). The knobs that shape those artifacts —+ * trim size, interior font, and title-page fields — live on the series record+ * under `exportSettings`. This is the pure sanitizer for that sub-object+ * (mirrors `sanitizeStyleGuide`): it returns `null` when nothing meaningful is+ * set so a series that never configured export keeps its on-disk + wire shape+ * unchanged, and existing series.json files migrate forward without a writer+ * pass (first save backfills).+ */++// Trade-paperback trim sizes, in PDF points (1pt = 1/72"). The keys are stable+// wire values; the labels are UI-only (kept on the client). us-trade (6"×9") is+// the default fiction trade size.+export const TRIM_SIZES = Object.freeze({+ 'us-trade': { width: 432, height: 648 }, // 6" × 9"+ 'digest': { width: 396, height: 612 }, // 5.5" × 8.5"+ 'mass-market': { width: 306, height: 486 }, // 4.25" × 6.75"+ 'us-letter': { width: 612, height: 792 }, // 8.5" × 11"+ 'a5': { width: 419.53, height: 595.28 }, // A5+});+export const DEFAULT_TRIM_SIZE = 'us-trade';++// Interior body fonts — the pdf-lib StandardFonts a print interior can use+// without embedding a font file. Times is the traditional book-interior serif.+export const INTERIOR_FONTS = Object.freeze(['times', 'helvetica', 'courier']);+export const DEFAULT_INTERIOR_FONT = 'times';++const TITLE_MAX = 200;+const SUBTITLE_MAX = 300;+const AUTHOR_MAX = 120;+const COPYRIGHT_MAX = 500;+const DEDICATION_MAX = 2000;++const trimTo = (val, max) => (typeof val === 'string' ? val.trim().slice(0, max) : '');++/**+ * Sanitize the optional `series.exportSettings` field. Returns `null` when the+ * settings carry no non-default content (so a series that only accepted the+ * defaults doesn't persist an empty husk). `trimSize`/`interiorFont` are always+ * validated against their allow-lists; the title-page fields are free text,+ * bounded. Legacy-tolerant: absent → `null`.+ */+export function sanitizeProseExportSettings(raw) {+ if (raw == null || typeof raw !== 'object') return null;+ const trimSize = TRIM_SIZES[raw.trimSize] ? raw.trimSize : null;+ const interiorFont = INTERIOR_FONTS.includes(raw.interiorFont) ? raw.interiorFont : null;+ const titlePageTitle = trimTo(raw.titlePageTitle, TITLE_MAX);+ const titlePageSubtitle = trimTo(raw.titlePageSubtitle, SUBTITLE_MAX);+ const titlePageAuthor = trimTo(raw.titlePageAuthor, AUTHOR_MAX);+ const copyright = trimTo(raw.copyright, COPYRIGHT_MAX);+ const dedication = trimTo(raw.dedication, DEDICATION_MAX);+ if (+ trimSize == null && interiorFont == null && !titlePageTitle && !titlePageSubtitle+ && !titlePageAuthor && !copyright && !dedication+ ) {+ return null;+ }+ return {+ trimSize, interiorFont, titlePageTitle, titlePageSubtitle, titlePageAuthor, copyright, dedication,+ };+}++/**+ * Resolve the effective export settings a build uses: the stored sub-object+ * merged over the defaults, with the series' own name/author filling any blank+ * title-page fields. Always returns a fully-populated object (never null), so+ * the packagers never branch on absent config.+ */+export function resolveExportSettings(series) {+ const stored = sanitizeProseExportSettings(series?.exportSettings) || {};+ return {+ trimSize: stored.trimSize || DEFAULT_TRIM_SIZE,+ interiorFont: stored.interiorFont || DEFAULT_INTERIOR_FONT,+ titlePageTitle: stored.titlePageTitle || series?.name || 'Untitled',+ titlePageSubtitle: stored.titlePageSubtitle || series?.logline || '',+ titlePageAuthor: stored.titlePageAuthor || series?.author || '',+ copyright: stored.copyright || '',+ dedication: stored.dedication || '',+ };+}diff --git a/server/lib/proseExportSettings.test.js b/server/lib/proseExportSettings.test.jsnew file mode 100644index 0000000000..8b951ac1b1--- /dev/null+++ b/server/lib/proseExportSettings.test.js@@ -0,0 +1,87 @@+/**+ * proseExportSettings.test.js — the per-series export-settings sanitizer ++ * resolver (#2181).+ */++import { describe, it, expect } from 'vitest';+import {+ sanitizeProseExportSettings,+ resolveExportSettings,+ TRIM_SIZES,+ INTERIOR_FONTS,+ DEFAULT_TRIM_SIZE,+ DEFAULT_INTERIOR_FONT,+} from './proseExportSettings.js';++describe('sanitizeProseExportSettings', () => {+ it('returns null for absent / non-object / all-default input', () => {+ expect(sanitizeProseExportSettings(undefined)).toBeNull();+ expect(sanitizeProseExportSettings(null)).toBeNull();+ expect(sanitizeProseExportSettings('nope')).toBeNull();+ expect(sanitizeProseExportSettings({})).toBeNull();+ // Unknown enum values collapse to null → still an empty husk → null.+ expect(sanitizeProseExportSettings({ trimSize: 'ghost', interiorFont: 'wingdings' })).toBeNull();+ });++ it('keeps valid trim size + font and drops invalid enums', () => {+ const out = sanitizeProseExportSettings({ trimSize: 'digest', interiorFont: 'courier' });+ expect(out.trimSize).toBe('digest');+ expect(out.interiorFont).toBe('courier');+ const bad = sanitizeProseExportSettings({ trimSize: 'ghost', interiorFont: 'courier' });+ expect(bad.trimSize).toBeNull();+ expect(bad.interiorFont).toBe('courier');+ });++ it('trims and bounds title-page text fields', () => {+ const out = sanitizeProseExportSettings({+ titlePageTitle: ' My Book ',+ titlePageAuthor: 'Ada',+ copyright: '© 2026',+ dedication: 'For X.',+ });+ expect(out.titlePageTitle).toBe('My Book');+ expect(out.titlePageAuthor).toBe('Ada');+ expect(out.copyright).toBe('© 2026');+ expect(out.dedication).toBe('For X.');+ // A long title is clipped to the 200-char bound.+ const long = sanitizeProseExportSettings({ titlePageTitle: 'x'.repeat(500) });+ expect(long.titlePageTitle.length).toBe(200);+ });++ it('exposes stable allow-lists + defaults', () => {+ expect(Object.keys(TRIM_SIZES)).toContain(DEFAULT_TRIM_SIZE);+ expect(INTERIOR_FONTS).toContain(DEFAULT_INTERIOR_FONT);+ // Every trim size carries positive point dimensions.+ for (const dims of Object.values(TRIM_SIZES)) {+ expect(dims.width).toBeGreaterThan(0);+ expect(dims.height).toBeGreaterThan(0);+ }+ });+});++describe('resolveExportSettings', () => {+ it('fills blank fields from the series and applies defaults', () => {+ const r = resolveExportSettings({ name: 'Series Name', logline: 'A tale', author: 'Author' });+ expect(r.trimSize).toBe(DEFAULT_TRIM_SIZE);+ expect(r.interiorFont).toBe(DEFAULT_INTERIOR_FONT);+ expect(r.titlePageTitle).toBe('Series Name');+ expect(r.titlePageSubtitle).toBe('A tale');+ expect(r.titlePageAuthor).toBe('Author');+ });++ it('prefers explicit stored settings over series fallbacks', () => {+ const r = resolveExportSettings({+ name: 'Series Name',+ author: 'Author',+ exportSettings: { trimSize: 'a5', titlePageTitle: 'Override', titlePageAuthor: 'Other' },+ });+ expect(r.trimSize).toBe('a5');+ expect(r.titlePageTitle).toBe('Override');+ expect(r.titlePageAuthor).toBe('Other');+ });++ it('falls back to Untitled when the series has no name', () => {+ expect(resolveExportSettings({}).titlePageTitle).toBe('Untitled');+ expect(resolveExportSettings(null).titlePageTitle).toBe('Untitled');+ });+});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 3b81156046..eb16e05758 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -150,7 +150,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// wholly-absent `styleGuide`, not a present-but-sub-field-stripped one). Bump makes// the older peer reject the ahead-version series transfer instead. Per-category gate// → only series sync pauses with old peers.- pipelineSeries: 11,+ // v12 = `series.exportSettings` added (#2181) — the per-series prose-export+ // config (trim size, interior font, title-page fields) for the compiled-+ // manuscript / ePub / print-interior-PDF exports. Top-level additive field+ // like styleGuide (v4): a ≤v11 peer that re-sanitizes a series through its+ // exportSettings-unaware `sanitizeSeries` would silently strip it and+ // last-writer-wins the loss back onto the newer peer+ // (`preserveAbsentAdditiveFields` restores a wholly-absent `exportSettings`+ // from a BEHIND-version SAME-schema peer, but a wire-received record from an+ // OLDER peer must be rejected outright). Bump makes the older peer reject the+ // ahead-version series transfer instead. Per-category gate → only series sync+ // pauses with old peers.+ pipelineSeries: 12,// NOT bumped for the manuscript-review sibling doc now bundled on series// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).// Unlike `readerMap` (v2), the review is NOT a field inside the seriesdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 5ee2966965..7c5a8dc651 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -27,13 +27,13 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {it('declares pipeline collection layout versions', () => {// pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);- // pipelineSeries bumped to 11 when series.styleGuide.voiceExemplars +- // voiceAntiExemplars were added (#2179)+ // pipelineSeries bumped to 12 when series.exportSettings was added (#2181)// (v2 = readerMap, v3 = tickingClock, v4 = styleGuide, v5 = coverImage,// v6 = characterArcs, v7 = factCritical + factReference,// v8 = editorialCheckConfig, v9 = severityWeights + blockingSeverities,- // v10 = arc.foreshadowing).- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(11);+ // v10 = arc.foreshadowing, v11 = styleGuide.voiceExemplars ++ // voiceAntiExemplars).+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(12);});it('declares mediaCollections layout version', () => {@@ -47,7 +47,7 @@ describe('buildPortosMeta', () => {expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(7);expect(meta.schemaVersions.pipelineIssues).toBe(2);- expect(meta.schemaVersions.pipelineSeries).toBe(11);+ expect(meta.schemaVersions.pipelineSeries).toBe(12);});it('overrides merge into schemaVersions', async () => {diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.jsindex 8e5401472d..f33b8d5e90 100644--- a/server/routes/pipeline/index.js+++ b/server/routes/pipeline/index.js@@ -58,6 +58,7 @@ import continuityBibleRoutes from './continuityBible.js';import perspectiveRewriteRoutes from './perspectiveRewrite.js';import autopilotRoutes from './autopilot.js';import canonRoutes from './canon.js';+import proseExportRoutes from './proseExport.js';const router = Router();@@ -73,5 +74,6 @@ router.use(continuityBibleRoutes);router.use(perspectiveRewriteRoutes);router.use(autopilotRoutes);router.use(canonRoutes);+router.use(proseExportRoutes);export default router;diff --git a/server/routes/pipeline/proseExport.js b/server/routes/pipeline/proseExport.jsnew file mode 100644index 0000000000..d135881c73--- /dev/null+++ b/server/routes/pipeline/proseExport.js@@ -0,0 +1,52 @@+/**+ * Pipeline prose-export routes (#2181) — download a prose series as a compiled+ * manuscript (Markdown), an ePub, or a print-interior PDF. Each artifact is+ * assembled on demand and streamed straight to the response — no on-disk+ * artifact, so a re-export always reflects the freshest manuscript. All three+ * 409 (ERR_NO_PROSE) when no issue has drafted prose yet.+ */++import { Router } from 'express';+import { asyncHandler } from '../../lib/errorHandler.js';+import {+ buildManuscriptFile,+ buildEpub,+ buildProsePdf,+} from '../../services/pipeline/proseExport.js';+import { mapServiceError } from './shared.js';++const router = Router();++// Stream a Buffer/Uint8Array body with download headers.+const sendBinary = (res, { bytes, filename, contentType }) => {+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ res.setHeader('Content-Type', contentType);+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);+ res.setHeader('Content-Length', String(buf.length));+ res.end(buf);+};++// Compiled manuscript — Markdown with front matter, volume breaks, chapter headings.+router.get('/series/:id/export/manuscript.md', asyncHandler(async (req, res) => {+ const { text, filename } = await buildManuscriptFile(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ res.setHeader('Content-Type', 'text/markdown; charset=utf-8');+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);+ res.send(text);+}));++// ePub — OCF container (XHTML chapters + OPF manifest + cover), packaged in-repo.+router.get('/series/:id/export/book.epub', asyncHandler(async (req, res) => {+ const { bytes, filename } = await buildEpub(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ sendBinary(res, { bytes, filename, contentType: 'application/epub+zip' });+}));++// Print-interior PDF — trade-format interior (trim size, margins, running heads).+router.get('/series/:id/export/interior.pdf', asyncHandler(async (req, res) => {+ const { bytes, filename } = await buildProsePdf(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ sendBinary(res, { bytes, filename, contentType: 'application/pdf' });+}));++export default router;diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex 79112807c8..50ac749b1b 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -9,6 +9,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import { validateRequest, optionalBooleanMap, llmSchema } from '../../lib/validation.js';import * as seriesSvc from '../../services/pipeline/series.js';+import { TRIM_SIZES, INTERIOR_FONTS } from '../../lib/proseExportSettings.js';import * as issuesSvc from '../../services/pipeline/issues.js';import * as seasonsSvc from '../../services/pipeline/seasons.js';import { findDuplicateSeriesGroups, findSameNameSeries } from '../../services/duplicateDetection.js';@@ -207,6 +208,20 @@ const blockingSeveritiesSchema = z.object({editorial: z.array(blockingSeverityEnum).optional(),}).strict();+// Per-series prose-export settings (#2181). All fields optional so a partial+// PATCH tunes one knob; `null` clears the whole sub-object (defaults apply).+// Re-bounded by sanitizeProseExportSettings on persist. `trimSize`/`interiorFont`+// validated against their allow-lists; the title-page fields are free text.+const exportSettingsSchema = z.object({+ trimSize: z.enum(Object.keys(TRIM_SIZES)).optional(),+ interiorFont: z.enum(INTERIOR_FONTS).optional(),+ titlePageTitle: z.string().trim().max(200).optional(),+ titlePageSubtitle: z.string().trim().max(300).optional(),+ titlePageAuthor: z.string().trim().max(120).optional(),+ copyright: z.string().trim().max(500).optional(),+ dedication: z.string().trim().max(2000).optional(),+}).strict();+const seriesCreateSchema = z.object({name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional().default(''),@@ -235,6 +250,7 @@ const seriesCreateSchema = z.object({factCritical: z.boolean().optional().default(false),factReference: z.string().trim().max(seriesSvc.FACT_REFERENCE_MAX).optional().default(''),styleGuide: styleGuideSchema.nullable().optional(),+ exportSettings: exportSettingsSchema.nullable().optional(),titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional().default(''),author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional().default(''),authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),@@ -263,6 +279,7 @@ const seriesPatchSchema = z.object({factCritical: z.boolean().optional(),factReference: z.string().trim().max(seriesSvc.FACT_REFERENCE_MAX).optional(),styleGuide: styleGuideSchema.nullable().optional(),+ exportSettings: exportSettingsSchema.nullable().optional(),titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional(),author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional(),authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),diff --git a/server/routes/pipeline/shared.js b/server/routes/pipeline/shared.jsindex bbfe969876..717be04478 100644--- a/server/routes/pipeline/shared.js+++ b/server/routes/pipeline/shared.js@@ -14,6 +14,7 @@ import * as manuscriptFix from '../../services/pipeline/manuscriptFix.js';import { ERR_NO_STORYBOARDS } from '../../services/pipeline/episodeVideo.js';import { ERR_NO_RENDERED_PAGES } from '../../services/pipeline/comicPdf.js';import { ERR_NO_VOLUME_COVER, ERR_NO_RENDERED_ISSUES } from '../../services/pipeline/volumePdf.js';+import { ERR_NO_PROSE } from '../../services/pipeline/proseExport.js';import { buildCascadeContext } from '../../services/recordMerge.js';const SERVICE_ERROR_STATUS = {@@ -37,6 +38,9 @@ const SERVICE_ERROR_STATUS = {[ERR_NO_RENDERED_PAGES]: 409,[ERR_NO_VOLUME_COVER]: 409,[ERR_NO_RENDERED_ISSUES]: 409,+ // Prose-export refusal when no issue has drafted prose (#2181) → 409, same+ // "resource not ready for this action" idiom as the PDF exports above.+ [ERR_NO_PROSE]: 409,// recordMerge validation (unresolved conflicts, bad ids, cross-universe).MERGE_VALIDATION: 400,// recordMerge cascade partially completed (the issue reassign failed) → 409 sodiff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 8e77f6fbf9..b1f0bb8aea 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -185,6 +185,9 @@ export async function collectManuscriptSections(seriesId, { stageOrder = MANUSCRif (!pick) continue;sections.push({issueId: iss.id,+ // `seasonId` (additive) lets the prose-export packager group issues into+ // volume breaks; existing corpus/completeness callers ignore it.+ seasonId: iss.seasonId || null,number: iss.number,title: iss.title || '',stageId: pick.sid,diff --git a/server/services/pipeline/proseExport.js b/server/services/pipeline/proseExport.jsnew file mode 100644index 0000000000..8881a87a22--- /dev/null+++ b/server/services/pipeline/proseExport.js@@ -0,0 +1,485 @@+/**+ * proseExport.js — Prose series export (issue #2181).+ *+ * The shipping step for a prose-format series: once the quality-engine phases+ * produce publishable prose, this stitches the drafted issue prose (in arc+ * order, grouped into volume breaks) into three downloadable artifacts:+ *+ * 1. Compiled manuscript — Markdown with front matter, volume breaks, and+ * chapter headings. Reuses the same `collectManuscriptSections` stitching+ * the editorial passes use (arc-ordered, drafted-prose-only), so the+ * exported prose is the same text the editor and the LLM see; only the+ * surrounding front matter / volume / chapter framing is added here.+ * 2. ePub — an OCF (zip) container: `mimetype` + container.xml+ * + an OPF package manifest + a nav doc + per-volume XHTML chapters + CSS,+ * plus the cover image from the existing cover stage. Packaged in-repo with+ * `server/lib/zipWriter.js` (no epub dependency, per the dependency policy).+ * 3. Print-interior PDF — a trade-format interior (trim size, margins,+ * running heads, title page, chapter openers) built on the same `pdf-lib`+ * plumbing as `volumePdf.js` / `comicPdf.js`.+ *+ * All three are assembled on demand and streamed straight to the response — no+ * on-disk artifact, so a re-export always reflects the freshest manuscript.+ *+ * The pure helpers (markdown/XHTML/OPF builders + the paginator) are exported+ * via `__testing` so the export shape is unit-tested without touching disk.+ */++import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';+import { createZip } from '../../lib/zipWriter.js';+import { slugifyForFilename } from '../../lib/civitai.js';+import { readImageFromMedia, detectImageKind } from '../../lib/pdfImageEmbed.js';+import { resolveExportSettings, TRIM_SIZES, DEFAULT_TRIM_SIZE } from '../../lib/proseExportSettings.js';+import { getSeries } from './series.js';+import { listSeasons } from './seasons.js';+import { collectManuscriptSections } from './arcPlanner.js';++export const ERR_NO_PROSE = 'PIPELINE_PROSE_EXPORT_NO_CONTENT';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++const nowUtc = () => new Date().toISOString().slice(0, 19).replace('T', ' ');++// ---------------------------------------------------------------------------+// Section gathering — the shared front for all three exports.+// ---------------------------------------------------------------------------++/**+ * Collect the drafted prose sections in arc order and group them into volumes+ * by `seasonId`. Returns `{ series, sections, volumes }` where `volumes` is an+ * ordered list of `{ id, title, number, sections }`. Sections that don't map to+ * a known season (or a series with no seasons) fall into a single implicit+ * volume so nothing is dropped. Throws ERR_NO_PROSE when no issue has drafted+ * prose.+ */+export async function gatherProse(seriesId) {+ const series = await getSeries(seriesId);+ // MANUSCRIPT_STAGES (the default) already excludes `idea` — so we never+ // export an outline as if it were finished prose.+ const sections = await collectManuscriptSections(seriesId);+ if (!sections.length) {+ throw makeErr(+ 'No drafted prose to export — write or import a manuscript on at least one issue first.',+ ERR_NO_PROSE,+ );+ }+ const seasons = await listSeasons(seriesId);+ const volumes = groupIntoVolumes(sections, seasons);+ return { series, sections, volumes };+}++/**+ * Group ordered sections into volumes by seasonId, preserving section order.+ * Season order comes from the series' `seasons[]` (by `number` then order of+ * appearance); an unknown/absent seasonId collapses into one trailing+ * "Unassigned" volume. When the series has zero seasons every section lands in a+ * single untitled volume. Pure — exported via __testing.+ */+export function groupIntoVolumes(sections, seasons = []) {+ const seasonById = new Map((seasons || []).map((s) => [s.id, s]));+ const buckets = new Map(); // seasonId|'__none__' → { season, sections }+ for (const sec of sections) {+ const key = sec.seasonId && seasonById.has(sec.seasonId) ? sec.seasonId : '__none__';+ if (!buckets.has(key)) buckets.set(key, { season: seasonById.get(sec.seasonId) || null, sections: [] });+ buckets.get(key).sections.push(sec);+ }+ // Order volumes by the season list's order; the implicit "__none__" bucket+ // always sorts last.+ const ordered = [];+ for (const s of (seasons || [])) {+ if (buckets.has(s.id)) ordered.push(buckets.get(s.id));+ }+ if (buckets.has('__none__')) ordered.push(buckets.get('__none__'));+ // A series whose sections all landed in __none__ and had no season match →+ // just that one bucket. Number volumes sequentially for display.+ return ordered.map((b, idx) => ({+ id: b.season?.id || `__vol-${idx + 1}`,+ number: b.season?.number || idx + 1,+ title: b.season?.title || (ordered.length > 1 ? `Volume ${idx + 1}` : ''),+ sections: b.sections,+ }));+}++// ---------------------------------------------------------------------------+// 1) Compiled manuscript (Markdown)+// ---------------------------------------------------------------------------++/**+ * Build the compiled-manuscript Markdown string: YAML front matter (title /+ * author / date), then each volume as a `# Volume` break, then each issue as a+ * `## Chapter` heading followed by its prose. Single-volume series omit the+ * volume break. Pure over `{ series, volumes }` — exported via __testing.+ */+export function buildManuscriptMarkdown({ series, volumes }, settings) {+ const cfg = settings || resolveExportSettings(series);+ const lines = [];+ lines.push('---');+ lines.push(`title: ${yamlValue(cfg.titlePageTitle)}`);+ if (cfg.titlePageSubtitle) lines.push(`subtitle: ${yamlValue(cfg.titlePageSubtitle)}`);+ if (cfg.titlePageAuthor) lines.push(`author: ${yamlValue(cfg.titlePageAuthor)}`);+ lines.push(`date: ${new Date().toISOString().slice(0, 10)}`);+ lines.push('---');+ lines.push('');+ if (cfg.dedication) {+ lines.push(`> ${cfg.dedication.replace(/\n/g, '\n> ')}`);+ lines.push('');+ }+ const multiVolume = volumes.length > 1;+ for (const vol of volumes) {+ if (multiVolume) {+ lines.push(`# ${vol.title || `Volume ${vol.number}`}`);+ lines.push('');+ }+ for (const sec of vol.sections) {+ const heading = sec.title ? `Chapter ${sec.number} — ${sec.title}` : `Chapter ${sec.number}`;+ lines.push(`## ${heading}`);+ lines.push('');+ lines.push((sec.content || '').trim());+ lines.push('');+ }+ }+ return `${lines.join('\n').trimEnd()}\n`;+}++const yamlValue = (v) => {+ const s = String(v ?? '');+ // Quote when the value could confuse a YAML parser (colons, leading specials).+ return /[:#\-\[\]{}&*!|>'"%@`]/.test(s) ? JSON.stringify(s) : s;+};++export async function buildManuscriptFile(seriesId) {+ const { series, volumes } = await gatherProse(seriesId);+ const settings = resolveExportSettings(series);+ const markdown = buildManuscriptMarkdown({ series, volumes }, settings);+ return {+ text: markdown,+ filename: `${slugifyForFilename(series.name || 'series')}-manuscript.md`,+ };+}++// ---------------------------------------------------------------------------+// 2) ePub (OCF container)+// ---------------------------------------------------------------------------++const escapeXml = (s) => String(s ?? '')+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');++// Render one section's plain-text prose into XHTML paragraphs. Blank-line-+// separated blocks become <p>; single newlines inside a block become <br/>.+export function proseToXhtmlBody(content) {+ const blocks = String(content || '').split(/\n{2,}/).map((b) => b.trim()).filter(Boolean);+ if (!blocks.length) return '<p></p>';+ return blocks.map((b) => `<p>${escapeXml(b).replace(/\n/g, '<br/>')}</p>`).join('\n');+}++// One XHTML chapter document for a whole volume (its chapters stacked). A+// volume-title header is emitted only for multi-volume books.+export function buildChapterXhtml(vol, { multiVolume }) {+ const parts = [];+ parts.push('<?xml version="1.0" encoding="UTF-8"?>');+ parts.push('<!DOCTYPE html>');+ parts.push('<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">');+ parts.push(`<head><title>${escapeXml(vol.title || `Volume ${vol.number}`)}</title>`);+ parts.push('<link rel="stylesheet" type="text/css" href="style.css"/></head>');+ parts.push('<body>');+ if (multiVolume) parts.push(`<h1 class="volume-title">${escapeXml(vol.title || `Volume ${vol.number}`)}</h1>`);+ for (const sec of vol.sections) {+ const heading = sec.title ? `Chapter ${sec.number} — ${sec.title}` : `Chapter ${sec.number}`;+ parts.push(`<section epub:type="chapter" id="ch-${escapeXml(sec.issueId)}">`);+ parts.push(`<h2 class="chapter-title">${escapeXml(heading)}</h2>`);+ parts.push(proseToXhtmlBody(sec.content));+ parts.push('</section>');+ }+ parts.push('</body></html>');+ return parts.join('\n');+}++// The OPF package document (EPUB 3): metadata + manifest + spine.+export function buildOpf({ series, settings, volumes, coverImage, bookId }) {+ const items = [];+ const spine = [];+ items.push('<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>');+ items.push('<item id="style" href="style.css" media-type="text/css"/>');+ if (coverImage) {+ items.push(`<item id="cover-image" href="${escapeXml(coverImage.name)}" media-type="${coverImage.mediaType}" properties="cover-image"/>`);+ }+ volumes.forEach((vol, idx) => {+ const id = `vol${idx + 1}`;+ items.push(`<item id="${id}" href="${id}.xhtml" media-type="application/xhtml+xml"/>`);+ spine.push(`<itemref idref="${id}"/>`);+ });+ const modified = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');+ const lines = [];+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');+ lines.push('<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id">');+ lines.push('<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">');+ lines.push(`<dc:identifier id="book-id">${escapeXml(bookId)}</dc:identifier>`);+ lines.push(`<dc:title>${escapeXml(settings.titlePageTitle)}</dc:title>`);+ lines.push('<dc:language>en</dc:language>');+ if (settings.titlePageAuthor) lines.push(`<dc:creator>${escapeXml(settings.titlePageAuthor)}</dc:creator>`);+ if (settings.titlePageSubtitle) lines.push(`<dc:description>${escapeXml(settings.titlePageSubtitle)}</dc:description>`);+ lines.push(`<meta property="dcterms:modified">${modified}</meta>`);+ if (coverImage) lines.push('<meta name="cover" content="cover-image"/>');+ lines.push('</metadata>');+ lines.push(`<manifest>${items.join('')}</manifest>`);+ lines.push(`<spine>${spine.join('')}</spine>`);+ lines.push('</package>');+ return lines.join('\n');+}++// The EPUB 3 nav document (table of contents).+export function buildNavXhtml({ settings, volumes }) {+ const multiVolume = volumes.length > 1;+ const lis = [];+ volumes.forEach((vol, idx) => {+ const href = `vol${idx + 1}.xhtml`;+ const label = multiVolume ? (vol.title || `Volume ${vol.number}`) : (settings.titlePageTitle || 'Text');+ lis.push(`<li><a href="${href}">${escapeXml(label)}</a></li>`);+ });+ return [+ '<?xml version="1.0" encoding="UTF-8"?>',+ '<!DOCTYPE html>',+ '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">',+ `<head><title>${escapeXml(settings.titlePageTitle)}</title></head>`,+ '<body>',+ '<nav epub:type="toc" id="toc"><h1>Contents</h1>',+ `<ol>${lis.join('')}</ol>`,+ '</nav>',+ '</body></html>',+ ].join('\n');+}++const EPUB_CSS = `body { font-family: serif; line-height: 1.5; margin: 5%; }+h1.volume-title { text-align: center; margin: 2em 0; page-break-before: always; }+h2.chapter-title { text-align: center; margin: 2em 0 1em; page-break-before: always; }+p { margin: 0; text-indent: 1.5em; }+p:first-of-type { text-indent: 0; }+`;++const CONTAINER_XML = `<?xml version="1.0" encoding="UTF-8"?>+<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">+ <rootfiles>+ <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>+ </rootfiles>+</container>`;++// Resolve the series cover image (if any) into `{ name, mediaType, bytes }` for+// the ePub manifest. `series.coverImage` is a plain filename string (stamped by+// the cover filename hooks / setSeriesCoverImage). Returns null when there's no+// rendered cover — the ePub is still valid without one.+async function resolveCoverImage(series) {+ const filename = typeof series?.coverImage === 'string' && series.coverImage ? series.coverImage : null;+ if (!filename) return null;+ const bytes = await readImageFromMedia(filename, { subject: 'series cover image' }).catch(() => null);+ if (!bytes) return null;+ const kind = detectImageKind(bytes, filename);+ if (!kind) return null;+ const mediaType = kind === 'png' ? 'image/png' : 'image/jpeg';+ const ext = kind === 'png' ? 'png' : 'jpg';+ return { name: `cover.${ext}`, mediaType, bytes };+}++/**+ * Build the ePub as a Buffer. The OCF spec requires the `mimetype` entry to be+ * first and stored (uncompressed) — everything else is deflated. Returns+ * `{ bytes, filename }`.+ */+export async function buildEpub(seriesId) {+ const { series, volumes } = await gatherProse(seriesId);+ const settings = resolveExportSettings(series);+ const bookId = `urn:portos:series:${series.id}`;+ const coverImage = await resolveCoverImage(series);+ const multiVolume = volumes.length > 1;++ // OCF requires `mimetype` to be the FIRST entry, stored (uncompressed). It is+ // first in this list, and its 20-byte payload never shrinks under deflate, so+ // `createZip`'s "keep deflate only when smaller" rule stores it — satisfying+ // the spec while the bulkier text entries below still compress.+ const entries = [+ { name: 'mimetype', data: 'application/epub+zip' },+ { name: 'META-INF/container.xml', data: CONTAINER_XML },+ { name: 'OEBPS/content.opf', data: buildOpf({ series, settings, volumes, coverImage, bookId }) },+ { name: 'OEBPS/nav.xhtml', data: buildNavXhtml({ settings, volumes }) },+ { name: 'OEBPS/style.css', data: EPUB_CSS },+ ...volumes.map((vol, idx) => ({ name: `OEBPS/vol${idx + 1}.xhtml`, data: buildChapterXhtml(vol, { multiVolume }) })),+ ];+ if (coverImage) entries.push({ name: `OEBPS/${coverImage.name}`, data: coverImage.bytes });+ const bytes = createZip(entries, { compress: true });++ return {+ bytes,+ filename: `${slugifyForFilename(series.name || 'series')}.epub`,+ };+}++// ---------------------------------------------------------------------------+// 3) Print-interior PDF+// ---------------------------------------------------------------------------++// Greedy word-wrap a paragraph to `maxWidth` at `size` using pdf-lib font+// metrics. Returns an array of lines. Pure over the font (exported via+// __testing with a stub `widthOfTextAtSize`).+export function wrapText(text, font, size, maxWidth) {+ const words = String(text || '').split(/\s+/).filter(Boolean);+ const lines = [];+ let line = '';+ for (const word of words) {+ const candidate = line ? `${line} ${word}` : word;+ if (font.widthOfTextAtSize(candidate, size) <= maxWidth || !line) {+ line = candidate;+ } else {+ lines.push(line);+ line = word;+ }+ }+ if (line) lines.push(line);+ return lines;+}++const PDF_FONT_MAP = {+ times: { regular: StandardFonts.TimesRoman, bold: StandardFonts.TimesRomanBold, italic: StandardFonts.TimesRomanItalic },+ helvetica: { regular: StandardFonts.Helvetica, bold: StandardFonts.HelveticaBold, italic: StandardFonts.HelveticaOblique },+ courier: { regular: StandardFonts.Courier, bold: StandardFonts.CourierBold, italic: StandardFonts.CourierOblique },+};++/**+ * Build the print-interior PDF as a Uint8Array. Trade-format interior: title+ * page → per-volume/-chapter body with running heads (author verso, title+ * recto) and page numbers, wrapping the prose to the text block. Reuses the+ * `pdf-lib` plumbing from volumePdf.js. Returns `{ bytes, pageCount, filename }`.+ */+export async function buildProsePdf(seriesId) {+ const { series, volumes } = await gatherProse(seriesId);+ const settings = resolveExportSettings(series);+ const trim = TRIM_SIZES[settings.trimSize] || TRIM_SIZES[DEFAULT_TRIM_SIZE];+ const { width: pageW, height: pageH } = trim;++ const pdf = await PDFDocument.create();+ pdf.setTitle(settings.titlePageTitle);+ if (settings.titlePageAuthor) pdf.setAuthor(settings.titlePageAuthor);+ if (settings.titlePageSubtitle) pdf.setSubject(settings.titlePageSubtitle);+ pdf.setProducer('PortOS');++ const fontKey = PDF_FONT_MAP[settings.interiorFont] ? settings.interiorFont : 'times';+ const font = await pdf.embedFont(PDF_FONT_MAP[fontKey].regular);+ const fontBold = await pdf.embedFont(PDF_FONT_MAP[fontKey].bold);++ const margin = 54; // 0.75"+ const bodySize = 11;+ const lineHeight = bodySize * 1.4;+ const textW = pageW - margin * 2;+ const topY = pageH - margin;+ const bottomY = margin + 24; // reserve room for the page-number footer+ const runningHead = settings.titlePageTitle;+ const author = settings.titlePageAuthor;++ let pageNo = 0;+ let pageCount = 0;++ // --- Title page (no running head / number) ---+ const title = pdf.addPage([pageW, pageH]);+ pageCount += 1;+ {+ let cy = pageH * 0.62;+ const centered = (text, sz, f) => {+ const w = f.widthOfTextAtSize(text, sz);+ title.drawText(text, { x: (pageW - w) / 2, y: cy, size: sz, font: f, color: rgb(0, 0, 0) });+ cy -= sz * 1.6;+ };+ centered(settings.titlePageTitle, 24, fontBold);+ if (settings.titlePageSubtitle) centered(settings.titlePageSubtitle, 13, font);+ cy -= 24;+ if (settings.titlePageAuthor) centered(settings.titlePageAuthor, 14, font);+ if (settings.dedication) {+ cy = pageH * 0.25;+ for (const dl of wrapText(settings.dedication, font, 11, textW * 0.8)) {+ const w = font.widthOfTextAtSize(dl, 11);+ title.drawText(dl, { x: (pageW - w) / 2, y: cy, size: 11, font, color: rgb(0.3, 0.3, 0.3) });+ cy -= 11 * 1.4;+ }+ }+ if (settings.copyright) {+ const w = font.widthOfTextAtSize(settings.copyright, 8);+ title.drawText(settings.copyright.slice(0, 120), { x: (pageW - w) / 2, y: margin + 8, size: 8, font, color: rgb(0.4, 0.4, 0.4) });+ }+ }++ const multiVolume = volumes.length > 1;+ let page = null;+ let y = 0;++ const footer = (p, n) => {+ const s = String(n);+ const w = font.widthOfTextAtSize(s, 9);+ p.drawText(s, { x: (pageW - w) / 2, y: margin, size: 9, font, color: rgb(0.4, 0.4, 0.4) });+ };+ const header = (p, text) => {+ if (!text) return;+ const w = font.widthOfTextAtSize(text, 8);+ p.drawText(text, { x: (pageW - w) / 2, y: pageH - margin + 6, size: 8, font, color: rgb(0.5, 0.5, 0.5) });+ };+ const newPage = () => {+ // Running head alternates: verso (even page number) = author, recto = title.+ pageNo += 1;+ page = pdf.addPage([pageW, pageH]);+ pageCount += 1;+ footer(page, pageNo);+ header(page, pageNo % 2 === 0 ? author : runningHead);+ y = topY;+ };+ const ensureSpace = (needed) => {+ if (!page || y - needed < bottomY) newPage();+ };++ for (const vol of volumes) {+ if (multiVolume) {+ newPage();+ y = pageH * 0.5;+ const vt = vol.title || `Volume ${vol.number}`;+ const w = fontBold.widthOfTextAtSize(vt, 20);+ page.drawText(vt, { x: (pageW - w) / 2, y, size: 20, font: fontBold, color: rgb(0, 0, 0) });+ y = bottomY; // force a fresh page for the first chapter+ }+ for (const sec of vol.sections) {+ // Chapter opener starts on a fresh page.+ newPage();+ y = pageH * 0.72;+ const heading = sec.title ? `Chapter ${sec.number} — ${sec.title}` : `Chapter ${sec.number}`;+ for (const hl of wrapText(heading, fontBold, 16, textW)) {+ const w = fontBold.widthOfTextAtSize(hl, 16);+ page.drawText(hl, { x: (pageW - w) / 2, y, size: 16, font: fontBold, color: rgb(0, 0, 0) });+ y -= 16 * 1.4;+ }+ y -= lineHeight;+ const paras = String(sec.content || '').split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);+ for (const para of paras) {+ const wrapped = wrapText(para, font, bodySize, textW);+ for (let i = 0; i < wrapped.length; i += 1) {+ ensureSpace(lineHeight);+ // First-line indent for continued paragraphs (not the chapter's first).+ const indent = i === 0 ? 18 : 0;+ page.drawText(wrapped[i], { x: margin + indent, y, size: bodySize, font, color: rgb(0, 0, 0) });+ y -= lineHeight;+ }+ y -= lineHeight * 0.3; // paragraph gap+ }+ }+ }++ const bytes = await pdf.save();+ return {+ bytes,+ pageCount,+ filename: `${slugifyForFilename(series.name || 'series')}-interior.pdf`,+ };+}++export const __testing = {+ groupIntoVolumes,+ buildManuscriptMarkdown,+ proseToXhtmlBody,+ buildChapterXhtml,+ buildOpf,+ buildNavXhtml,+ wrapText,+};diff --git a/server/services/pipeline/proseExport.test.js b/server/services/pipeline/proseExport.test.jsnew file mode 100644index 0000000000..51a878b00f--- /dev/null+++ b/server/services/pipeline/proseExport.test.js@@ -0,0 +1,222 @@+/**+ * proseExport.test.js — pure-helper tests for the prose-series export (#2181):+ * volume grouping/order, manuscript-markdown shape, XHTML/OPF/nav ePub parts,+ * word-wrap, and a full ePub zip round-trip through the parser.+ */++import { describe, it, expect } from 'vitest';+import { Readable, Writable } from 'stream';+import { __testing } from './proseExport.js';+import { createZip } from '../../lib/zipWriter.js';+import { parseZip } from '../../lib/zipStream.js';+import {+ buildOpf as buildOpfExport,+ buildNavXhtml as buildNavXhtmlExport,+ buildChapterXhtml as buildChapterXhtmlExport,+} from './proseExport.js';++const {+ groupIntoVolumes,+ buildManuscriptMarkdown,+ proseToXhtmlBody,+ buildChapterXhtml,+ buildOpf,+ buildNavXhtml,+ wrapText,+} = __testing;++const section = (over = {}) => ({+ issueId: 'i1', seasonId: null, number: 1, title: 'One', stageId: 'prose', content: 'Body one.', ...over,+});++describe('groupIntoVolumes', () => {+ it('collapses everything into one untitled volume when the series has no seasons', () => {+ const sections = [section({ number: 1 }), section({ issueId: 'i2', number: 2, title: 'Two' })];+ const volumes = groupIntoVolumes(sections, []);+ expect(volumes).toHaveLength(1);+ expect(volumes[0].title).toBe(''); // single volume → no volume break+ expect(volumes[0].sections.map((s) => s.number)).toEqual([1, 2]);+ });++ it('groups by seasonId and orders volumes by the season list, __none__ last', () => {+ const seasons = [+ { id: 'sB', number: 2, title: 'Book Two' },+ { id: 'sA', number: 1, title: 'Book One' },+ ];+ const sections = [+ section({ issueId: 'i1', number: 1, seasonId: 'sA' }),+ section({ issueId: 'i2', number: 2, seasonId: 'sB' }),+ section({ issueId: 'i3', number: 3, seasonId: null }), // orphan → __none__+ ];+ const volumes = groupIntoVolumes(sections, seasons);+ // Season-list order: sB then sA, then the orphan bucket.+ expect(volumes.map((v) => v.title)).toEqual(['Book Two', 'Book One', 'Volume 3']);+ expect(volumes[0].sections.map((s) => s.number)).toEqual([2]);+ expect(volumes[2].sections.map((s) => s.number)).toEqual([3]);+ });++ it('routes an unknown seasonId into the trailing __none__ bucket (nothing dropped)', () => {+ const seasons = [{ id: 'sA', number: 1, title: 'A' }];+ const sections = [section({ number: 1, seasonId: 'ghost' })];+ const volumes = groupIntoVolumes(sections, seasons);+ expect(volumes).toHaveLength(1);+ expect(volumes[0].sections.map((s) => s.number)).toEqual([1]);+ });+});++describe('buildManuscriptMarkdown', () => {+ const settings = {+ trimSize: 'us-trade', interiorFont: 'times',+ titlePageTitle: 'My Book', titlePageSubtitle: 'A Tale', titlePageAuthor: 'Ada',+ copyright: '', dedication: 'For no one.',+ };++ it('emits YAML front matter, no volume break for a single volume, and chapter headings', () => {+ const volumes = groupIntoVolumes([section({ number: 1, title: 'Beginnings' })], []);+ const md = buildManuscriptMarkdown({ series: { name: 'My Book' }, volumes }, settings);+ expect(md).toMatch(/^---\ntitle: My Book\n/);+ expect(md).toContain('author: Ada');+ expect(md).toContain('> For no one.');+ expect(md).not.toMatch(/^# /m); // no volume-level heading for one volume+ expect(md).toContain('## Chapter 1 — Beginnings');+ expect(md).toContain('Body one.');+ });++ it('emits a # volume break for multi-volume series', () => {+ const seasons = [{ id: 'sA', number: 1, title: 'Book One' }, { id: 'sB', number: 2, title: 'Book Two' }];+ const sections = [+ section({ issueId: 'i1', number: 1, seasonId: 'sA' }),+ section({ issueId: 'i2', number: 2, seasonId: 'sB', title: 'Two' }),+ ];+ const volumes = groupIntoVolumes(sections, seasons);+ const md = buildManuscriptMarkdown({ series: { name: 'X' }, volumes }, settings);+ expect(md).toContain('# Book One');+ expect(md).toContain('# Book Two');+ });+});++describe('proseToXhtmlBody', () => {+ it('splits blank-line blocks into <p> and single newlines into <br/>', () => {+ const body = proseToXhtmlBody('First para.\nStill first.\n\nSecond para.');+ expect(body).toBe('<p>First para.<br/>Still first.</p>\n<p>Second para.</p>');+ });+ it('escapes XML special characters', () => {+ expect(proseToXhtmlBody('A & B < C > "D"')).toContain('A & B < C > "D"');+ });+ it('returns an empty paragraph for empty content', () => {+ expect(proseToXhtmlBody('')).toBe('<p></p>');+ });+});++describe('buildChapterXhtml / buildNavXhtml / buildOpf', () => {+ const vol = { id: 'sA', number: 1, title: 'Book One', sections: [section({ number: 3, title: 'Three', content: 'Prose.' })] };++ it('renders a valid-looking XHTML chapter with a chapter heading', () => {+ const xhtml = buildChapterXhtml(vol, { multiVolume: true });+ expect(xhtml).toContain('<?xml version="1.0" encoding="UTF-8"?>');+ expect(xhtml).toContain('<h1 class="volume-title">Book One</h1>');+ expect(xhtml).toContain('<h2 class="chapter-title">Chapter 3 — Three</h2>');+ expect(xhtml).toContain('<p>Prose.</p>');+ });++ it('omits the volume header for a single-volume book', () => {+ const xhtml = buildChapterXhtml(vol, { multiVolume: false });+ expect(xhtml).not.toContain('volume-title');+ });++ it('builds an OPF manifest + spine covering every volume and marks the cover', () => {+ const opf = buildOpf({+ series: { id: 's1' },+ settings: { titlePageTitle: 'T', titlePageAuthor: 'A', titlePageSubtitle: '' },+ volumes: [vol, { ...vol, id: 'sB' }],+ coverImage: { name: 'cover.png', mediaType: 'image/png' },+ bookId: 'urn:portos:series:s1',+ });+ expect(opf).toContain('<dc:title>T</dc:title>');+ expect(opf).toContain('<dc:creator>A</dc:creator>');+ expect(opf).toContain('<dc:identifier id="book-id">urn:portos:series:s1</dc:identifier>');+ expect(opf).toContain('properties="cover-image"');+ expect(opf).toContain('<meta name="cover" content="cover-image"/>');+ expect((opf.match(/<itemref /g) || []).length).toBe(2);+ });++ it('nav doc lists each volume title for a multi-volume book', () => {+ const nav = buildNavXhtml({ settings: { titlePageTitle: 'T' }, volumes: [vol, { ...vol, id: 'sB', title: 'Book Two' }] });+ expect(nav).toContain('Book One');+ expect(nav).toContain('Book Two');+ expect(nav).toContain('<nav epub:type="toc"');+ });++ // The exported (non-__testing) builders are the same functions.+ it('exports the builders at the module top level too', () => {+ expect(buildOpfExport).toBe(buildOpf);+ expect(buildNavXhtmlExport).toBe(buildNavXhtml);+ expect(buildChapterXhtmlExport).toBe(buildChapterXhtml);+ });+});++describe('wrapText', () => {+ // Stub font: each char is 10 units wide.+ const font = { widthOfTextAtSize: (t) => t.length * 10 };+ it('wraps words to fit maxWidth', () => {+ const lines = wrapText('aa bb cc dd', font, 1, 55); // 55 units → 5 chars/line+ expect(lines).toEqual(['aa bb', 'cc dd']);+ });+ it('never drops a word longer than the line (keeps it on its own line)', () => {+ const lines = wrapText('supercalifragilistic ok', font, 1, 50);+ expect(lines[0]).toBe('supercalifragilistic');+ expect(lines[1]).toBe('ok');+ });+ it('returns [] for empty text', () => {+ expect(wrapText('', font, 1, 100)).toEqual([]);+ });+});++// Round-trip: assemble an ePub-shaped zip and parse it back through the+// production parser, asserting order + content; the OCF "mimetype stored" rule+// is checked against the raw local-header bytes (the parser doesn't surface the+// compression method).+function collectEntries(zipBuf) {+ return new Promise((resolve, reject) => {+ const results = [];+ const promises = [];+ const parser = parseZip();+ parser.on('entry', (entry) => {+ promises.push(new Promise((res) => {+ const chunks = [];+ const sink = new Writable({ write(chunk, _, cb) { chunks.push(chunk); cb(); } });+ sink.on('finish', () => { results.push({ path: entry.path, data: Buffer.concat(chunks) }); res(); });+ entry.pipe(sink);+ }));+ });+ parser.on('close', () => Promise.all(promises).then(() => resolve(results), reject));+ parser.on('error', reject);+ Readable.from([zipBuf]).pipe(parser);+ });+}++describe('ePub OCF zip round-trip', () => {+ it('keeps mimetype first + stored and includes the container + OPF', async () => {+ const buf = createZip([+ { name: 'mimetype', data: 'application/epub+zip' },+ { name: 'META-INF/container.xml', data: '<container/>' },+ { name: 'OEBPS/content.opf', data: '<package/>' },+ { name: 'OEBPS/vol1.xhtml', data: buildChapterXhtml({ number: 1, title: '', sections: [section()] }, { multiVolume: false }) },+ ], { compress: true });++ // OCF invariant: the first local file header is `mimetype`, method 0 (stored).+ // Local header layout: sig(4) ver(2) flags(2) method(2 @ offset 8) …+ expect(buf.readUInt32LE(0)).toBe(0x04034b50);+ expect(buf.readUInt16LE(8)).toBe(0); // compression method 0 = stored+ const firstNameLen = buf.readUInt16LE(26);+ expect(buf.slice(30, 30 + firstNameLen).toString('utf8')).toBe('mimetype');++ const entries = await collectEntries(buf);+ expect(entries[0].path).toBe('mimetype');+ const byPath = Object.fromEntries(entries.map((e) => [e.path, e.data.toString('utf8')]));+ expect(byPath.mimetype).toBe('application/epub+zip');+ expect(byPath['META-INF/container.xml']).toBe('<container/>');+ expect(byPath['OEBPS/content.opf']).toBe('<package/>');+ expect(byPath['OEBPS/vol1.xhtml']).toContain('<p>Body one.</p>');+ });+});diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 1c51000f71..1404073a69 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -17,6 +17,7 @@ import { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';import { sanitizeStyleGuide } from '../../lib/styleGuide.js';+import { sanitizeProseExportSettings } from '../../lib/proseExportSettings.js';import { sanitizeSeverityWeights, sanitizeBlockingSeverities } from '../../lib/editorial/severityConfig.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';@@ -322,6 +323,14 @@ const sanitizeSeries = (raw) => {// sanitizeStyleGuide returns null when empty so existing series.json files// (which predate this field) migrate forward without a writer pass.styleGuide: sanitizeStyleGuide(raw.styleGuide),+ // Per-series prose-export settings (#2181) — trim size, interior font, and+ // title-page fields for the compiled-manuscript / ePub / print-interior-PDF+ // exports. `sanitizeProseExportSettings` returns null when nothing is set so+ // existing series.json files (which predate this field) migrate forward+ // without a writer pass; first save backfills. Additive + gracefully+ // degrading (a pre-feature peer's sanitizeSeries drops it), wire-gated at+ // pipelineSeries v12 so an older peer can't strip-then-LWW it back.+ exportSettings: sanitizeProseExportSettings(raw.exportSettings),titleLogo: trimTo(raw.titleLogo, TITLE_LOGO_MAX),// Derived cover thumbnail filename (a rendered volume/issue cover). Stamped// by the cover filename hooks + the one-time boot backfill via@@ -598,6 +607,10 @@ export async function updateSeries(id, patch = {}) {// Wholesale replace — sanitizeStyleGuide normalizes an empty object back// to null (clear); omission preserves. Mirrors the arc/readerMap pattern....('styleGuide' in patch ? { styleGuide: patch.styleGuide } : {}),+ // Per-series prose-export settings (#2181). Wholesale replace —+ // `null`/`{}` clears (defaults apply); omission preserves.+ // sanitizeProseExportSettings normalizes an all-default object back to null.+ ...('exportSettings' in patch ? { exportSettings: patch.exportSettings } : {}),...('titleLogo' in patch ? { titleLogo: patch.titleLogo } : {}),...('author' in patch ? { author: patch.author } : {}),...('authorId' in patch ? { authorId: patch.authorId } : {}),@@ -834,7 +847,7 @@ async function cascadeDeleteSideEffects(id) {// consult the RAW remote payload to tell the two apart: key absent → preserve// local; key present (even null/empty) → honor the intentional clear. Mirrors// the `universeId` hierarchy guard. See issue #1361.-const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig', 'severityWeights', 'blockingSeverities'];+const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig', 'severityWeights', 'blockingSeverities', 'exportSettings'];// Additive sub-fields nested inside `arc`. A peer that predates these (readerMap// shipped at schema v2, tickingClock at #1289/v3, foreshadowing at #2172/v10)// still sends an `arc` object — just without these keys — so the erasure fordiff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 9fa4f55f31..415c44fd3d 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -2333,7 +2333,7 @@ describe('sharing round-trip', () => {const result = await importer.processManifest(bucket.id, exp.filename);expect(result.skipped).toBe(true);expect(result.reason).toBe('portos-schema-ahead');- expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 11 }]);+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 12 }]);expect(result.producedByVersion).toBe('99.0.0');// Series stayed tombstoned (or absent) — apply was refused.await expect(series.getSeries(s.id)).rejects.toThrow();