437 lines
12 KiB
JavaScript
437 lines
12 KiB
JavaScript
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { basename, dirname, extname, resolve } from "node:path";
|
|
import { spawn, spawnSync } from "node:child_process";
|
|
|
|
const inputArg = process.argv[2];
|
|
|
|
if (!inputArg) {
|
|
console.error("Usage: npm run pdf -- <resume.md> [output.pdf]");
|
|
process.exit(1);
|
|
}
|
|
|
|
const inputPath = resolve(inputArg);
|
|
const outputPath = resolve(process.argv[3] ?? `dist/${basename(inputPath, extname(inputPath))}.pdf`);
|
|
const htmlPath = outputPath.replace(/\.pdf$/i, ".html");
|
|
const cssPath = resolve(process.env.PDF_CSS ?? "resume.css");
|
|
const markdown = readFileSync(inputPath, "utf8");
|
|
const css = readFileSync(cssPath, "utf8");
|
|
|
|
mkdirSync(dirname(outputPath), { recursive: true });
|
|
|
|
const html = `<!doctype html>
|
|
<html lang="ko">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>${escapeHtml(basename(inputPath, extname(inputPath)))}</title>
|
|
<style>${css}</style>
|
|
</head>
|
|
<body>
|
|
<main>
|
|
${renderMarkdown(markdown)}
|
|
</main>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
async function printPdfWithChrome(sourceHtmlPath, targetPdfPath) {
|
|
const chrome = findChrome();
|
|
const userDataDir = mkdtempSync(resolve(tmpdir(), "resume-chrome-"));
|
|
const chromeProcess = spawn(chrome, [
|
|
"--headless",
|
|
"--disable-gpu",
|
|
"--no-sandbox",
|
|
"--remote-debugging-port=0",
|
|
`--user-data-dir=${userDataDir}`,
|
|
"about:blank",
|
|
], {
|
|
stdio: ["ignore", "ignore", "pipe"],
|
|
});
|
|
|
|
let stderr = "";
|
|
chromeProcess.stderr.on("data", (chunk) => {
|
|
stderr += chunk.toString();
|
|
});
|
|
|
|
try {
|
|
const browserWsUrl = await readBrowserWsUrl(userDataDir, chromeProcess);
|
|
const tab = await createTab(browserWsUrl, `file://${sourceHtmlPath}`);
|
|
const pdfBase64 = await printTabToPdf(tab.webSocketDebuggerUrl);
|
|
writeFileSync(targetPdfPath, Buffer.from(pdfBase64, "base64"));
|
|
} catch (error) {
|
|
console.error(error.message);
|
|
if (stderr.trim()) {
|
|
console.error(stderr.trim());
|
|
}
|
|
process.exitCode = 1;
|
|
} finally {
|
|
chromeProcess.kill("SIGTERM");
|
|
if (chromeProcess.exitCode === null) {
|
|
await new Promise((resolveExit) => chromeProcess.once("exit", resolveExit));
|
|
}
|
|
try {
|
|
rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
} catch (error) {
|
|
if (error?.code !== "ENOTEMPTY" && error?.code !== "EBUSY") {
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (process.exitCode) {
|
|
process.exit(process.exitCode);
|
|
}
|
|
}
|
|
|
|
async function readBrowserWsUrl(userDataDir, chromeProcess) {
|
|
const activePortPath = resolve(userDataDir, "DevToolsActivePort");
|
|
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
if (chromeProcess.exitCode !== null) {
|
|
throw new Error(`Chrome exited before DevTools became available. Exit code: ${chromeProcess.exitCode}`);
|
|
}
|
|
|
|
try {
|
|
const [port, path] = readFileSync(activePortPath, "utf8").trim().split("\n");
|
|
return `ws://127.0.0.1:${port}${path}`;
|
|
} catch {
|
|
await delay(50);
|
|
}
|
|
}
|
|
|
|
throw new Error("Timed out while waiting for Chrome DevTools.");
|
|
}
|
|
|
|
async function createTab(browserWsUrl, url) {
|
|
const browser = new CdpClient(browserWsUrl);
|
|
await browser.open();
|
|
const { targetId } = await browser.send("Target.createTarget", { url });
|
|
await browser.close();
|
|
|
|
const targetsUrl = `http://${new URL(browserWsUrl).host}/json/list`;
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
const targets = await fetch(targetsUrl).then((response) => response.json());
|
|
const tab = targets.find((target) => target.id === targetId);
|
|
if (tab?.webSocketDebuggerUrl) {
|
|
return tab;
|
|
}
|
|
await delay(50);
|
|
}
|
|
|
|
throw new Error("Timed out while opening the HTML tab.");
|
|
}
|
|
|
|
async function printTabToPdf(tabWsUrl) {
|
|
const tab = new CdpClient(tabWsUrl);
|
|
await tab.open();
|
|
await tab.send("Page.enable");
|
|
await delay(300);
|
|
await tab.send("Page.getLayoutMetrics");
|
|
const result = await tab.send("Page.printToPDF", {
|
|
displayHeaderFooter: false,
|
|
printBackground: true,
|
|
preferCSSPageSize: true,
|
|
});
|
|
await tab.close();
|
|
return result.data;
|
|
}
|
|
|
|
class CdpClient {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.nextId = 1;
|
|
this.pending = new Map();
|
|
}
|
|
|
|
open() {
|
|
return new Promise((resolveOpen, rejectOpen) => {
|
|
this.ws = new WebSocket(this.url);
|
|
this.ws.onopen = () => resolveOpen();
|
|
this.ws.onerror = () => rejectOpen(new Error(`Failed to connect to ${this.url}`));
|
|
this.ws.onmessage = (event) => {
|
|
const message = JSON.parse(event.data);
|
|
const pending = this.pending.get(message.id);
|
|
if (!pending) {
|
|
return;
|
|
}
|
|
this.pending.delete(message.id);
|
|
if (message.error) {
|
|
pending.reject(new Error(message.error.message));
|
|
} else {
|
|
pending.resolve(message.result);
|
|
}
|
|
};
|
|
});
|
|
}
|
|
|
|
send(method, params = {}) {
|
|
const id = this.nextId;
|
|
this.nextId += 1;
|
|
const payload = JSON.stringify({ id, method, params });
|
|
|
|
return new Promise((resolveSend, rejectSend) => {
|
|
this.pending.set(id, { resolve: resolveSend, reject: rejectSend });
|
|
this.ws.send(payload);
|
|
});
|
|
}
|
|
|
|
close() {
|
|
this.ws.close();
|
|
}
|
|
}
|
|
|
|
function delay(ms) {
|
|
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
|
|
}
|
|
|
|
function findChrome() {
|
|
const candidates = [
|
|
process.env.CHROME_BIN,
|
|
"google-chrome",
|
|
"google-chrome-stable",
|
|
"chromium",
|
|
"chromium-browser",
|
|
].filter(Boolean);
|
|
|
|
for (const candidate of candidates) {
|
|
const found = spawnSync("which", [candidate], { encoding: "utf8" });
|
|
if (found.status === 0) {
|
|
return found.stdout.trim();
|
|
}
|
|
}
|
|
|
|
console.error("Chrome executable not found. Install Google Chrome or Chromium first.");
|
|
process.exit(1);
|
|
}
|
|
|
|
function renderMarkdown(source) {
|
|
const lines = source.replace(/\r\n/g, "\n").split("\n");
|
|
const blocks = [];
|
|
|
|
for (let index = 0; index < lines.length;) {
|
|
const line = lines[index];
|
|
|
|
if (!line.trim()) {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
const heading = /^(#{1,3})\s+(.+)$/.exec(line);
|
|
if (heading) {
|
|
const level = heading[1].length;
|
|
blocks.push(`<h${level}>${inline(heading[2])}</h${level}>`);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
if (/^---+$/.test(line.trim())) {
|
|
blocks.push("<hr>");
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
if (/^\`\`\`/.test(line.trim())) {
|
|
const fence = line.trim();
|
|
const language = fence.slice(3).trim();
|
|
const codeLines = [];
|
|
index += 1;
|
|
while (index < lines.length && !/^\`\`\`/.test(lines[index].trim())) {
|
|
codeLines.push(lines[index]);
|
|
index += 1;
|
|
}
|
|
if (index < lines.length) {
|
|
index += 1;
|
|
}
|
|
const languageClass = language ? ` class="language-${escapeHtml(language)}"` : "";
|
|
blocks.push(`<pre><code${languageClass}>${escapeHtml(codeLines.join("\n"))}</code></pre>`);
|
|
continue;
|
|
}
|
|
|
|
const image = /^!\[([^\]]*)\]\(([^)]+)\)$/.exec(line.trim());
|
|
if (image) {
|
|
const alt = image[1];
|
|
const caption = alt.replace(/^(FULL|CHART|WIDE|TOPOLOGY|STATE|SMALL)\s*·?\s*/, "").trim();
|
|
const imagePath = resolve(dirname(inputPath), image[2]);
|
|
const figcaption = caption ? `<figcaption>${escapeHtml(caption)}</figcaption>` : "";
|
|
blocks.push(`<figure><img src="file://${imagePath}" alt="${escapeHtml(alt)}">${figcaption}</figure>`);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
if (isTableStart(lines, index)) {
|
|
const rows = [];
|
|
rows.push(parseTableRow(lines[index]));
|
|
index += 2;
|
|
while (index < lines.length && /^\|.*\|$/.test(lines[index].trim())) {
|
|
rows.push(parseTableRow(lines[index]));
|
|
index += 1;
|
|
}
|
|
blocks.push(renderTable(rows));
|
|
continue;
|
|
}
|
|
|
|
if (line.startsWith(">")) {
|
|
const quoteLines = [];
|
|
while (index < lines.length && lines[index].startsWith(">")) {
|
|
quoteLines.push(lines[index].replace(/^>\s?/, ""));
|
|
index += 1;
|
|
}
|
|
blocks.push(`<blockquote>${renderParagraphs(quoteLines)}</blockquote>`);
|
|
continue;
|
|
}
|
|
|
|
if (/^-\s+/.test(line)) {
|
|
const items = [];
|
|
while (index < lines.length && /^-\s+/.test(lines[index])) {
|
|
items.push(lines[index].replace(/^-\s+/, ""));
|
|
index += 1;
|
|
}
|
|
blocks.push(`<ul>${items.map((item) => `<li>${inline(item)}</li>`).join("")}</ul>`);
|
|
continue;
|
|
}
|
|
|
|
if (/^\d+\.\s+/.test(line)) {
|
|
const items = [];
|
|
while (index < lines.length && /^\d+\.\s+/.test(lines[index])) {
|
|
items.push(lines[index].replace(/^\d+\.\s+/, ""));
|
|
index += 1;
|
|
}
|
|
blocks.push(`<ol>${items.map((item) => `<li>${inline(item)}</li>`).join("")}</ol>`);
|
|
continue;
|
|
}
|
|
|
|
const paragraph = [];
|
|
while (
|
|
index < lines.length &&
|
|
lines[index].trim() &&
|
|
!/^(#{1,3})\s+/.test(lines[index]) &&
|
|
!/^---+$/.test(lines[index].trim()) &&
|
|
!/^\`\`\`/.test(lines[index].trim()) &&
|
|
!lines[index].startsWith(">") &&
|
|
!/^- /.test(lines[index]) &&
|
|
!/^\d+\.\s+/.test(lines[index]) &&
|
|
!/^!\[[^\]]*\]\([^)]+\)$/.test(lines[index].trim()) &&
|
|
!isTableStart(lines, index)
|
|
) {
|
|
paragraph.push(lines[index].trim());
|
|
index += 1;
|
|
}
|
|
blocks.push(`<p>${inline(paragraph.join(" "))}</p>`);
|
|
}
|
|
|
|
return groupPages(groupProjectSections(blocks)).map((block) => ` ${block}`).join("\n");
|
|
}
|
|
|
|
/**
|
|
* Wrap every <h1> and the blocks that follow it in a fixed-height page box.
|
|
* The page box is a flex column, which lets its figure claim whatever vertical
|
|
* space the text on that page leaves over instead of being capped by a guess.
|
|
*/
|
|
function groupPages(blocks) {
|
|
const pages = [];
|
|
let current = null;
|
|
|
|
for (const block of blocks) {
|
|
if (block.startsWith("<h1>")) {
|
|
if (current) {
|
|
pages.push(current);
|
|
}
|
|
current = [block];
|
|
continue;
|
|
}
|
|
if (current) {
|
|
current.push(block);
|
|
} else {
|
|
pages.push([block]);
|
|
}
|
|
}
|
|
|
|
if (current) {
|
|
pages.push(current);
|
|
}
|
|
|
|
return pages.map((page) => `<section class="page">${page.join("")}</section>`);
|
|
}
|
|
|
|
function groupProjectSections(blocks) {
|
|
const grouped = [];
|
|
|
|
for (let index = 0; index < blocks.length;) {
|
|
if (!blocks[index].startsWith("<h3>")) {
|
|
grouped.push(blocks[index]);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
const section = [];
|
|
while (
|
|
index < blocks.length &&
|
|
!blocks[index].startsWith("<h1>") &&
|
|
!blocks[index].startsWith("<h2>") &&
|
|
(section.length === 0 || !blocks[index].startsWith("<h3>"))
|
|
) {
|
|
section.push(blocks[index]);
|
|
index += 1;
|
|
}
|
|
grouped.push(`<section class="project">${section.join("")}</section>`);
|
|
}
|
|
|
|
return grouped;
|
|
}
|
|
|
|
function renderParagraphs(lines) {
|
|
return lines
|
|
.join("\n")
|
|
.split(/\n\s*\n/)
|
|
.map((paragraph) => `<p>${inline(paragraph.replace(/\n/g, " ").trim())}</p>`)
|
|
.join("");
|
|
}
|
|
|
|
function isTableStart(lines, index) {
|
|
return (
|
|
index + 1 < lines.length &&
|
|
/^\|.*\|$/.test(lines[index].trim()) &&
|
|
/^\|\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(lines[index + 1].trim())
|
|
);
|
|
}
|
|
|
|
function parseTableRow(line) {
|
|
return line
|
|
.trim()
|
|
.replace(/^\|/, "")
|
|
.replace(/\|$/, "")
|
|
.split("|")
|
|
.map((cell) => cell.trim());
|
|
}
|
|
|
|
function renderTable(rows) {
|
|
const columns = rows[0]?.length ?? 0;
|
|
const className = columns === 3 ? "metric-table" : columns === 2 ? "two-col-table" : "data-table";
|
|
return `<table class="${className}"><tbody>${rows
|
|
.map((row) => `<tr>${row.map((cell) => `<td>${inline(cell)}</td>`).join("")}</tr>`)
|
|
.join("")}</tbody></table>`;
|
|
}
|
|
|
|
function inline(value) {
|
|
return escapeHtml(value)
|
|
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
|
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2">$1</a>');
|
|
}
|
|
|
|
function escapeHtml(value) {
|
|
return value
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, """);
|
|
}
|
|
|
|
writeFileSync(htmlPath, html);
|
|
|
|
await printPdfWithChrome(htmlPath, outputPath);
|
|
|
|
console.log(`HTML: ${htmlPath}`);
|
|
console.log(`PDF: ${outputPath}`);
|