// 从 contrib/snippet 入口引入,才能拿到 TypstSnippet 的辅助能力(如 preloadFontData) import { $typst, TypstSnippet } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs'; let inited = false; const PROJECT_ROOT = '/proj'; /** * 初始化 typst.ts(浏览器 Wasm 版本)。 * * 说明: * - 这里用的是 “lite” 方案:Wasm 模块从 jsdelivr 加载,避免把 wasm 打进你的 bundle。 * - 这意味着需要联网才能首次完成 wasm 资源加载。 */ export async function ensureTypstInited() { if (inited) return; // 预加载中文字体(否则中文容易显示成方块/乱码)。 // 这里使用 public/fonts 下的字体文件,包括 Noto Sans TC 和 FSung 系列。 const fontUrls = [ '/fonts/NotoSerifCJKtc-Medium.otf', // '/fonts/FSung-1.ttf', // '/fonts/FSung-2.ttf', // '/fonts/FSung-3.ttf', // '/fonts/FSung-F.ttf', // '/fonts/FSung-m.ttf', // '/fonts/FSung-p.ttf', // '/fonts/FSung-X.ttf', ]; // 必须在 compiler 初始化前 use,否则不会生效 await Promise.all( fontUrls.map(async (url) => { try { const resp = await fetch(url); if (!resp.ok) throw new Error(`HTTP ${resp.status}`); const fontBytes = new Uint8Array(await resp.arrayBuffer()); $typst.use(TypstSnippet.preloadFontData(fontBytes)); } catch (e) { console.warn(`[typst] 字体加载失败:${url},中文可能显示异常:`, e); } }), ); // 初始化 Wasm 模块来源(来自 typst.ts 官方文档示例) $typst.setCompilerInitOptions({ getModule: () => ({ module_or_path: 'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm' }) as any, }); $typst.setRendererInitOptions({ getModule: () => ({ module_or_path: 'https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm' }) as any, }); inited = true; } export async function compileTypstToSvg(mainContent: string): Promise { await ensureTypstInited(); return await $typst.svg({ mainContent }); } function isTypFilePath(p: string) { return p.endsWith('.typ'); } function extractTypDependencies(content: string): string[] { // 只做最小解析:抓 #import/#include 后紧跟的字符串路径 const deps: string[] = []; const re = /#(?:import|include)\s+(?:"([^"]+)"|'([^']+)')/g; let m: RegExpExecArray | null; while ((m = re.exec(content))) { const p = (m[1] ?? m[2] ?? '').trim(); if (!p) continue; // 排除 typst 包导入等 if (p.startsWith('@')) continue; if (!isTypFilePath(p)) continue; deps.push(p); } return deps; } function resolveUrl(fromUrl: string, rel: string): string { // fromUrl 和 rel 都是类似 /xxx/yyy.typ 或 ../lib.typ // 用 URL 来做可靠的相对路径解析 const base = new URL(fromUrl, 'http://local'); const next = new URL(rel, base); return next.pathname; } function toProjectPath(urlPath: string): string { // 把 /public 下的请求路径映射到虚拟工程根目录 // 例如 /hlm.typ -> /proj/hlm.typ return `${PROJECT_ROOT}${urlPath}`; } export type TypstProject = { entryUrl: string; entryPath: string; files: Map; // projectPath -> content }; export async function loadTypstProjectFromPublic(entryUrl: string): Promise { await ensureTypstInited(); const entry = entryUrl.startsWith('/') ? entryUrl : `/${entryUrl}`; const visited = new Set(); // urlPath const files = new Map(); // projectPath -> content const queue: Array<{ urlPath: string }> = [{ urlPath: entry }]; while (queue.length) { const { urlPath } = queue.shift()!; if (visited.has(urlPath)) continue; visited.add(urlPath); const resp = await fetch(urlPath); if (!resp.ok) { throw new Error(`加载 typ 文件失败:${urlPath}(HTTP ${resp.status})`); } const text = await resp.text(); files.set(toProjectPath(urlPath), text); for (const dep of extractTypDependencies(text)) { const depUrl = resolveUrl(urlPath, dep); queue.push({ urlPath: depUrl }); } } return { entryUrl: entry, entryPath: toProjectPath(entry), files, }; } export async function compileTypstProjectToSvg( project: TypstProject, overrides?: Record, ) { await ensureTypstInited(); // 清空 shadow 文件,避免上次编译残留影响 await $typst.resetShadow(); // 写入项目所有文件 for (const [projectPath, content] of project.files.entries()) { const override = overrides?.[projectPath]; await $typst.addSource(projectPath, override ?? content); } // 写入 overrides 中可能新增的文件(不在 project.files 里) if (overrides) { for (const [projectPath, content] of Object.entries(overrides)) { if (!project.files.has(projectPath)) { await $typst.addSource(projectPath, content); } } } // 始终以入口文件编译(typst.app 的典型体验:编辑任意文件,但预览是整个项目的主入口) return await $typst.svg({ mainFilePath: project.entryPath }); }