diff --git a/src/lib/clean-pdf/__tests__/template.test.ts b/src/lib/clean-pdf/__tests__/template.test.ts
new file mode 100644
index 0000000..2a74221
--- /dev/null
+++ b/src/lib/clean-pdf/__tests__/template.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import { buildCleanHtml, safePdfFilename } from "@/lib/clean-pdf/template";
+
+const base = {
+ title: "Заголовок статьи",
+ url: "https://example.com/article",
+ theme: "light" as const,
+};
+
+describe("buildCleanHtml", () => {
+ it("экранирует HTML в метаполях", () => {
+ const html = buildCleanHtml({ ...base, title: ``, contentHtml: "
ок
" });
+ expect(html).not.toContain("");
+ expect(html).toContain("<script>");
+ });
+
+ it("вставляет контент и шапку", () => {
+ const html = buildCleanHtml({ ...base, author: "Автор", site: "Example", contentHtml: "Текст статьи
" });
+ expect(html).toContain("Текст статьи
");
+ expect(html).toContain("Заголовок статьи");
+ expect(html).toContain("Автор");
+ expect(html).toContain("https://example.com/article");
+ });
+
+ it("строит оглавление при 3+ заголовках и проставляет якоря", () => {
+ const content = "Один
a
Два
b
Три
c
";
+ const html = buildCleanHtml({ ...base, contentHtml: content });
+ expect(html).toContain("Содержание");
+ expect(html).toMatch(/Один<\/h2>/);
+ expect((html.match(/class="toc-item/g) ?? []).length).toBe(3);
+ });
+
+ it("не строит оглавление при <3 заголовках", () => {
+ const html = buildCleanHtml({ ...base, contentHtml: "Один
a
" });
+ expect(html).not.toContain("Содержание");
+ });
+
+ it("уникализирует одинаковые якоря", () => {
+ const content = "Раздел
Раздел
Раздел
";
+ const html = buildCleanHtml({ ...base, contentHtml: content });
+ const ids = [...html.matchAll(/ m[1]);
+ expect(new Set(ids).size).toBe(3);
+ });
+
+ it("переключает тёмную тему", () => {
+ const light = buildCleanHtml({ ...base, contentHtml: "
x
" });
+ const dark = buildCleanHtml({ ...base, theme: "dark", contentHtml: "x
" });
+ expect(light).toContain('data-theme="light"');
+ expect(dark).toContain('data-theme="dark"');
+ });
+});
+
+describe("safePdfFilename", () => {
+ it("убирает опасные символы и ограничивает длину", () => {
+ expect(safePdfFilename('Статья: как/не\\надо "делать"?')).toBe("Статья_ как_не_надо _делать_");
+ expect(safePdfFilename("")).toBe("document");
+ expect(safePdfFilename("a".repeat(300)).length).toBeLessThanOrEqual(140);
+ });
+});
diff --git a/src/lib/clean-pdf/template.ts b/src/lib/clean-pdf/template.ts
new file mode 100644
index 0000000..da29cb4
--- /dev/null
+++ b/src/lib/clean-pdf/template.ts
@@ -0,0 +1,107 @@
+import { JSDOM } from "jsdom";
+
+export interface CleanArticle {
+ title: string;
+ author?: string;
+ site?: string;
+ url: string;
+ contentHtml: string;
+ theme: "light" | "dark";
+}
+
+function escapeHtml(s: string): string {
+ return s
+ .replace(/&/g, "&")
+ .replace(//g, ">")
+ .replace(/"/g, """);
+}
+
+export function safePdfFilename(title: string): string {
+ const cleaned = title.replace(/[\\/:"*?<>|\n\r]+/g, "_").trim().slice(0, 140);
+ return cleaned || "document";
+}
+
+interface TocEntry { id: string; text: string; level: 2 | 3 }
+
+/** Проставляет id заголовкам h2/h3 и возвращает контент + записи оглавления. */
+function prepareContent(contentHtml: string): { html: string; toc: TocEntry[] } {
+ const dom = new JSDOM(`${contentHtml}`);
+ const doc = dom.window.document;
+ const used = new Set();
+ const toc: TocEntry[] = [];
+
+ doc.querySelectorAll("h2, h3").forEach((h) => {
+ const text = (h.textContent ?? "").trim();
+ if (!text) return;
+ let id = text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "") || "section";
+ let i = 2;
+ while (used.has(id)) id = `${id}-${i++}`;
+ used.add(id);
+ h.id = id;
+ toc.push({ id, text, level: h.tagName === "H2" ? 2 : 3 });
+ });
+
+ return { html: doc.body.innerHTML, toc };
+}
+
+const CSS = `
+ :root[data-theme="light"] { --bg: #faf7f0; --fg: #1f1d1a; --muted: #6b6459; --line: #d8d2c4; --accent: #7a2e2e; }
+ :root[data-theme="dark"] { --bg: #201e1b; --fg: #e8e4dc; --muted: #a39b8d; --line: #3d3a34; --accent: #d4a0a0; }
+ * { box-sizing: border-box; }
+ body { background: var(--bg); color: var(--fg); font-family: Georgia, "Times New Roman", serif;
+ font-size: 12.5pt; line-height: 1.65; margin: 0; }
+ main { max-width: 100%; }
+ h1 { font-size: 22pt; line-height: 1.25; margin: 0 0 6pt; }
+ h2 { font-size: 16pt; margin: 20pt 0 8pt; }
+ h3 { font-size: 13.5pt; margin: 16pt 0 6pt; }
+ p { margin: 0 0 9pt; }
+ a { color: var(--accent); text-decoration: none; }
+ img, video, iframe { max-width: 100%; height: auto; }
+ pre { background: rgba(127,127,127,.08); border: 1px solid var(--line); padding: 8pt;
+ overflow-x: hidden; white-space: pre-wrap; word-wrap: break-word;
+ font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 9.5pt; }
+ code { font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 0.9em; }
+ blockquote { border-left: 3px solid var(--line); margin: 0 0 9pt; padding: 2pt 0 2pt 12pt; color: var(--muted); }
+ table { border-collapse: collapse; width: 100%; font-size: 10.5pt; }
+ th, td { border: 1px solid var(--line); padding: 4pt 6pt; text-align: left; }
+ figure { margin: 0 0 9pt; } figcaption { color: var(--muted); font-size: 9.5pt; }
+ .meta { color: var(--muted); font-size: 10pt; margin-bottom: 4pt; }
+ .meta a { color: var(--muted); }
+ .head-rule { border: 0; border-top: 1px solid var(--line); margin: 12pt 0 16pt; }
+ .toc { border: 1px solid var(--line); padding: 10pt 14pt; margin: 0 0 16pt; }
+ .toc-title { font-weight: bold; margin-bottom: 6pt; }
+ .toc-item { display: block; margin: 2pt 0; }
+ .toc-item.lvl3 { padding-left: 14pt; font-size: 0.92em; }
+ h2, h3 { break-after: avoid; } pre, blockquote, figure, table { break-inside: avoid; }
+`;
+
+export function buildCleanHtml(article: CleanArticle): string {
+ const { html, toc } = prepareContent(article.contentHtml);
+ const metaParts = [article.site, article.author].filter(Boolean).map((s) => escapeHtml(s!));
+
+ const tocHtml = toc.length >= 3
+ ? ``
+ : "";
+
+ return `
+
+
+
+${escapeHtml(article.title)}
+
+
+
+
+ ${escapeHtml(article.title)}
+ ${metaParts.length ? `${metaParts.join(" · ")}
` : ""}
+
+
+ ${tocHtml}
+ ${html}
+
+
+`;
+}