import type { TypstState } from "@typbase/engine"; import type { WorkspaceStore } from "@typbase/storage"; import type { PageMeta } from "@typbase/typing"; import { stripCellAttributes } from "@typbase/codemirror"; import { escapeHtml, fileBase, fontFiles, fontPackFiles, inlineBlobs, renderFailure, setsPageConfiguration, styleExportHtml, type ExportFile, type ExportOptions, } from "~/lib/exportPage"; import { pageContext, pageContextBinding, typstContextValue } from "~/lib/pageContext"; import { pluginBundleSummary, pluginProjectFiles } from "~/lib/pluginBundle"; import { EXPORT_TEXT_SCALE, publishPrelude, publishSyntaxTheme, publishThemePalette, } from "~/lib/publishPrelude"; import { renderInWorker, setPublishRequestStore, type RenderOutcome } from "~/lib/renderWorker"; export interface WorkspaceExportOptions extends ExportOptions { /** Write each selected page's source and artifacts. */ separate: boolean; /** Write one merged document from the selected pages. */ combined: boolean; } /** * Bundle stem for a page's rendered artifacts. Sources keep their `page.path`. * Renders live under `artifacts/` so the two never collide. */ function artifactStem(path: string): string { return `artifacts/${path.replace(/\.typ$/i, "")}`; } export async function buildWorkspaceExport( store: WorkspaceStore, pageIds: string[], options: WorkspaceExportOptions, typstState?: TypstState, ): Promise<{ name: string; files: ExportFile[] }> { const pages = pageIds .map((id) => store.getPage(id)) .filter((page): page is PageMeta => Boolean(page)) .sort((a, b) => a.path.localeCompare(b.path)); if (!pages.length) throw new Error("Select at least one page."); if (!options.separate && !options.combined) { throw new Error("Choose per-page files, a combined document, or both."); } const themeOptions = { theme: options.theme, pageSize: options.pageSize, } as const; const palette = publishThemePalette(store.getSettings(), themeOptions); const encoder = new TextEncoder(); const files: ExportFile[] = []; const names = new Set(); const payloads = new Map(); const index: Array<{ title: string; href: string }> = []; const addFile = (file: ExportFile): void => { if (names.has(file.name)) { throw new Error(`Two exported files would both be named ${file.name}; rename one page.`); } names.add(file.name); files.push(file); }; // Support files can arrive from both the render request payloads and the // plugin/project inventory. They describe the same generated source, so the // first copy wins. Page files still go through `addFile` and collide loudly. const addSupportFile = (file: ExportFile): void => { if (!names.has(file.name)) addFile(file); }; const collect = (outcome: RenderOutcome): void => { for (const payload of outcome.payloads) { // Packages were installed into the worker's world. The exported project // references them by spec instead of vendoring the tarball. if (payload.type === "package") continue; const bytes = payload.type === "file" ? payload.bytes : encoder.encode(payload.text); payloads.set(payload.path, { name: payload.path, bytes }); } }; setPublishRequestStore(store); const renderInto = async (input: { source: string; /** Virtual page path handed to the renderer. */ pagePath: string; /** Bundle path of the source file, mirroring the workspace tree. */ sourceName: string; /** Artifact stem under `artifacts/`. Sheet suffixes are appended. */ stem: string; /** The page's `note` binding. Empty for the combined document. */ context: string; /** Page id for `sys.inputs`. Null for the combined document. */ pageId: string | null; title?: string; }): Promise => { const { source, pagePath, sourceName, stem, context, pageId, title } = input; const htmlPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: false, textScale: EXPORT_TEXT_SCALE, context, }); const pagedPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: true, textScale: EXPORT_TEXT_SCALE, scaleMode: setsPageConfiguration(source) ? "text" : "document", context, }); if (options.html) { const rendered = await renderInWorker({ pagePath, source, prelude: htmlPrelude, wants: "html", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.html) { throw renderFailure(`The render produced no HTML for ${pagePath}`, rendered.diagnostics); } collect(rendered); addFile({ name: `${stem}.html`, bytes: encoder.encode(styleExportHtml(await inlineBlobs(rendered.html, store), palette)), }); if (title) index.push({ title, href: `${stem}.html` }); } if (options.pdf) { const rendered = await renderInWorker({ pagePath, source, prelude: pagedPrelude, wants: "pdf", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.pdf) { throw renderFailure(`The render produced no PDF for ${pagePath}`, rendered.diagnostics); } collect(rendered); addFile({ name: `${stem}.pdf`, bytes: rendered.pdf }); } if (options.svg) { const rendered = await renderInWorker({ pagePath, source, prelude: pagedPrelude, wants: "svg", merged: options.svgMerged, spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.svg?.length) { throw renderFailure( `The render produced no SVG pages for ${pagePath}`, rendered.diagnostics, ); } collect(rendered); const many = rendered.svg.length > 1; rendered.svg.forEach((svg, sheet) => { addFile({ name: `${stem}${many ? `-${sheet + 1}` : ""}.svg`, bytes: encoder.encode(svg), }); }); } if (options.project) { const projectSource = options.stripMarkers ? stripCellAttributes(source) : source; addFile({ name: sourceName, bytes: encoder.encode(`${pagedPrelude}\n${projectSource}`), }); } }; if (options.separate) { for (const page of pages) { const source = await store.loadPageText(page.id); await renderInto({ source, pagePath: page.path, sourceName: page.path, stem: artifactStem(page.path), context: pageContextBinding(store, page.id), pageId: page.id, title: page.title, }); } } if (options.combined) { const sources: string[] = []; for (const page of pages) { sources.push(await store.loadPageText(page.id)); } const htmlPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: false, textScale: EXPORT_TEXT_SCALE, }); const scalePages = !sources.some(setsPageConfiguration); const pagedPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: true, textScale: EXPORT_TEXT_SCALE, scaleMode: scalePages ? "none" : "text", }); // A combined document is one compile, so each page gets its own // `note` in a scoped block instead of a shared binding. const wrapper = (source: string, position: number, scale: boolean): string => { const page = pages[position]; if (!page) return source; const binding = ` let note = ${typstContextValue(pageContext(pages, page))}\n`; const body = scale ? ` scale(${EXPORT_TEXT_SCALE * 100}%, reflow: true)[\n${source}\n ]` : ` [\n${source}\n ]`; return `#{\n${binding}${body}\n}`; }; const paged = `${sources .map((source, position) => wrapper(source, position, scalePages)) .join("\n#context { pagebreak(weak: true) }\n")}\n`; const flowed = `${sources .map((source, position) => wrapper(source, position, false)) .join("\n\n#horizontalrule()\n\n")}\n`; const name = pages.every((page) => page.path.startsWith("daily/")) ? "daily" : "combined"; const pagePath = `${name}.typ`; const stem = `artifacts/${name}`; if (options.html) { const rendered = await renderInWorker({ pagePath, source: flowed, prelude: htmlPrelude, wants: "html", spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.html) { throw renderFailure("The combined render produced no HTML", rendered.diagnostics); } collect(rendered); addFile({ name: `${stem}.html`, bytes: encoder.encode(styleExportHtml(await inlineBlobs(rendered.html, store), palette)), }); index.unshift({ title: name, href: `${stem}.html` }); } if (options.pdf) { const rendered = await renderInWorker({ pagePath, source: paged, prelude: pagedPrelude, wants: "pdf", spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.pdf) { throw renderFailure("The combined render produced no PDF", rendered.diagnostics); } collect(rendered); addFile({ name: `${stem}.pdf`, bytes: rendered.pdf }); } if (options.svg) { const rendered = await renderInWorker({ pagePath, source: paged, prelude: pagedPrelude, wants: "svg", merged: options.svgMerged, spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.svg?.length) { throw renderFailure("The combined render produced no SVG pages", rendered.diagnostics); } collect(rendered); const many = rendered.svg.length > 1; rendered.svg.forEach((svg, sheet) => { addFile({ name: `${stem}${many ? `-${sheet + 1}` : ""}.svg`, bytes: encoder.encode(svg), }); }); } if (options.project) { const combined = options.stripMarkers ? stripCellAttributes(paged) : paged; addFile({ name: pagePath, bytes: encoder.encode(`${pagedPrelude}\n${combined}`), }); } } if (options.project) { if (typstState) { addFile({ name: "typbase/lib.typ", bytes: encoder.encode(typstState.typbaseLib()), }); } const syntax = await publishSyntaxTheme(store.getSettings(), themeOptions); addFile({ name: syntax.path, bytes: encoder.encode(syntax.text) }); for (const payload of payloads.values()) addSupportFile(payload); for (const plugin of await pluginProjectFiles(store)) { addSupportFile({ name: plugin.path, bytes: encoder.encode(plugin.text) }); } if (options.fonts) { for (const font of await fontFiles(store)) addFile(font); const sources = pages.map( (page) => `${pageContextBinding(store, page.id)}\n${store.getPageText(page.id)}`, ); for (const font of await fontPackFiles(sources)) addFile(font); } for (const file of editorConfigFiles()) { addFile({ name: file.name, bytes: encoder.encode(file.text) }); } } if (files.length > 1) { addFile({ name: "README.md", bytes: encoder.encode(buildWorkspaceReadme(pages.length, options)), }); if (index.length) { addFile({ name: "index.html", bytes: encoder.encode(buildWorkspaceIndex(index)), }); } } return { name: pages.length === 1 ? fileBase(pages[0]!.title, pages[0]!.path) : "workspace", files, }; } function buildWorkspaceIndex(entries: Array<{ title: string; href: string }>): string { const items = entries .map((entry) => `
  • ${escapeHtml(entry.title)}
  • `) .join("\n"); return ` Workspace export

    Workspace export

      ${items}
    `; } /** * Editor config so the bundle behaves the same in an external editor as it does * here. The one that matters is Tinymist's project root: every source imports * `/typbase/lib.typ`, and a root-absolute import only resolves against a root, * so without it every file opens with a wall of unresolved imports. * * Only written for a project export. A bundle of rendered artifacts is not * something anyone opens in an editor. */ function editorConfigFiles(): { name: string; text: string }[] { const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`; return [ { name: ".vscode/settings.json", text: json({ "tinymist.typstExtraArgs": ["--root", "."], }), }, { name: ".vscode/extensions.json", text: json({ recommendations: ["myriad-dreamin.tinymist"] }), }, { // Not editor-specific: the same line endings and indent whatever opens it. name: ".editorconfig", text: [ "root = true", "", "[*]", "charset = utf-8", "end_of_line = lf", "insert_final_newline = true", "indent_style = space", "indent_size = 2", "", ].join("\n"), }, ]; } function buildWorkspaceReadme(pageCount: number, options: WorkspaceExportOptions): string { const lines = [ "# Workspace export", "", `${pageCount} page${pageCount === 1 ? "" : "s"}, exported ${new Date().toISOString()}.`, "", "## Files", "", ]; if (options.separate) { lines.push( "- `artifacts/`: rendered HTML, PDF, and SVG, mirroring each page's path", "- `pages/`, `daily/`, ...: the page sources with the workspace prelude inlined", ); } if (options.combined) { lines.push("- `combined.*` or `daily.*`: the selected pages merged into one document"); } if (options.project) { lines.push("- `typbase/`: the library, referenced data and blobs, and optionally fonts"); const plugins = pluginBundleSummary(); if (plugins) lines.push(plugins); lines.push( "- `.vscode/`, `.editorconfig`: editor settings, including the Tinymist project root", ); } lines.push(""); if (options.project) { lines.push( "## Compiling the Typst source", "", "Compile from the extracted bundle root; the prelude imports `/typbase/lib.typ`:", "", "```sh", `typst compile --root .${options.fonts ? " --font-path typbase/fonts" : ""} pages/`, "```", "", "Tinymist needs the same root, because the prelude's import is root-absolute.", "`.vscode/settings.json` already sets it, so opening the bundle folder in VS Code", "works without configuring anything.", "", ); } return lines.join("\n"); }