const fs = require('node:fs/promises');
const path = require('node:path');
const {chromium} = require('playwright');
function escapeHtml(text) {
return text.replace(/[&<>"']/g, ch => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[ch]));
}
function renderInlineMath(text) {
return text.replace(/\\\(\s*\\sqrt\{([^}]+)\}\s*\\\)/g, 'sqrt($1)');
}
function inline(text) {
// Code spans are escaped, but not interpreted as Markdown or math.
return text.split(/(`[^`]*`)/g).map(part => {
if (part.startsWith('`') && part.endsWith('`')) return `${escapeHtml(part.slice(1, -1))}`;
return escapeHtml(renderInlineMath(part)).replace(/\*\*([^*]+)\*\*/g, '$1');
}).join('');
}
function renderMarkdown(markdown) {
return markdown.replace(/\r\n/g, '\n').split('\n').map(line => {
const heading = line.match(/^\s{0,3}(#{1,6})\s+(.+)$/);
if (heading) return `
${inline(line)}
` : ''; }).join('\n'); } async function writePdf(browser, inputPath, outputPath) { const markdown = await fs.readFile(inputPath, 'utf8'); const page = await browser.newPage(); try { await page.route(/^https?:/, route => route.abort()); await page.setContent(` ${renderMarkdown(markdown)}`); await page.evaluate(() => document.fonts.ready); await fs.mkdir(path.dirname(outputPath), {recursive: true}); await page.pdf({path: outputPath, format: 'A4', printBackground: true, margin: {top: '18mm', bottom: '18mm', left: '18mm', right: '18mm'}}); } finally { await page.close(); } } async function withBrowser(action) { const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); try { return await action(browser); } finally { await browser.close(); } } async function convertMarkdownToPdf(inputPath, outputPath) { return withBrowser(browser => writePdf(browser, inputPath, outputPath)); } async function convertBatch(inputDir, outputDir) { await fs.mkdir(outputDir, {recursive: true}); const entries = await fs.readdir(inputDir, {withFileTypes: true}); await withBrowser(async browser => { for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { if (!entry.isFile() || !entry.name.endsWith('.md')) continue; await writePdf(browser, path.join(inputDir, entry.name), path.join(outputDir, entry.name.slice(0, -3) + '.pdf')); } }); } if (require.main === module) { const [inputDir = 'samples', outputDir = 'out'] = process.argv.slice(2); convertBatch(inputDir, outputDir).catch(error => { console.error(error); process.exitCode = 1; }); } module.exports = {convertBatch, convertMarkdownToPdf, renderInlineMath, renderMarkdown};