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.
@@ -0,0 +1,488 @@
1
+ /**
2
+ * @fileoverview Configuration merger for PDF export settings.
3
+ *
4
+ * This module handles merging configuration from multiple sources:
5
+ * 1. Extension defaults (lowest priority)
6
+ * 2. Global settings (from settings.json)
7
+ * 3. Front matter (highest priority)
8
+ *
9
+ * Key features:
10
+ * - Deep merge with zone-level override for header/footer
11
+ * - Support for explicit null to remove zones
12
+ * - Backward compatibility with raw HTML templates
13
+ * - Detection of structured vs. raw template mode
14
+ *
15
+ * @module config-merger
16
+ */
17
+
18
+ import { isStructuredConfig } from "./schema-validator.mjs";
19
+ import { DEFAULT_FOOTER } from "./types.mjs";
20
+
21
+ // ─────────────────────────────────────────────────────────────────────────────
22
+ // Constants
23
+ // ─────────────────────────────────────────────────────────────────────────────
24
+
25
+ /**
26
+ * Extension default configuration.
27
+ * Used when no settings or front matter is provided.
28
+ *
29
+ * @type {Readonly<Object>}
30
+ */
31
+ export const EXTENSION_DEFAULTS = Object.freeze({
32
+ // Page settings
33
+ page_format: "A4",
34
+ orientation: "portrait",
35
+ scale: 1,
36
+ page_ranges: "",
37
+ print_background: true,
38
+ margin: Object.freeze({
39
+ top: "15mm",
40
+ right: "15mm",
41
+ bottom: "15mm",
42
+ left: "15mm",
43
+ }),
44
+
45
+ // Rendering settings
46
+ font_family: null,
47
+ include_default_styles: true,
48
+ stylesheet_path: null,
49
+ highlight: true,
50
+ highlight_style: "github.css",
51
+ breaks: false,
52
+ emoji: true,
53
+
54
+ // Header/footer settings
55
+ display_header_footer: false,
56
+ header: null,
57
+ footer: null,
58
+
59
+ // Output settings
60
+ output_directory: null,
61
+ open_after_export: false,
62
+ });
63
+
64
+ /**
65
+ * Keys that are header/footer zone names.
66
+ * @type {Set<string>}
67
+ */
68
+ const ZONE_KEYS = new Set(["left", "center", "right"]);
69
+
70
+ // ─────────────────────────────────────────────────────────────────────────────
71
+ // Merge Utilities
72
+ // ─────────────────────────────────────────────────────────────────────────────
73
+
74
+ /**
75
+ * Check if a value is a plain object (not array, not null).
76
+ *
77
+ * @param {any} value - Value to check
78
+ * @returns {boolean}
79
+ */
80
+ function isPlainObject(value) {
81
+ return value !== null && typeof value === "object" && !Array.isArray(value);
82
+ }
83
+
84
+ /**
85
+ * Deep merge two objects.
86
+ * Later values override earlier values.
87
+ * Arrays are replaced, not merged.
88
+ *
89
+ * @param {Object} target - Target object
90
+ * @param {Object} source - Source object
91
+ * @returns {Object} Merged object
92
+ */
93
+ function deepMerge(target, source) {
94
+ if (!isPlainObject(target) || !isPlainObject(source)) {
95
+ return source;
96
+ }
97
+
98
+ const result = { ...target };
99
+
100
+ for (const [key, sourceValue] of Object.entries(source)) {
101
+ // Explicit null means "remove this"
102
+ if (sourceValue === null) {
103
+ result[key] = null;
104
+ continue;
105
+ }
106
+
107
+ // Undefined means "no override"
108
+ if (sourceValue === undefined) {
109
+ continue;
110
+ }
111
+
112
+ const targetValue = result[key];
113
+
114
+ // Deep merge for nested objects (except arrays)
115
+ if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
116
+ result[key] = deepMerge(targetValue, sourceValue);
117
+ } else {
118
+ result[key] = sourceValue;
119
+ }
120
+ }
121
+
122
+ return result;
123
+ }
124
+
125
+ /**
126
+ * Merge header/footer configurations with zone-level override.
127
+ *
128
+ * When a zone is defined in the source, it completely replaces the target zone.
129
+ * Container-level properties (height, padding, etc.) are merged.
130
+ *
131
+ * @param {Object|null} target - Target header/footer config
132
+ * @param {Object|null} source - Source header/footer config
133
+ * @returns {Object|null} Merged config
134
+ */
135
+ function mergeHeaderFooter(target, source) {
136
+ // Explicit null removes the header/footer
137
+ if (source === null) {
138
+ return null;
139
+ }
140
+
141
+ // No override
142
+ if (source === undefined || !isPlainObject(source)) {
143
+ return target;
144
+ }
145
+
146
+ // No target to merge with
147
+ if (!isPlainObject(target)) {
148
+ return source;
149
+ }
150
+
151
+ const result = { ...target };
152
+
153
+ for (const [key, value] of Object.entries(source)) {
154
+ if (ZONE_KEYS.has(key)) {
155
+ // Zones are replaced entirely (not merged)
156
+ // null explicitly removes the zone
157
+ result[key] = value;
158
+ } else {
159
+ // Other properties are merged normally
160
+ if (value !== undefined) {
161
+ result[key] = value;
162
+ }
163
+ }
164
+ }
165
+
166
+ return result;
167
+ }
168
+
169
+ // ─────────────────────────────────────────────────────────────────────────────
170
+ // Mode Detection
171
+ // ─────────────────────────────────────────────────────────────────────────────
172
+
173
+ /**
174
+ * @typedef {'structured'|'none'} HeaderFooterMode
175
+ */
176
+
177
+ /**
178
+ * Detect the header/footer mode from configuration.
179
+ *
180
+ * @param {Object} config - Configuration object
181
+ * @returns {HeaderFooterMode}
182
+ */
183
+ export function detectMode(config) {
184
+ if (!config || typeof config !== "object") {
185
+ return "none";
186
+ }
187
+
188
+ // Check for structured config (header/footer as objects)
189
+ if (isStructuredConfig(config)) {
190
+ return "structured";
191
+ }
192
+
193
+ return "none";
194
+ }
195
+
196
+ /**
197
+ * Check if configuration uses structured header/footer format.
198
+ *
199
+ * @param {Object} settings - Settings object
200
+ * @param {Object|null} frontMatterConfig - Front matter PDF config
201
+ * @returns {boolean}
202
+ */
203
+ export function usesStructuredConfig(settings, frontMatterConfig) {
204
+ // Front matter takes priority
205
+ if (frontMatterConfig && isStructuredConfig(frontMatterConfig)) {
206
+ return true;
207
+ }
208
+
209
+ // Check settings
210
+ if (settings && isStructuredConfig(settings)) {
211
+ return true;
212
+ }
213
+
214
+ return false;
215
+ }
216
+
217
+ // ─────────────────────────────────────────────────────────────────────────────
218
+ // Main Merge Function
219
+ // ─────────────────────────────────────────────────────────────────────────────
220
+
221
+ /**
222
+ * @typedef {Object} MergeOptions
223
+ * @property {boolean} [applyDefaults=true] - Whether to apply extension defaults
224
+ */
225
+
226
+ /**
227
+ * @typedef {Object} MergedConfig
228
+ * @property {Object} config - Merged configuration
229
+ * @property {boolean} hasHeaderFooter - Whether header/footer is enabled
230
+ * @property {string[]} sources - List of sources that contributed to the config
231
+ */
232
+
233
+ /**
234
+ * Merge configuration from multiple sources.
235
+ *
236
+ * Priority (lowest to highest):
237
+ * 1. Extension defaults
238
+ * 2. Global settings
239
+ * 3. Front matter
240
+ *
241
+ * @param {Object} [settings={}] - Global settings from settings.json
242
+ * @param {Object|null} [frontMatterConfig=null] - PDF config from front matter
243
+ * @param {MergeOptions} [options={}] - Merge options
244
+ * @returns {MergedConfig}
245
+ *
246
+ * @example
247
+ * const { config, mode } = mergeConfig(
248
+ * { page_format: 'Letter', header: { left_text: 'Company' } },
249
+ * { header: { left_image: './logo.svg' } }
250
+ * );
251
+ * // config.header will have left_image (front matter overrides)
252
+ * // config.page_format will be 'Letter' (from settings)
253
+ */
254
+ export function mergeConfig(
255
+ settings = {},
256
+ frontMatterConfig = null,
257
+ options = {},
258
+ ) {
259
+ const { applyDefaults = true } = options;
260
+
261
+ const sources = [];
262
+
263
+ // Start with defaults if requested
264
+ let result = applyDefaults ? { ...EXTENSION_DEFAULTS } : {};
265
+ if (applyDefaults) {
266
+ sources.push("defaults");
267
+ }
268
+
269
+ // Merge global settings
270
+ if (
271
+ settings &&
272
+ typeof settings === "object" &&
273
+ Object.keys(settings).length > 0
274
+ ) {
275
+ sources.push("settings");
276
+
277
+ for (const [key, value] of Object.entries(settings)) {
278
+ if (value === undefined) {
279
+ continue;
280
+ }
281
+
282
+ if (key === "header" || key === "footer") {
283
+ result[key] = mergeHeaderFooter(result[key], value);
284
+ } else if (key === "margin" && isPlainObject(value)) {
285
+ result[key] = { ...result[key], ...value };
286
+ } else {
287
+ result[key] = value;
288
+ }
289
+ }
290
+ }
291
+
292
+ // Merge front matter config (highest priority)
293
+ if (frontMatterConfig && typeof frontMatterConfig === "object") {
294
+ sources.push("frontmatter");
295
+
296
+ for (const [key, value] of Object.entries(frontMatterConfig)) {
297
+ if (value === undefined) {
298
+ continue;
299
+ }
300
+
301
+ if (key === "header" || key === "footer") {
302
+ result[key] = mergeHeaderFooter(result[key], value);
303
+ } else if (key === "margin" && isPlainObject(value)) {
304
+ result[key] = { ...result[key], ...value };
305
+ } else {
306
+ result[key] = value;
307
+ }
308
+ }
309
+ }
310
+
311
+ // Detect mode
312
+ const mode = detectMode(result);
313
+
314
+ // Determine if header/footer is enabled
315
+ let hasHeaderFooter = false;
316
+
317
+ if (mode === "structured") {
318
+ // In structured mode, having header or footer config enables display
319
+ hasHeaderFooter = result.header !== null || result.footer !== null;
320
+
321
+ // Auto-enable display_header_footer if we have structured config
322
+ if (hasHeaderFooter && result.display_header_footer !== true) {
323
+ result.display_header_footer = true;
324
+ }
325
+
326
+ // Apply default footer if header is set but footer is not
327
+ if (result.header && !result.footer && result.footer !== null) {
328
+ result.footer = { ...DEFAULT_FOOTER };
329
+ }
330
+ }
331
+
332
+ return {
333
+ config: result,
334
+ mode,
335
+ hasHeaderFooter,
336
+ sources,
337
+ };
338
+ }
339
+
340
+ // ─────────────────────────────────────────────────────────────────────────────
341
+ // Convenience Functions
342
+ // ─────────────────────────────────────────────────────────────────────────────
343
+
344
+ /**
345
+ * Extract just the header configuration from merged config.
346
+ *
347
+ * @param {Object} mergedConfig - Result from mergeConfig
348
+ * @returns {Object|null}
349
+ */
350
+ export function getHeaderConfig(mergedConfig) {
351
+ return mergedConfig?.config?.header || null;
352
+ }
353
+
354
+ /**
355
+ * Extract just the footer configuration from merged config.
356
+ *
357
+ * @param {Object} mergedConfig - Result from mergeConfig
358
+ * @returns {Object|null}
359
+ */
360
+ export function getFooterConfig(mergedConfig) {
361
+ return mergedConfig?.config?.footer || null;
362
+ }
363
+
364
+ /**
365
+ * Check if the merged config has a structured header.
366
+ *
367
+ * @param {Object} mergedConfig - Result from mergeConfig
368
+ * @returns {boolean}
369
+ */
370
+ export function hasStructuredHeader(mergedConfig) {
371
+ const header = getHeaderConfig(mergedConfig);
372
+ return header !== null && typeof header === "object";
373
+ }
374
+
375
+ /**
376
+ * Check if the merged config has a structured footer.
377
+ *
378
+ * @param {Object} mergedConfig - Result from mergeConfig
379
+ * @returns {boolean}
380
+ */
381
+ export function hasStructuredFooter(mergedConfig) {
382
+ const footer = getFooterConfig(mergedConfig);
383
+ return footer !== null && typeof footer === "object";
384
+ }
385
+
386
+ /**
387
+ * Get page settings from merged config.
388
+ *
389
+ * @param {Object} mergedConfig - Result from mergeConfig
390
+ * @returns {Object}
391
+ */
392
+ export function getPageSettings(mergedConfig) {
393
+ const config = mergedConfig?.config || {};
394
+
395
+ return {
396
+ page_format: config.page_format || EXTENSION_DEFAULTS.page_format,
397
+ orientation: config.orientation || EXTENSION_DEFAULTS.orientation,
398
+ scale: config.scale ?? EXTENSION_DEFAULTS.scale,
399
+ page_ranges: config.page_ranges || "",
400
+ print_background:
401
+ config.print_background ?? EXTENSION_DEFAULTS.print_background,
402
+ margin: config.margin || { ...EXTENSION_DEFAULTS.margin },
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Get rendering settings from merged config.
408
+ *
409
+ * @param {Object} mergedConfig - Result from mergeConfig
410
+ * @returns {Object}
411
+ */
412
+ export function getRenderSettings(mergedConfig) {
413
+ const config = mergedConfig?.config || {};
414
+
415
+ return {
416
+ font_family: config.font_family || null,
417
+ include_default_styles:
418
+ config.include_default_styles ??
419
+ EXTENSION_DEFAULTS.include_default_styles,
420
+ stylesheet_path: config.stylesheet_path || null,
421
+ highlight: config.highlight ?? EXTENSION_DEFAULTS.highlight,
422
+ highlight_style:
423
+ config.highlight_style || EXTENSION_DEFAULTS.highlight_style,
424
+ breaks: config.breaks ?? EXTENSION_DEFAULTS.breaks,
425
+ emoji: config.emoji ?? EXTENSION_DEFAULTS.emoji,
426
+ };
427
+ }
428
+
429
+ // ─────────────────────────────────────────────────────────────────────────────
430
+ // Merger Factory
431
+ // ─────────────────────────────────────────────────────────────────────────────
432
+
433
+ /**
434
+ * @typedef {Object} ConfigMerger
435
+ * @property {(frontMatterConfig?: Object|null) => MergedConfig} merge - Merge with front matter
436
+ * @property {() => Object} getSettings - Get current settings
437
+ * @property {(newSettings: Object) => void} updateSettings - Update settings
438
+ */
439
+
440
+ /**
441
+ * Create a config merger bound to specific settings.
442
+ *
443
+ * Useful when you have global settings that stay constant
444
+ * and only the front matter changes per document.
445
+ *
446
+ * @param {Object} [settings={}] - Global settings
447
+ * @param {MergeOptions} [options={}] - Merge options
448
+ * @returns {ConfigMerger}
449
+ *
450
+ * @example
451
+ * const merger = createConfigMerger(globalSettings);
452
+ *
453
+ * // For each document
454
+ * const { config, mode } = merger.merge(documentFrontMatter.pdfConfig);
455
+ */
456
+ export function createConfigMerger(settings = {}, options = {}) {
457
+ let currentSettings = { ...settings };
458
+
459
+ return {
460
+ /**
461
+ * Merge current settings with front matter config.
462
+ *
463
+ * @param {Object|null} [frontMatterConfig=null] - PDF config from front matter
464
+ * @returns {MergedConfig}
465
+ */
466
+ merge(frontMatterConfig = null) {
467
+ return mergeConfig(currentSettings, frontMatterConfig, options);
468
+ },
469
+
470
+ /**
471
+ * Get current settings.
472
+ *
473
+ * @returns {Object}
474
+ */
475
+ getSettings() {
476
+ return { ...currentSettings };
477
+ },
478
+
479
+ /**
480
+ * Update settings.
481
+ *
482
+ * @param {Object} newSettings - New settings to merge
483
+ */
484
+ updateSettings(newSettings) {
485
+ currentSettings = deepMerge(currentSettings, newSettings);
486
+ },
487
+ };
488
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @fileoverview Plain-language rendering of the doctor report: a checklist
3
+ * where every problem comes with the one command that fixes it.
4
+ */
5
+
6
+ /**
7
+ * @param {object} report result of doctorMarkdownPdf()
8
+ * @param {{bin?: string, nodeVersion?: string}} [opts]
9
+ * @returns {{text: string, ok: boolean}}
10
+ */
11
+ export function formatDoctor(report, { bin = "markdown-pdf-export", nodeVersion = process.versions.node } = {}) {
12
+ const lines = [];
13
+ let ok = true;
14
+ const good = (msg) => lines.push(` ✓ ${msg}`);
15
+ const bad = (msg, fix) => {
16
+ ok = false;
17
+ lines.push(` ✗ ${msg}`);
18
+ if (fix) lines.push(` fix: ${fix}`);
19
+ };
20
+ const info = (msg, hint) => {
21
+ lines.push(` · ${msg}`);
22
+ if (hint) lines.push(` ${hint}`);
23
+ };
24
+
25
+ const major = Number.parseInt(nodeVersion, 10);
26
+ if (major >= 20) good(`Node ${nodeVersion}`);
27
+ else bad(`Node ${nodeVersion} is too old (needs 20 or newer)`, "install Node 20+ from nodejs.org");
28
+
29
+ const b = report.browser ?? {};
30
+ if (b.available) good(`Browser: ${b.backend ?? "Chromium"} ${b.version ?? ""}`.trim());
31
+ else bad("No browser found (needed to draw the PDF)", `${bin} install-browser (or install Chrome / Edge)`);
32
+
33
+ const sources = report.settings_sources ?? [];
34
+ const loaded = sources.filter((s) => s.loaded);
35
+ for (const s of sources) {
36
+ if (s.error) bad(`Settings file has an error: ${s.path ?? s.kind}\n ${s.error}`, "open the file and fix the JSON");
37
+ else if (s.loaded) good(`Settings: ${s.path ?? "MARKDOWN_PDF_SETTINGS (inline)"}`);
38
+ }
39
+ if (loaded.length === 0 && !sources.some((s) => s.error)) {
40
+ info("No settings file — built-in defaults are used", `create one: ${bin} init`);
41
+ }
42
+
43
+ const st = report.settings ?? {};
44
+ const hf = st.display_header_footer || st.header || st.footer;
45
+ info(
46
+ `Page: ${st.page_format ?? "A4"}, ${st.orientation ?? "portrait"} · header/footer: ${hf ? "on" : "off"}` +
47
+ (st.font_family ? " · custom font" : ""),
48
+ );
49
+
50
+ const head = ok ? "Everything is ready." : "Something needs attention:";
51
+ return { text: `${head}\n\n${lines.join("\n")}\n`, ok };
52
+ }