import { Browser } from "playwright"; import MarkdownIt from "markdown-it"; import { PFiles } from "../file.ts"; function resolveChromiumPath(): string { const chromiumPath = Deno.env.get("CHROMIUM_PATH"); if (chromiumPath) { return chromiumPath; } throw new Error( [ "CHROMIUM_PATH is not set.", "Use the provided flake shell or set CHROMIUM_PATH manually.", 'Example: export CHROMIUM_PATH="$(command -v chromium)"', ].join("\n"), ); } export class DocuBuilder { html_pages: Array; browser: Browser | null; pfiles: PFiles | null = null; constructor() { this.html_pages = []; this.browser = null; } async with_browser() { const { chromium } = await import("playwright"); const browser = await chromium.launch({ executablePath: resolveChromiumPath(), headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"], }); this.browser = browser; } with_files_sync(dir: string) { this.pfiles = new PFiles(dir); } as_html_page() { this.html_pages = []; const MD = new MarkdownIt(); if (this.pfiles != null) { this.pfiles.pcolumes.forEach((colume) => { this.html_pages.push(`

${colume.name}

`); colume.pfiles.forEach((pfile) => { const html = MD.render(pfile.content); this.html_pages.push( `
${html}
`, ); }); }); } } async build_as_pdf(path = "output.pdf") { if (this.browser == null) { throw new Error("Browser is not initialized. Call with_browser() first."); } if (this.pfiles != null && this.html_pages.length === 0) { this.as_html_page(); } const page = await this.browser.newPage(); try { await page.setContent(this.html_pages.join("\n")); await page.pdf({ path, format: "A4" }); } finally { await page.close(); await this.browser.close(); this.browser = null; } } async close_browser() { if (this.browser == null) { return; } await this.browser.close(); this.browser = null; } }