markdown-pdf-export 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/export.mjs ADDED
@@ -0,0 +1,1369 @@
1
+ /**
2
+ * Markdown PDF core — Markdown → HTML → PDF (Playwright/Chromium).
3
+ *
4
+ * No stdio or process side effects at import time, so it can be used from the
5
+ * CLI (cli.mjs), the MCP server (mcp.mjs) or any other Node program.
6
+ * Dependencies come from `npm install`; nothing is installed at runtime.
7
+ */
8
+
9
+ // ── Built-in imports only at top level ────────────────────────────────────────
10
+ import fs from "node:fs/promises";
11
+ import fsSync from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import process from "node:process";
15
+ import { createRequire } from "node:module";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+
18
+ // ── Structured header/footer pipeline imports ─────────────────────────────────
19
+ import {
20
+ parseFrontMatter,
21
+ ensureYamlLoaded,
22
+ } from "./lib/frontmatter-parser.mjs";
23
+ import { mergeConfig } from "./lib/config-merger.mjs";
24
+ import { createAssetResolver } from "./lib/asset-resolver.mjs";
25
+ import {
26
+ deepMerge,
27
+ findProjectSettingsFile,
28
+ readSettingsFile,
29
+ userSettingsPath,
30
+ } from "./lib/settings-loader.mjs";
31
+ import { applyPresets } from "./lib/looks.mjs";
32
+ import {
33
+ createPlaceholderResolver,
34
+ createRenderContext,
35
+ ensureDateFnsLoaded,
36
+ } from "./lib/placeholder-resolver.mjs";
37
+ import { createHtmlGenerator } from "./lib/html-generator.mjs";
38
+
39
+ // ── Debug logging (opt-in) ────────────────────────────────────────────────────
40
+ // Set MARKDOWN_PDF_DEBUG=1 to log to <tmpdir>/markdown-pdf-debug.log, or set it
41
+ // to a file path to log there. Disabled by default.
42
+ const DEBUG_ENV = process.env.MARKDOWN_PDF_DEBUG ?? "";
43
+ export const DEBUG_LOG =
44
+ DEBUG_ENV === "" || DEBUG_ENV === "0" || DEBUG_ENV.toLowerCase() === "false"
45
+ ? null
46
+ : DEBUG_ENV === "1" || DEBUG_ENV.toLowerCase() === "true"
47
+ ? path.join(os.tmpdir(), "markdown-pdf-debug.log")
48
+ : path.resolve(DEBUG_ENV);
49
+
50
+ export function debugLog(message) {
51
+ if (!DEBUG_LOG) return;
52
+ try {
53
+ fsSync.appendFileSync(
54
+ DEBUG_LOG,
55
+ `[${new Date().toISOString()}] ${message}\n`,
56
+ );
57
+ } catch {
58
+ // Never let logging break the caller.
59
+ }
60
+ }
61
+
62
+ // ── Constants ─────────────────────────────────────────────────────────────────
63
+ export const SERVER_NAME = "markdown-pdf";
64
+ // Single source of truth for the version: package.json.
65
+ export const SERVER_VERSION = createRequire(import.meta.url)(
66
+ "./package.json",
67
+ ).version;
68
+ const SERVER_DIR = path.dirname(fileURLToPath(import.meta.url));
69
+
70
+ /**
71
+ * Directory of an installed dependency. Works whether npm nested it under
72
+ * server/node_modules or hoisted it (npx cache, global install, workspaces).
73
+ */
74
+ function packageDir(name) {
75
+ const require = createRequire(import.meta.url);
76
+ return path.dirname(require.resolve(`${name}/package.json`));
77
+ }
78
+ const DEFAULT_CSS_PATH = path.join(SERVER_DIR, "default.css");
79
+
80
+ export const DEFAULT_SETTINGS = {
81
+ // output
82
+ stylesheet_path: null,
83
+ output_directory: null,
84
+ assets_directory: null,
85
+ open_after_export: false,
86
+ // page layout
87
+ page_format: "A4",
88
+ orientation: "portrait",
89
+ scale: 1,
90
+ page_ranges: "",
91
+ print_background: true,
92
+ margin: { top: "15mm", right: "15mm", bottom: "15mm", left: "15mm" },
93
+ // content / rendering
94
+ font_family: null,
95
+ heading_font_family: null,
96
+ include_default_styles: true,
97
+ highlight: true,
98
+ highlight_style: "github.css",
99
+ breaks: false,
100
+ emoji: true,
101
+ // math (KaTeX)
102
+ math: false,
103
+ math_options: {
104
+ throw_on_error: false,
105
+ error_color: "#cc0000",
106
+ macros: {},
107
+ },
108
+ // headings / TOC
109
+ heading_anchors: false,
110
+ toc: false,
111
+ toc_options: {
112
+ level: [1, 2, 3],
113
+ list_type: "ul",
114
+ },
115
+ // header / footer
116
+ display_header_footer: false,
117
+ };
118
+
119
+ const ALLOWED_ORIENTATIONS = new Set(["portrait", "landscape"]);
120
+
121
+ export const HIGHLIGHT_STYLES = new Set([
122
+ "1c-light.css",
123
+ "a11y-dark.css",
124
+ "a11y-light.css",
125
+ "agate.css",
126
+ "an-old-hope.css",
127
+ "androidstudio.css",
128
+ "arduino-light.css",
129
+ "arta.css",
130
+ "ascetic.css",
131
+ "atom-one-dark-reasonable.css",
132
+ "atom-one-dark.css",
133
+ "atom-one-light.css",
134
+ "brown-paper.css",
135
+ "codepen-embed.css",
136
+ "color-brewer.css",
137
+ "cybertopia-cherry.css",
138
+ "cybertopia-dimmer.css",
139
+ "cybertopia-icecap.css",
140
+ "cybertopia-saturated.css",
141
+ "dark.css",
142
+ "default.css",
143
+ "devibeans.css",
144
+ "docco.css",
145
+ "far.css",
146
+ "felipec.css",
147
+ "foundation.css",
148
+ "github-dark-dimmed.css",
149
+ "github-dark.css",
150
+ "github.css",
151
+ "gml.css",
152
+ "googlecode.css",
153
+ "gradient-dark.css",
154
+ "gradient-light.css",
155
+ "grayscale.css",
156
+ "hybrid.css",
157
+ "idea.css",
158
+ "intellij-light.css",
159
+ "ir-black.css",
160
+ "isbl-editor-dark.css",
161
+ "isbl-editor-light.css",
162
+ "kimbie-dark.css",
163
+ "kimbie-light.css",
164
+ "lightfair.css",
165
+ "lioshi.css",
166
+ "magula.css",
167
+ "mono-blue.css",
168
+ "monokai-sublime.css",
169
+ "monokai.css",
170
+ "night-owl.css",
171
+ "nnfx-dark.css",
172
+ "nnfx-light.css",
173
+ "nord.css",
174
+ "obsidian.css",
175
+ "panda-syntax-dark.css",
176
+ "panda-syntax-light.css",
177
+ "paraiso-dark.css",
178
+ "paraiso-light.css",
179
+ "pojoaque.css",
180
+ "purebasic.css",
181
+ "qtcreator-dark.css",
182
+ "qtcreator-light.css",
183
+ "rainbow.css",
184
+ "rose-pine-dawn.css",
185
+ "rose-pine-moon.css",
186
+ "rose-pine.css",
187
+ "routeros.css",
188
+ "school-book.css",
189
+ "shades-of-purple.css",
190
+ "srcery.css",
191
+ "stackoverflow-dark.css",
192
+ "stackoverflow-light.css",
193
+ "sunburst.css",
194
+ "tokyo-night-dark.css",
195
+ "tokyo-night-light.css",
196
+ "tomorrow-night-blue.css",
197
+ "tomorrow-night-bright.css",
198
+ "vs.css",
199
+ "vs2015.css",
200
+ "xcode.css",
201
+ "xt256.css",
202
+ ]);
203
+
204
+ export const ALLOWED_PAGE_FORMATS = new Set([
205
+ "A4",
206
+ "Letter",
207
+ "Legal",
208
+ "Tabloid",
209
+ "Ledger",
210
+ "A0",
211
+ "A1",
212
+ "A2",
213
+ "A3",
214
+ "A5",
215
+ "A6",
216
+ ]);
217
+
218
+ // ── Settings ──────────────────────────────────────────────────────────────────
219
+ function normalizeNonEmptyString(value) {
220
+ return typeof value === "string" && value.trim() !== "" ? value : null;
221
+ }
222
+
223
+ function normalizeBoolean(value, fallback) {
224
+ return typeof value === "boolean" ? value : fallback;
225
+ }
226
+
227
+ function normalizePageFormat(value, fallback = DEFAULT_SETTINGS.page_format) {
228
+ if (typeof value !== "string") return fallback;
229
+ const trimmed = value.trim();
230
+ return ALLOWED_PAGE_FORMATS.has(trimmed) ? trimmed : fallback;
231
+ }
232
+
233
+ function normalizeMargin(raw, fallback = DEFAULT_SETTINGS.margin) {
234
+ const safe = raw && typeof raw === "object" ? raw : {};
235
+
236
+ return {
237
+ top:
238
+ typeof safe.top === "string" && safe.top.trim() !== ""
239
+ ? safe.top
240
+ : fallback.top,
241
+ right:
242
+ typeof safe.right === "string" && safe.right.trim() !== ""
243
+ ? safe.right
244
+ : fallback.right,
245
+ bottom:
246
+ typeof safe.bottom === "string" && safe.bottom.trim() !== ""
247
+ ? safe.bottom
248
+ : fallback.bottom,
249
+ left:
250
+ typeof safe.left === "string" && safe.left.trim() !== ""
251
+ ? safe.left
252
+ : fallback.left,
253
+ };
254
+ }
255
+
256
+ function normalizeMathOptions(raw, fallback = DEFAULT_SETTINGS.math_options) {
257
+ const safe = raw && typeof raw === "object" ? raw : {};
258
+ const macros =
259
+ safe.macros && typeof safe.macros === "object" && !Array.isArray(safe.macros)
260
+ ? safe.macros
261
+ : fallback.macros;
262
+ return {
263
+ throw_on_error: normalizeBoolean(safe.throw_on_error, fallback.throw_on_error),
264
+ error_color:
265
+ typeof safe.error_color === "string" && safe.error_color.trim() !== ""
266
+ ? safe.error_color
267
+ : fallback.error_color,
268
+ macros,
269
+ };
270
+ }
271
+
272
+ function normalizeTocOptions(raw, fallback = DEFAULT_SETTINGS.toc_options) {
273
+ const safe = raw && typeof raw === "object" ? raw : {};
274
+ let level = fallback.level;
275
+ if (Array.isArray(safe.level)) {
276
+ const filtered = safe.level
277
+ .map((n) => (typeof n === "number" ? Math.floor(n) : NaN))
278
+ .filter((n) => Number.isFinite(n) && n >= 1 && n <= 6);
279
+ if (filtered.length > 0) level = filtered;
280
+ } else if (typeof safe.level === "number" && safe.level >= 1 && safe.level <= 6) {
281
+ level = [Math.floor(safe.level)];
282
+ }
283
+ const list_type =
284
+ safe.list_type === "ol" || safe.list_type === "ul"
285
+ ? safe.list_type
286
+ : fallback.list_type;
287
+ return { level, list_type };
288
+ }
289
+
290
+ export function normalizeSettings(raw) {
291
+ const safe = raw && typeof raw === "object" ? raw : {};
292
+ return {
293
+ stylesheet_path: normalizeNonEmptyString(safe.stylesheet_path),
294
+ output_directory: normalizeNonEmptyString(safe.output_directory),
295
+ assets_directory: normalizeNonEmptyString(safe.assets_directory),
296
+ open_after_export: normalizeBoolean(
297
+ safe.open_after_export,
298
+ DEFAULT_SETTINGS.open_after_export,
299
+ ),
300
+ page_format: normalizePageFormat(safe.page_format),
301
+ orientation:
302
+ typeof safe.orientation === "string" &&
303
+ ALLOWED_ORIENTATIONS.has(safe.orientation.trim())
304
+ ? safe.orientation.trim()
305
+ : DEFAULT_SETTINGS.orientation,
306
+ scale:
307
+ typeof safe.scale === "number" && safe.scale > 0
308
+ ? safe.scale
309
+ : DEFAULT_SETTINGS.scale,
310
+ page_ranges:
311
+ typeof safe.page_ranges === "string" ? safe.page_ranges.trim() : "",
312
+ print_background: normalizeBoolean(
313
+ safe.print_background,
314
+ DEFAULT_SETTINGS.print_background,
315
+ ),
316
+ margin: normalizeMargin(safe.margin, DEFAULT_SETTINGS.margin),
317
+ include_default_styles: normalizeBoolean(
318
+ safe.include_default_styles,
319
+ DEFAULT_SETTINGS.include_default_styles,
320
+ ),
321
+ highlight: normalizeBoolean(safe.highlight, DEFAULT_SETTINGS.highlight),
322
+ highlight_style:
323
+ typeof safe.highlight_style === "string" &&
324
+ HIGHLIGHT_STYLES.has(safe.highlight_style.trim())
325
+ ? safe.highlight_style.trim()
326
+ : DEFAULT_SETTINGS.highlight_style,
327
+ breaks: normalizeBoolean(safe.breaks, DEFAULT_SETTINGS.breaks),
328
+ emoji: normalizeBoolean(safe.emoji, DEFAULT_SETTINGS.emoji),
329
+ math: normalizeBoolean(safe.math, DEFAULT_SETTINGS.math),
330
+ math_options: normalizeMathOptions(safe.math_options),
331
+ heading_anchors: normalizeBoolean(
332
+ safe.heading_anchors,
333
+ DEFAULT_SETTINGS.heading_anchors,
334
+ ),
335
+ toc: normalizeBoolean(safe.toc, DEFAULT_SETTINGS.toc),
336
+ toc_options: normalizeTocOptions(safe.toc_options),
337
+ display_header_footer: normalizeBoolean(
338
+ safe.display_header_footer,
339
+ DEFAULT_SETTINGS.display_header_footer,
340
+ ),
341
+
342
+ font_family: normalizeNonEmptyString(safe.font_family),
343
+ heading_font_family: normalizeNonEmptyString(safe.heading_font_family),
344
+
345
+ // Structured header/footer configs – pass through as-is for the
346
+ // config-merger / html-generator pipeline to consume.
347
+ header: safe.header && typeof safe.header === "object" ? safe.header : null,
348
+ footer: safe.footer && typeof safe.footer === "object" ? safe.footer : null,
349
+ };
350
+ }
351
+
352
+ /**
353
+ * Base settings layer (user level). Resolution:
354
+ * MARKDOWN_PDF_SETTINGS (inline JSON or a file path) when set,
355
+ * otherwise the user settings file if it exists.
356
+ * Returns the raw (un-normalized) settings plus the sources that were consulted.
357
+ */
358
+ function loadBaseSettings() {
359
+ const env = (process.env.MARKDOWN_PDF_SETTINGS ?? "").trim();
360
+ debugLog(`MARKDOWN_PDF_SETTINGS env: ${env}`);
361
+
362
+ if (env && env !== "{}") {
363
+ if (env.startsWith("{")) {
364
+ try {
365
+ const { data: parsed, warnings } = applyPresets(JSON.parse(env));
366
+ for (const w of warnings) console.error(`[markdown-pdf] ⚠️ MARKDOWN_PDF_SETTINGS: ${w}`);
367
+ return {
368
+ raw: parsed,
369
+ sources: [{ kind: "env", path: null, loaded: true, error: null }],
370
+ };
371
+ } catch (error) {
372
+ const msg = error instanceof Error ? error.message : String(error);
373
+ console.error(
374
+ `[markdown-pdf] ⚠️ Could not parse MARKDOWN_PDF_SETTINGS — falling back to defaults.\n` +
375
+ ` Reason : ${msg}`,
376
+ );
377
+ return {
378
+ raw: {},
379
+ sources: [{ kind: "env", path: null, loaded: false, error: msg }],
380
+ };
381
+ }
382
+ }
383
+ const file = readSettingsFile(env);
384
+ if (file.error) {
385
+ console.error(
386
+ `[markdown-pdf] ⚠️ Could not load settings file ${file.path} — falling back to defaults.\n` +
387
+ ` Reason : ${file.error}`,
388
+ );
389
+ }
390
+ return {
391
+ raw: file.data ?? {},
392
+ sources: [
393
+ { kind: "env", path: file.path, loaded: !file.error, error: file.error },
394
+ ],
395
+ };
396
+ }
397
+
398
+ const userFile = userSettingsPath();
399
+ if (!fsSync.existsSync(userFile)) {
400
+ return {
401
+ raw: {},
402
+ sources: [{ kind: "user", path: userFile, loaded: false, error: null }],
403
+ };
404
+ }
405
+ const file = readSettingsFile(userFile);
406
+ if (file.error) {
407
+ console.error(
408
+ `[markdown-pdf] ⚠️ Could not load ${file.path} — falling back to defaults.\n` +
409
+ ` Reason : ${file.error}`,
410
+ );
411
+ }
412
+ return {
413
+ raw: file.data ?? {},
414
+ sources: [{ kind: "user", path: file.path, loaded: !file.error, error: file.error }],
415
+ };
416
+ }
417
+
418
+ const baseLoad = loadBaseSettings();
419
+ let baseRaw = baseLoad.raw;
420
+ let baseSources = baseLoad.sources;
421
+ let settings = normalizeSettings(baseRaw);
422
+
423
+ /** Re-read the base settings layer (env var / user file) — used by --watch. */
424
+ export function reloadSettings() {
425
+ const load = loadBaseSettings();
426
+ baseRaw = load.raw;
427
+ baseSources = load.sources;
428
+ settings = normalizeSettings(baseRaw);
429
+ }
430
+
431
+ /**
432
+ * Replace the base settings layer (used by the CLI for --settings).
433
+ * `sourcePath` (optional) records the file the settings came from.
434
+ */
435
+ export function setSettings(raw, sourcePath = null) {
436
+ baseRaw = raw && typeof raw === "object" ? raw : {};
437
+ settings = normalizeSettings(baseRaw);
438
+ baseSources = [
439
+ {
440
+ kind: "cli",
441
+ path: sourcePath,
442
+ loaded: true,
443
+ error: null,
444
+ },
445
+ ];
446
+ }
447
+ debugLog(
448
+ `final loaded settings.display_header_footer: ${settings.display_header_footer}`,
449
+ );
450
+
451
+ /**
452
+ * Effective settings for one document: base layer deep-merged with the
453
+ * nearest .markdown-pdf.json found walking up from the document.
454
+ */
455
+ let projectDiscovery = true;
456
+
457
+ /**
458
+ * Turn the .markdown-pdf.json lookup on or off. Studio turns it off: it builds
459
+ * the settings stack itself so an unsaved draft is what gets rendered.
460
+ */
461
+ export function setProjectDiscovery(enabled) {
462
+ projectDiscovery = Boolean(enabled);
463
+ }
464
+
465
+ function resolveDocumentSettings(inputDir) {
466
+ const sources = [...baseSources];
467
+ const projectFile = projectDiscovery ? findProjectSettingsFile(inputDir) : null;
468
+ if (!projectFile) return { settings, sources };
469
+
470
+ const file = readSettingsFile(projectFile);
471
+ sources.push({
472
+ kind: "project",
473
+ path: file.path,
474
+ loaded: !file.error,
475
+ error: file.error,
476
+ });
477
+ if (file.error) {
478
+ console.error(
479
+ `[markdown-pdf] ⚠️ Could not load ${file.path} — ignoring it.\n Reason : ${file.error}`,
480
+ );
481
+ return { settings, sources };
482
+ }
483
+ return {
484
+ settings: normalizeSettings(deepMerge(baseRaw, file.data)),
485
+ sources,
486
+ };
487
+ }
488
+
489
+ function buildEffectiveOptions(args = {}, settings) {
490
+ return {
491
+ stylesheet_path:
492
+ normalizeNonEmptyString(args.stylesheet_path) ?? settings.stylesheet_path,
493
+ output_path: normalizeNonEmptyString(args.output_path),
494
+ open_after_export:
495
+ typeof args.open_after_export === "boolean"
496
+ ? args.open_after_export
497
+ : settings.open_after_export,
498
+ page_format: normalizePageFormat(args.page_format, settings.page_format),
499
+ orientation:
500
+ typeof args.orientation === "string" &&
501
+ ALLOWED_ORIENTATIONS.has(args.orientation.trim())
502
+ ? args.orientation.trim()
503
+ : settings.orientation,
504
+ scale:
505
+ typeof args.scale === "number" && args.scale > 0
506
+ ? args.scale
507
+ : settings.scale,
508
+ page_ranges:
509
+ typeof args.page_ranges === "string"
510
+ ? args.page_ranges.trim()
511
+ : settings.page_ranges,
512
+ print_background:
513
+ typeof args.print_background === "boolean"
514
+ ? args.print_background
515
+ : settings.print_background,
516
+ margin: normalizeMargin(args.margin, settings.margin),
517
+ include_default_styles:
518
+ typeof args.include_default_styles === "boolean"
519
+ ? args.include_default_styles
520
+ : settings.include_default_styles,
521
+ highlight:
522
+ typeof args.highlight === "boolean" ? args.highlight : settings.highlight,
523
+ highlight_style:
524
+ typeof args.highlight_style === "string" &&
525
+ HIGHLIGHT_STYLES.has(args.highlight_style.trim())
526
+ ? args.highlight_style.trim()
527
+ : settings.highlight_style,
528
+ breaks: typeof args.breaks === "boolean" ? args.breaks : settings.breaks,
529
+ emoji: typeof args.emoji === "boolean" ? args.emoji : settings.emoji,
530
+ math: typeof args.math === "boolean" ? args.math : settings.math,
531
+ math_options:
532
+ args.math_options && typeof args.math_options === "object"
533
+ ? normalizeMathOptions(args.math_options, settings.math_options)
534
+ : settings.math_options,
535
+ heading_anchors:
536
+ typeof args.heading_anchors === "boolean"
537
+ ? args.heading_anchors
538
+ : settings.heading_anchors,
539
+ toc: typeof args.toc === "boolean" ? args.toc : settings.toc,
540
+ toc_options:
541
+ args.toc_options && typeof args.toc_options === "object"
542
+ ? normalizeTocOptions(args.toc_options, settings.toc_options)
543
+ : settings.toc_options,
544
+ display_header_footer:
545
+ typeof args.display_header_footer === "boolean"
546
+ ? args.display_header_footer
547
+ : settings.display_header_footer,
548
+ // Structured header/footer: a per-call object replaces the one from settings.
549
+ header:
550
+ args.header && typeof args.header === "object"
551
+ ? args.header
552
+ : settings.header,
553
+ footer:
554
+ args.footer && typeof args.footer === "object"
555
+ ? args.footer
556
+ : settings.footer,
557
+
558
+ font_family:
559
+ normalizeNonEmptyString(args.font_family) ?? settings.font_family,
560
+ heading_font_family:
561
+ normalizeNonEmptyString(args.heading_font_family) ?? settings.heading_font_family,
562
+ };
563
+ }
564
+
565
+ // ── Dependency loading ────────────────────────────────────────────────────────
566
+ // Packages are resolved by npm at install time. These two just preload the
567
+ // lazily-imported helpers used by lib/*.
568
+ let dependenciesPromise = null;
569
+
570
+ function ensureDependencies() {
571
+ if (!dependenciesPromise) {
572
+ dependenciesPromise = Promise.all([
573
+ ensureYamlLoaded(),
574
+ ensureDateFnsLoaded(),
575
+ ]).catch((error) => {
576
+ dependenciesPromise = null;
577
+ throw error;
578
+ });
579
+ }
580
+ return dependenciesPromise;
581
+ }
582
+
583
+ // ── Lazy module loading ───────────────────────────────────────────────────────
584
+ let chromiumSingleton = null;
585
+ async function getChromium() {
586
+ if (!chromiumSingleton) {
587
+ await ensureDependencies();
588
+ const playwright = await import("playwright-core");
589
+ chromiumSingleton = playwright.chromium;
590
+ }
591
+ return chromiumSingleton;
592
+ }
593
+
594
+ let hljs_module = null;
595
+ async function getHljs() {
596
+ if (!hljs_module) {
597
+ await ensureDependencies();
598
+ hljs_module = (await import("highlight.js")).default;
599
+ }
600
+ return hljs_module;
601
+ }
602
+
603
+ let katexPlugin = null;
604
+ async function getKatexPlugin() {
605
+ if (!katexPlugin) {
606
+ await ensureDependencies();
607
+ const mod = await import("@vscode/markdown-it-katex");
608
+ // The CJS->ESM bridge nests the plugin under .default.default
609
+ let plugin = mod.default ?? mod;
610
+ if (typeof plugin !== "function" && typeof plugin?.default === "function") {
611
+ plugin = plugin.default;
612
+ }
613
+ katexPlugin = plugin;
614
+ }
615
+ return katexPlugin;
616
+ }
617
+
618
+ let anchorPlugin = null;
619
+ async function getAnchorPlugin() {
620
+ if (!anchorPlugin) {
621
+ await ensureDependencies();
622
+ const mod = await import("markdown-it-anchor");
623
+ anchorPlugin = mod.default ?? mod;
624
+ }
625
+ return anchorPlugin;
626
+ }
627
+
628
+ let tocPlugin = null;
629
+ async function getTocPlugin() {
630
+ if (!tocPlugin) {
631
+ await ensureDependencies();
632
+ const mod = await import("markdown-it-toc-done-right");
633
+ tocPlugin = mod.default ?? mod;
634
+ }
635
+ return tocPlugin;
636
+ }
637
+
638
+ function ghSlugify(str) {
639
+ return String(str)
640
+ .trim()
641
+ .toLowerCase()
642
+ .replace(/[^\w\sÀ-￿-]/g, "")
643
+ .replace(/\s+/g, "-");
644
+ }
645
+
646
+ let emojiPlugin = null;
647
+ async function getEmojiPlugin() {
648
+ if (!emojiPlugin) {
649
+ await ensureDependencies();
650
+ // markdown-it-emoji v3 uses named exports; `full` includes all emoji sets
651
+ const mod = await import("markdown-it-emoji");
652
+ emojiPlugin = mod.full ?? mod.bare ?? mod.default;
653
+ }
654
+ return emojiPlugin;
655
+ }
656
+
657
+ async function createMarkdown(options) {
658
+ await ensureDependencies();
659
+ const MarkdownIt = (await import("markdown-it")).default;
660
+
661
+ let highlightFn = undefined;
662
+ if (options.highlight) {
663
+ const hljs = await getHljs();
664
+ highlightFn = (str, lang) => {
665
+ if (lang && hljs.getLanguage(lang)) {
666
+ try {
667
+ return (
668
+ '<pre class="hljs"><code>' +
669
+ hljs.highlight(str, { language: lang, ignoreIllegals: true })
670
+ .value +
671
+ "</code></pre>"
672
+ );
673
+ } catch {
674
+ // fall through to plain escaping
675
+ }
676
+ }
677
+ return (
678
+ '<pre class="hljs"><code>' +
679
+ MarkdownIt().utils.escapeHtml(str) +
680
+ "</code></pre>"
681
+ );
682
+ };
683
+ }
684
+
685
+ const md = new MarkdownIt({
686
+ html: true,
687
+ linkify: true,
688
+ typographer: true,
689
+ breaks: options.breaks ?? false,
690
+ highlight: highlightFn,
691
+ });
692
+
693
+ if (options.emoji) {
694
+ try {
695
+ const emoji = await getEmojiPlugin();
696
+ md.use(emoji);
697
+ } catch {
698
+ debugLog("markdown-it-emoji not available, skipping emoji support");
699
+ }
700
+ }
701
+
702
+ if (options.math) {
703
+ try {
704
+ const katex = await getKatexPlugin();
705
+ // Inject our own katex so the rendered markup and the stylesheet
706
+ // (vendor/katex-inline.css, built from the same package) always match.
707
+ // The plugin's bundled katex is pinned to an older release line.
708
+ const katexModule = await import("katex");
709
+ md.use(katex, {
710
+ katex: katexModule.default ?? katexModule,
711
+ throwOnError: options.math_options.throw_on_error,
712
+ errorColor: options.math_options.error_color,
713
+ macros: options.math_options.macros,
714
+ });
715
+ } catch (error) {
716
+ debugLog(
717
+ `KaTeX plugin not available: ${error instanceof Error ? error.message : String(error)}`,
718
+ );
719
+ }
720
+ }
721
+
722
+ if (options.heading_anchors || options.toc) {
723
+ try {
724
+ const anchor = await getAnchorPlugin();
725
+ md.use(anchor, { permalink: false, slugify: ghSlugify });
726
+ } catch (error) {
727
+ debugLog(
728
+ `markdown-it-anchor not available: ${error instanceof Error ? error.message : String(error)}`,
729
+ );
730
+ }
731
+ }
732
+
733
+ if (options.toc) {
734
+ try {
735
+ const toc = await getTocPlugin();
736
+ md.use(toc, {
737
+ level: options.toc_options.level,
738
+ listType: options.toc_options.list_type,
739
+ containerClass: "markdown-toc",
740
+ slugify: ghSlugify,
741
+ });
742
+ } catch (error) {
743
+ debugLog(
744
+ `markdown-it-toc-done-right not available: ${error instanceof Error ? error.message : String(error)}`,
745
+ );
746
+ }
747
+ }
748
+
749
+ return md;
750
+ }
751
+
752
+ // ── Browser setup ─────────────────────────────────────────────────────────────
753
+ // Order: system Chrome → system Edge → Playwright's own Chromium.
754
+ // Override with MARKDOWN_PDF_BROWSER = chrome | msedge | chromium | <path to executable>.
755
+ // A browser is NEVER downloaded implicitly — see installBrowser().
756
+ export const INSTALL_BROWSER_HINT = "npx -y markdown-pdf-export install-browser";
757
+
758
+ // Playwright's own Chromium. `install-browser` installs the full browser
759
+ // (`--no-shell`), which is selected with channel "chromium"; plain `{}` is the
760
+ // separate headless-shell build, tried last in case only that one is present.
761
+ const PLAYWRIGHT_CHROMIUM = [{ channel: "chromium" }, {}];
762
+
763
+ function browserCandidates() {
764
+ const override = (process.env.MARKDOWN_PDF_BROWSER ?? "").trim();
765
+ if (!override) {
766
+ return [{ channel: "chrome" }, { channel: "msedge" }, ...PLAYWRIGHT_CHROMIUM];
767
+ }
768
+ if (override === "chromium") return PLAYWRIGHT_CHROMIUM;
769
+ if (/^(chrome|msedge)(-(beta|dev|canary))?$/.test(override)) {
770
+ return [{ channel: override }];
771
+ }
772
+ return [{ executablePath: path.resolve(override) }];
773
+ }
774
+
775
+ let workingBrowserOptions = null;
776
+
777
+ export async function launchBrowser() {
778
+ const chromium = await getChromium();
779
+ const candidates = workingBrowserOptions
780
+ ? [workingBrowserOptions]
781
+ : browserCandidates();
782
+ const failures = [];
783
+
784
+ for (const candidate of candidates) {
785
+ try {
786
+ const browser = await chromium.launch({ headless: true, ...candidate });
787
+ workingBrowserOptions = candidate;
788
+ debugLog(`browser launched: ${JSON.stringify(candidate)}`);
789
+ return browser;
790
+ } catch (error) {
791
+ const message = error instanceof Error ? error.message : String(error);
792
+ failures.push(`${JSON.stringify(candidate)} → ${message.split("\n")[0]}`);
793
+ }
794
+ }
795
+
796
+ const message =
797
+ `No usable Chrome/Chromium browser found.\n` +
798
+ `Tried:\n ${failures.join("\n ")}\n` +
799
+ `Install Google Chrome or Microsoft Edge, set MARKDOWN_PDF_BROWSER to a ` +
800
+ `browser executable, or download Playwright's Chromium (~200 MB) with:\n` +
801
+ ` ${INSTALL_BROWSER_HINT}`;
802
+ debugLog(message);
803
+ throw new Error(message);
804
+ }
805
+
806
+ /** Explicit, user-initiated download of Playwright's Chromium. */
807
+ export async function installBrowser({ onOutput } = {}) {
808
+ const { spawn } = await import("node:child_process");
809
+ // playwright-core's "exports" map does not expose ./cli.js, so locate the
810
+ // package directory through its package.json and join the path.
811
+ const playwrightCliPath = path.join(packageDir("playwright-core"), "cli.js");
812
+
813
+ await new Promise((resolve, reject) => {
814
+ const proc = spawn(
815
+ process.execPath,
816
+ [playwrightCliPath, "install", "--no-shell", "chromium"],
817
+ { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env } },
818
+ );
819
+
820
+ let output = "";
821
+ const collect = (chunk) => {
822
+ output += chunk.toString();
823
+ onOutput?.(chunk.toString());
824
+ };
825
+ proc.stdout?.on("data", collect);
826
+ proc.stderr?.on("data", collect);
827
+
828
+ proc.on("exit", (code) => {
829
+ if (code === 0) {
830
+ workingBrowserOptions = null;
831
+ resolve();
832
+ return;
833
+ }
834
+ reject(new Error(`Chromium install failed (exit ${code}).\n${output.trim()}`));
835
+ });
836
+ proc.on("error", (error) =>
837
+ reject(new Error(`Failed to start Chromium installer: ${error.message}`)),
838
+ );
839
+ });
840
+ }
841
+
842
+ // ── Tool implementations ──────────────────────────────────────────────────────
843
+ export async function doctorMarkdownPdf(args) {
844
+ await ensureDependencies();
845
+ const inputPath = args.input_path
846
+ ? await resolveInputPath(args.input_path)
847
+ : null;
848
+
849
+ let browserInfo;
850
+ try {
851
+ const browser = await launchBrowser();
852
+ const version = browser.version();
853
+ await browser.close();
854
+
855
+ browserInfo = {
856
+ available: true,
857
+ version,
858
+ backend: "Chromium (Playwright)",
859
+ launch_options: workingBrowserOptions,
860
+ };
861
+ } catch (error) {
862
+ browserInfo = {
863
+ available: false,
864
+ error: error instanceof Error ? error.message : String(error),
865
+ hint: `Install Chrome/Edge, set MARKDOWN_PDF_BROWSER, or run: ${INSTALL_BROWSER_HINT}`,
866
+ };
867
+ }
868
+
869
+ const doc = resolveDocumentSettings(
870
+ inputPath ? path.dirname(inputPath) : process.cwd(),
871
+ );
872
+
873
+ return {
874
+ browser: browserInfo,
875
+ settings_sources: doc.sources,
876
+ settings: {
877
+ stylesheet_path: doc.settings.stylesheet_path,
878
+ output_directory: doc.settings.output_directory,
879
+ assets_directory: doc.settings.assets_directory,
880
+ open_after_export: doc.settings.open_after_export,
881
+ page_format: doc.settings.page_format,
882
+ orientation: doc.settings.orientation,
883
+ scale: doc.settings.scale,
884
+ page_ranges: doc.settings.page_ranges,
885
+ print_background: doc.settings.print_background,
886
+ margin: doc.settings.margin,
887
+ include_default_styles: doc.settings.include_default_styles,
888
+ highlight: doc.settings.highlight,
889
+ highlight_style: doc.settings.highlight_style,
890
+ breaks: doc.settings.breaks,
891
+ emoji: doc.settings.emoji,
892
+ display_header_footer: doc.settings.display_header_footer,
893
+ font_family: doc.settings.font_family,
894
+ heading_font_family: doc.settings.heading_font_family,
895
+ header: doc.settings.header,
896
+ footer: doc.settings.footer,
897
+ },
898
+ default_settings: DEFAULT_SETTINGS,
899
+ server_dir: SERVER_DIR,
900
+ input_path: inputPath,
901
+ debug_log: DEBUG_LOG,
902
+ };
903
+ }
904
+
905
+ export async function exportMarkdownPdf(args) {
906
+ await ensureDependencies();
907
+ const inputPath = await resolveInputPath(args.input_path);
908
+ debugLog(`exportMarkdownPdf args: ${JSON.stringify(args)}`);
909
+ debugLog(
910
+ `exportMarkdownPdf args.display_header_footer: ${args.display_header_footer} (type: ${typeof args.display_header_footer})`,
911
+ );
912
+
913
+ // ── Step 1: Read source and parse front matter ────────────────────────────
914
+ const source = await fs.readFile(inputPath, "utf8");
915
+ const filename = path.basename(inputPath);
916
+
917
+ const {
918
+ data: frontMatterData,
919
+ body: markdownBody,
920
+ validation: fmValidation,
921
+ parseError: fmParseError,
922
+ } = parseFrontMatter(source, { filename, validate: true });
923
+
924
+ if (fmParseError) {
925
+ debugLog(`Front matter parse error: ${fmParseError}`);
926
+ }
927
+ if (fmValidation && !fmValidation.valid) {
928
+ debugLog(
929
+ `Front matter validation errors: ${JSON.stringify(fmValidation.errors)}`,
930
+ );
931
+ }
932
+ if (fmValidation && fmValidation.warnings.length > 0) {
933
+ debugLog(
934
+ `Front matter validation warnings: ${JSON.stringify(fmValidation.warnings)}`,
935
+ );
936
+ }
937
+
938
+ const {
939
+ title,
940
+ author,
941
+ pdfConfig: frontMatterPdfConfig,
942
+ customVariables,
943
+ } = frontMatterData;
944
+ debugLog(
945
+ `Parsed front matter - title: ${title}, author: ${author}, pdfConfig: ${JSON.stringify(frontMatterPdfConfig)}`,
946
+ );
947
+
948
+ // ── Step 2: Build effective options from args (tool call params) ──────────
949
+ const { settings: docSettings, sources: settingsSources } =
950
+ resolveDocumentSettings(path.dirname(inputPath));
951
+ debugLog(`settings sources: ${JSON.stringify(settingsSources)}`);
952
+ const options = buildEffectiveOptions(args, docSettings);
953
+ debugLog(
954
+ `exportMarkdownPdf options.display_header_footer: ${options.display_header_footer}`,
955
+ );
956
+
957
+ // ── Step 3: Merge config (defaults < settings < front matter) ─────────────
958
+ // Build settings object from current options (which already merged args with global settings)
959
+ const settingsForMerge = {
960
+ page_format: options.page_format,
961
+ orientation: options.orientation,
962
+ scale: options.scale,
963
+ page_ranges: options.page_ranges,
964
+ print_background: options.print_background,
965
+ margin: options.margin,
966
+ font_family: options.font_family,
967
+ heading_font_family: options.heading_font_family,
968
+ include_default_styles: options.include_default_styles,
969
+ highlight: options.highlight,
970
+ highlight_style: options.highlight_style,
971
+ breaks: options.breaks,
972
+ emoji: options.emoji,
973
+ display_header_footer: options.display_header_footer,
974
+ // Structured header/footer from the call arguments, else from settings
975
+ header: options.header || null,
976
+ footer: options.footer || null,
977
+ };
978
+
979
+ const { config: mergedConfig, hasHeaderFooter } = mergeConfig(
980
+ settingsForMerge,
981
+ frontMatterPdfConfig,
982
+ {
983
+ applyDefaults: false,
984
+ },
985
+ );
986
+
987
+ debugLog(`hasHeaderFooter: ${hasHeaderFooter}`);
988
+ debugLog(`Merged config: ${JSON.stringify(mergedConfig)}`);
989
+
990
+ // Override options with merged config values that may have come from front matter
991
+ const effectiveOptions = {
992
+ ...options,
993
+ page_format: mergedConfig.page_format ?? options.page_format,
994
+ orientation: mergedConfig.orientation ?? options.orientation,
995
+ scale: mergedConfig.scale ?? options.scale,
996
+ page_ranges: mergedConfig.page_ranges ?? options.page_ranges,
997
+ print_background: mergedConfig.print_background ?? options.print_background,
998
+ margin: mergedConfig.margin ?? options.margin,
999
+ font_family: mergedConfig.font_family ?? options.font_family,
1000
+ heading_font_family: mergedConfig.heading_font_family ?? options.heading_font_family,
1001
+ include_default_styles:
1002
+ mergedConfig.include_default_styles ?? options.include_default_styles,
1003
+ highlight: mergedConfig.highlight ?? options.highlight,
1004
+ highlight_style: mergedConfig.highlight_style ?? options.highlight_style,
1005
+ breaks: mergedConfig.breaks ?? options.breaks,
1006
+ emoji: mergedConfig.emoji ?? options.emoji,
1007
+ math: mergedConfig.math ?? options.math,
1008
+ math_options:
1009
+ mergedConfig.math_options ?? options.math_options,
1010
+ heading_anchors:
1011
+ mergedConfig.heading_anchors ?? options.heading_anchors,
1012
+ toc: mergedConfig.toc ?? options.toc,
1013
+ toc_options: mergedConfig.toc_options ?? options.toc_options,
1014
+ display_header_footer:
1015
+ hasHeaderFooter ||
1016
+ mergedConfig.display_header_footer ||
1017
+ options.display_header_footer,
1018
+ };
1019
+
1020
+ const outputPath = await resolveOutputPath(
1021
+ inputPath,
1022
+ options.output_path,
1023
+ docSettings,
1024
+ );
1025
+
1026
+ // ── Step 4: Render Markdown to HTML ───────────────────────────────────────
1027
+ const { html } = await renderMarkdownToHtmlWithBody(
1028
+ inputPath,
1029
+ markdownBody,
1030
+ title,
1031
+ effectiveOptions,
1032
+ );
1033
+
1034
+ const browser = await launchBrowser();
1035
+
1036
+ let displayHeaderFooterResult;
1037
+
1038
+ try {
1039
+ const page = await browser.newPage();
1040
+
1041
+ // Write HTML to a uniquely-named temp file so parallel exports don't collide
1042
+ const { randomUUID } = await import('node:crypto');
1043
+ const tempHtmlPath = path.join(path.dirname(inputPath), `.${randomUUID()}.temp_render.html`);
1044
+ await fs.writeFile(tempHtmlPath, html, 'utf8');
1045
+
1046
+ try {
1047
+ const tempUrl = pathToFileURL(tempHtmlPath).href;
1048
+ await page.goto(tempUrl, { waitUntil: "networkidle" });
1049
+ } finally {
1050
+ try {
1051
+ await fs.unlink(tempHtmlPath);
1052
+ } catch {
1053
+ // ignore cleanup errors
1054
+ }
1055
+ }
1056
+
1057
+ const pdfOptions = {
1058
+ path: outputPath,
1059
+ format: effectiveOptions.page_format,
1060
+ landscape: effectiveOptions.orientation === "landscape",
1061
+ scale: effectiveOptions.scale,
1062
+ printBackground: effectiveOptions.print_background,
1063
+ margin: effectiveOptions.margin,
1064
+ };
1065
+
1066
+ if (
1067
+ effectiveOptions.page_ranges &&
1068
+ effectiveOptions.page_ranges.trim() !== ""
1069
+ ) {
1070
+ pdfOptions.pageRanges = effectiveOptions.page_ranges;
1071
+ }
1072
+
1073
+ debugLog(`pdfOptions before header/footer: ${JSON.stringify(pdfOptions)}`);
1074
+ debugLog(`hasHeaderFooter: ${hasHeaderFooter}`);
1075
+
1076
+ // ── Step 5: Generate header/footer templates ────────────────────────────
1077
+ if (hasHeaderFooter || effectiveOptions.display_header_footer) {
1078
+ debugLog("BRANCH: header/footer is enabled");
1079
+ pdfOptions.displayHeaderFooter = true;
1080
+
1081
+ // Create render context for placeholders
1082
+ const renderContext = createRenderContext({
1083
+ inputPath,
1084
+ title: title || "",
1085
+ author: author || "",
1086
+ frontMatter: { ...customVariables },
1087
+ now: new Date(),
1088
+ });
1089
+
1090
+ // Create resolvers
1091
+ const placeholderResolver = createPlaceholderResolver(renderContext);
1092
+ const assetResolver = createAssetResolver({
1093
+ basePath: inputPath,
1094
+ assetsDirectory: docSettings.assets_directory,
1095
+ });
1096
+
1097
+ // Create HTML generator
1098
+ const htmlGenerator = createHtmlGenerator({
1099
+ placeholderResolver,
1100
+ assetResolver,
1101
+ fontFamily: effectiveOptions.font_family,
1102
+ });
1103
+
1104
+ // Generate header template
1105
+ if (mergedConfig.header) {
1106
+ try {
1107
+ pdfOptions.headerTemplate = await htmlGenerator.generateHeader(
1108
+ mergedConfig.header,
1109
+ );
1110
+ debugLog(
1111
+ `Generated structured header: ${pdfOptions.headerTemplate.substring(0, 200)}...`,
1112
+ );
1113
+ } catch (err) {
1114
+ debugLog(`Error generating structured header: ${err.message}`);
1115
+ pdfOptions.headerTemplate = "<span></span>";
1116
+ }
1117
+ } else {
1118
+ pdfOptions.headerTemplate = "<span></span>";
1119
+ }
1120
+
1121
+ // Generate footer template
1122
+ if (mergedConfig.footer) {
1123
+ try {
1124
+ pdfOptions.footerTemplate = await htmlGenerator.generateFooter(
1125
+ mergedConfig.footer,
1126
+ );
1127
+ debugLog(
1128
+ `Generated structured footer: ${pdfOptions.footerTemplate.substring(0, 200)}...`,
1129
+ );
1130
+ } catch (err) {
1131
+ debugLog(`Error generating structured footer: ${err.message}`);
1132
+ pdfOptions.footerTemplate = "<span></span>";
1133
+ }
1134
+ } else {
1135
+ pdfOptions.footerTemplate = "<span></span>";
1136
+ }
1137
+
1138
+ // Log any asset warnings
1139
+ const assetWarnings = assetResolver.getWarnings();
1140
+ if (assetWarnings.length > 0) {
1141
+ debugLog(`Asset warnings: ${JSON.stringify(assetWarnings)}`);
1142
+ }
1143
+ } else {
1144
+ debugLog("BRANCH: header/footer is disabled");
1145
+ pdfOptions.displayHeaderFooter = false;
1146
+ pdfOptions.headerTemplate = "";
1147
+ pdfOptions.footerTemplate = "";
1148
+ }
1149
+
1150
+ debugLog(`final pdfOptions: ${JSON.stringify(pdfOptions)}`);
1151
+ displayHeaderFooterResult = pdfOptions.displayHeaderFooter;
1152
+ await page.pdf(pdfOptions);
1153
+ } finally {
1154
+ await browser.close();
1155
+ }
1156
+
1157
+ if (effectiveOptions.open_after_export) {
1158
+ void openFile(outputPath);
1159
+ }
1160
+
1161
+ return {
1162
+ input_path: inputPath,
1163
+ output_path: outputPath,
1164
+ backend: "Playwright/Chromium",
1165
+ page_format: effectiveOptions.page_format,
1166
+ orientation: effectiveOptions.orientation,
1167
+ scale: effectiveOptions.scale,
1168
+ print_background: effectiveOptions.print_background,
1169
+ margin: effectiveOptions.margin,
1170
+ open_after_export: effectiveOptions.open_after_export,
1171
+ display_header_footer: displayHeaderFooterResult,
1172
+ settings_files: settingsSources
1173
+ .filter((source) => source.loaded && source.path)
1174
+ .map((source) => source.path),
1175
+ };
1176
+ }
1177
+
1178
+ // ── Path helpers ──────────────────────────────────────────────────────────────
1179
+ async function resolveInputPath(inputPath) {
1180
+ if (typeof inputPath !== "string" || inputPath.trim() === "") {
1181
+ throw new Error("input_path must be a non-empty string");
1182
+ }
1183
+
1184
+ const absolutePath = path.resolve(inputPath);
1185
+ await assertFileExists(absolutePath, "Markdown input");
1186
+ return absolutePath;
1187
+ }
1188
+
1189
+ async function resolveOutputPath(inputPath, outputPath, settings) {
1190
+ if (typeof outputPath === "string" && outputPath.trim() !== "") {
1191
+ const resolved = path.resolve(path.dirname(inputPath), outputPath);
1192
+ await fs.mkdir(path.dirname(resolved), { recursive: true });
1193
+ return resolved;
1194
+ }
1195
+
1196
+ const baseDirectory = settings.output_directory
1197
+ ? path.resolve(path.dirname(inputPath), settings.output_directory)
1198
+ : path.dirname(inputPath);
1199
+
1200
+ await fs.mkdir(baseDirectory, { recursive: true });
1201
+ return path.join(baseDirectory, `${path.parse(inputPath).name}.pdf`);
1202
+ }
1203
+
1204
+ /**
1205
+ * Background colour a highlight.js theme gives code blocks, or null when it
1206
+ * is plain white (then the default light grey box is kept) or not a hex colour.
1207
+ * @param {string} css
1208
+ * @returns {string|null}
1209
+ */
1210
+ export function codeThemeBackground(css) {
1211
+ // Only the bare ".hljs" rule counts ("pre code.hljs" is layout, not colour).
1212
+ for (const rule of String(css).matchAll(/(?:^|[},\s/])\.hljs\s*\{([^}]*)\}/g)) {
1213
+ const m = /background(?:-color)?\s*:\s*(#[0-9a-f]{3,8})\b/i.exec(rule[1]);
1214
+ if (!m) continue;
1215
+ const hex = m[1].toLowerCase();
1216
+ return hex === "#fff" || hex === "#ffffff" ? null : hex;
1217
+ }
1218
+ return null;
1219
+ }
1220
+
1221
+ function resolveStylesheetPath(baseDirectory, stylesheetPath) {
1222
+ if (!stylesheetPath) return null;
1223
+ return path.resolve(baseDirectory, stylesheetPath);
1224
+ }
1225
+
1226
+ // ── HTML rendering ────────────────────────────────────────────────────────────
1227
+
1228
+ /**
1229
+ * Render Markdown to HTML with pre-parsed body and title.
1230
+ * Used by the new structured header/footer pipeline where front matter
1231
+ * is already parsed.
1232
+ */
1233
+ async function renderMarkdownToHtmlWithBody(inputPath, body, title, options) {
1234
+ const markdown = await createMarkdown(options);
1235
+ const rendered = markdown.render(body);
1236
+
1237
+ // Build style blocks
1238
+ let styleBlocks = "";
1239
+
1240
+ if (options.include_default_styles) {
1241
+ const defaultCss = await fs.readFile(DEFAULT_CSS_PATH, "utf8");
1242
+ styleBlocks += `<style>${defaultCss}</style>\n `;
1243
+ }
1244
+
1245
+ // KaTeX stylesheet (with inlined fonts when bundled, else read from node_modules)
1246
+ if (options.math) {
1247
+ try {
1248
+ const vendorCss = path.join(SERVER_DIR, "vendor", "katex-inline.css");
1249
+ const katexCssPath = (await fileExists(vendorCss))
1250
+ ? vendorCss
1251
+ : path.join(packageDir("katex"), "dist", "katex.min.css");
1252
+ const katexCss = await fs.readFile(katexCssPath, "utf8");
1253
+ styleBlocks += `<style>${katexCss}</style>\n `;
1254
+ } catch (error) {
1255
+ debugLog(
1256
+ `Could not load KaTeX CSS: ${error instanceof Error ? error.message : String(error)}`,
1257
+ );
1258
+ }
1259
+ }
1260
+
1261
+ // Highlight.js stylesheet
1262
+ if (options.highlight && options.highlight_style) {
1263
+ try {
1264
+ const hljsStylesDir = path.join(packageDir("highlight.js"), "styles");
1265
+ const hljsCssPath = path.join(hljsStylesDir, options.highlight_style);
1266
+ const hljsCss = await fs.readFile(hljsCssPath, "utf8");
1267
+ styleBlocks += `<style>${hljsCss}</style>\n `;
1268
+ // default.css paints code blocks light grey. A theme with its own
1269
+ // (dark or tinted) background must win, or light text lands on grey.
1270
+ const themeBg = codeThemeBackground(hljsCss);
1271
+ if (themeBg) styleBlocks += `<style>pre.hljs{background:${themeBg}}</style>\n `;
1272
+ } catch {
1273
+ debugLog(`Could not load highlight style: ${options.highlight_style}`);
1274
+ }
1275
+ }
1276
+
1277
+ // Custom stylesheet
1278
+ const stylesheetPath = resolveStylesheetPath(
1279
+ path.dirname(inputPath),
1280
+ options.stylesheet_path,
1281
+ );
1282
+ if (stylesheetPath) {
1283
+ try {
1284
+ const customCss = await fs.readFile(stylesheetPath, "utf8");
1285
+ styleBlocks += `<style>${customCss}</style>\n `;
1286
+ } catch {
1287
+ debugLog(`Could not load stylesheet: ${stylesheetPath}`);
1288
+ }
1289
+ }
1290
+
1291
+ // Font choices come last: an explicit font must win over the root stack of
1292
+ // default.css and over a page style (look) that brings its own fonts.
1293
+ if (options.font_family) {
1294
+ styleBlocks += `<style>:root { font-family: ${options.font_family}; }</style>\n `;
1295
+ }
1296
+ if (options.heading_font_family) {
1297
+ styleBlocks += `<style>h1, h2, h3, h4, h5, h6 { font-family: ${options.heading_font_family}; }</style>\n `;
1298
+ }
1299
+
1300
+ const baseHref = `${pathToFileURL(path.dirname(inputPath)).href}/`;
1301
+
1302
+ return {
1303
+ html: `<!doctype html>
1304
+ <html lang="en">
1305
+ <head>
1306
+ <meta charset="utf-8">
1307
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1308
+ <title>${escapeHtml(title)}</title>
1309
+ <base href="${baseHref}">
1310
+ ${styleBlocks}
1311
+ </head>
1312
+ <body>
1313
+ <main>
1314
+ ${rendered}
1315
+ </main>
1316
+ </body>
1317
+ </html>`,
1318
+ title,
1319
+ };
1320
+ }
1321
+
1322
+ // ── Filesystem helpers ────────────────────────────────────────────────────────
1323
+ async function assertFileExists(filePath, label) {
1324
+ if (!(await fileExists(filePath))) {
1325
+ throw new Error(`${label} not found: ${filePath}`);
1326
+ }
1327
+ }
1328
+
1329
+ async function fileExists(filePath) {
1330
+ try {
1331
+ return (await fs.stat(filePath)).isFile();
1332
+ } catch {
1333
+ return false;
1334
+ }
1335
+ }
1336
+
1337
+ // ── Open file with OS default application ─────────────────────────────────────
1338
+ async function openFile(filePath) {
1339
+ const { spawn } = await import("node:child_process");
1340
+
1341
+ let command;
1342
+ let args;
1343
+
1344
+ if (process.platform === "darwin") {
1345
+ command = "open";
1346
+ args = [filePath];
1347
+ } else if (process.platform === "win32") {
1348
+ command = "cmd";
1349
+ args = ["/C", "start", "", filePath];
1350
+ } else {
1351
+ command = "xdg-open";
1352
+ args = [filePath];
1353
+ }
1354
+
1355
+ spawn(command, args, {
1356
+ detached: true,
1357
+ stdio: "ignore",
1358
+ }).unref();
1359
+ }
1360
+
1361
+ // ── Misc utilities ────────────────────────────────────────────────────────────
1362
+ function escapeHtml(value) {
1363
+ return String(value)
1364
+ .replaceAll("&", "&amp;")
1365
+ .replaceAll("<", "&lt;")
1366
+ .replaceAll(">", "&gt;")
1367
+ .replaceAll('"', "&quot;")
1368
+ .replaceAll("'", "&#39;");
1369
+ }