main
1import { root } from "astro:config/server";
2import { fileURLToPath } from "node:url";
3import type { RehypePlugins } from "@astrojs/markdown-remark";
4import { NodeCompiler } from "@myriaddreamin/typst-ts-node-compiler";
5import { rehypeIt } from "astro-typst/dist/lib/rehype";
6import * as cheerio from "cheerio";
7import type { Root } from "hast";
8
9const rootPath = fileURLToPath(root);
10const $typst = NodeCompiler.create({
11 workspace: rootPath,
12 inputs: { "x-renderer": "tybios" },
13});
14
15export async function renderTypstToHtml(
16 mainfilePath: string,
17 plugins?: RehypePlugins,
18): Promise<string> {
19 const docRes = $typst.compileHtml({ mainFilePath: mainfilePath });
20 if (!docRes.result) {
21 docRes.printDiagnostics();
22 return "";
23 }
24 const doc = docRes.result;
25 const html = $typst.tryHtml(doc);
26 if (!html.result) {
27 html.printDiagnostics();
28 return "";
29 }
30 const hast = html.result.hast() as Root;
31 const rehypeRes = await rehypeIt(hast, plugins || []);
32 const $ = cheerio.load(rehypeRes.toString());
33
34 return $("body").html() || "";
35}
36
37export function renderTypstToPdf(mainfilePath: string): Buffer {
38 const docRes = $typst.compile({ mainFilePath: mainfilePath });
39 if (!docRes.result) {
40 docRes.printDiagnostics();
41 throw new Error("Failed to compile Typst document.");
42 }
43 const doc = docRes.result;
44 const pdf = $typst.pdf(doc);
45 return pdf;
46}