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/LICENSE +21 -0
- package/README.md +91 -2
- package/cli.mjs +695 -0
- package/default.css +230 -0
- package/export.mjs +1369 -0
- package/lib/asset-resolver.mjs +493 -0
- package/lib/config-merger.mjs +488 -0
- package/lib/doctor-report.mjs +52 -0
- package/lib/editor-setup.mjs +280 -0
- package/lib/frontmatter-parser.mjs +595 -0
- package/lib/html-generator.mjs +837 -0
- package/lib/looks.mjs +150 -0
- package/lib/placeholder-resolver.mjs +490 -0
- package/lib/schema-validator.mjs +725 -0
- package/lib/settings-loader.mjs +167 -0
- package/lib/settings-schema.mjs +192 -0
- package/lib/studio-server.mjs +490 -0
- package/lib/types.mjs +334 -0
- package/looks/academic.css +8 -0
- package/looks/compact.css +5 -0
- package/looks/report.css +8 -0
- package/looks/technical.css +11 -0
- package/mcp.mjs +263 -0
- package/package.json +97 -4
- package/schema/settings.schema.json +768 -0
- package/studio/app.mjs +589 -0
- package/studio/index.html +113 -0
- package/studio/model.mjs +316 -0
- package/studio/sample.md +53 -0
- package/studio/style.css +497 -0
- package/templates/academic.json +26 -0
- package/templates/corporate.json +24 -0
- package/templates/minimal.json +6 -0
- package/templates/simple.json +12 -0
- package/templates/two-logo.json +27 -0
- package/tool-schemas.mjs +215 -0
- package/vendor/katex-inline.css +1 -0
package/lib/looks.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Beginner-facing presets. A settings file can be as short as
|
|
3
|
+
* { "look": "report", "font": "serif", "template": "corporate" }
|
|
4
|
+
*
|
|
5
|
+
* - look → stylesheet + code theme + margins (looks/*.css)
|
|
6
|
+
* - font → a safe font stack for the text (heading_font: same, for titles)
|
|
7
|
+
* - template → header/footer preset (templates/*.json)
|
|
8
|
+
*
|
|
9
|
+
* Explicit keys in the same file always win over presets; template wins over look.
|
|
10
|
+
*/
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
|
|
15
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
16
|
+
|
|
17
|
+
/** @type {Record<string, {description: string, settings: object}>} */
|
|
18
|
+
export const LOOKS = {
|
|
19
|
+
clean: {
|
|
20
|
+
description: "Default. GitHub-style, neutral.",
|
|
21
|
+
settings: {},
|
|
22
|
+
},
|
|
23
|
+
report: {
|
|
24
|
+
description: "Serif headings, strong title rule. Business reports.",
|
|
25
|
+
settings: { stylesheet: "report.css", highlight_style: "github.css" },
|
|
26
|
+
},
|
|
27
|
+
academic: {
|
|
28
|
+
description: "Serif body, justified, minimal colour. Papers and theses.",
|
|
29
|
+
settings: {
|
|
30
|
+
stylesheet: "academic.css",
|
|
31
|
+
highlight_style: "ascetic.css",
|
|
32
|
+
margin: { top: "25mm", right: "25mm", bottom: "25mm", left: "25mm" },
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
compact: {
|
|
36
|
+
description: "Dense and small. More text per page.",
|
|
37
|
+
settings: {
|
|
38
|
+
stylesheet: "compact.css",
|
|
39
|
+
margin: { top: "10mm", right: "10mm", bottom: "10mm", left: "10mm" },
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
technical: {
|
|
43
|
+
description: "For documents with code: framed code blocks, blue accents.",
|
|
44
|
+
settings: { stylesheet: "technical.css", highlight_style: "atom-one-light.css" },
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const FONTS = {
|
|
49
|
+
sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',
|
|
50
|
+
serif: 'Georgia, "Times New Roman", Times, serif',
|
|
51
|
+
book: '"Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif',
|
|
52
|
+
humanist: 'Seravek, "Gill Sans Nova", "Gill Sans", Ubuntu, Calibri, "DejaVu Sans", sans-serif',
|
|
53
|
+
geometric: 'Avenir, "Avenir Next", Montserrat, Corbel, "Century Gothic", "URW Gothic", sans-serif',
|
|
54
|
+
mono: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
|
|
55
|
+
system: "system-ui, sans-serif",
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Names shown to people (Studio, init). */
|
|
59
|
+
export const FONT_LABELS = {
|
|
60
|
+
sans: "Sans",
|
|
61
|
+
serif: "Serif",
|
|
62
|
+
book: "Book serif",
|
|
63
|
+
humanist: "Humanist sans",
|
|
64
|
+
geometric: "Geometric sans",
|
|
65
|
+
mono: "Mono",
|
|
66
|
+
system: "System",
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Short list of code colour themes offered in Studio (any highlight.js theme works in a file). */
|
|
70
|
+
export const CODE_THEMES = [
|
|
71
|
+
{ file: "github.css", label: "GitHub light" },
|
|
72
|
+
{ file: "github-dark.css", label: "GitHub dark" },
|
|
73
|
+
{ file: "atom-one-light.css", label: "Atom One light" },
|
|
74
|
+
{ file: "atom-one-dark.css", label: "Atom One dark" },
|
|
75
|
+
{ file: "vs.css", label: "Visual Studio light" },
|
|
76
|
+
{ file: "vs2015.css", label: "Visual Studio dark" },
|
|
77
|
+
{ file: "xcode.css", label: "Xcode light" },
|
|
78
|
+
{ file: "monokai.css", label: "Monokai dark" },
|
|
79
|
+
{ file: "nord.css", label: "Nord dark" },
|
|
80
|
+
{ file: "tokyo-night-dark.css", label: "Tokyo Night dark" },
|
|
81
|
+
{ file: "ascetic.css", label: "Black and white" },
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
export const TEMPLATES = ["minimal", "simple", "corporate", "academic", "two-logo"];
|
|
85
|
+
|
|
86
|
+
export const looksDir = () => path.join(ROOT, "looks");
|
|
87
|
+
export const templatesDir = () => path.join(ROOT, "templates");
|
|
88
|
+
|
|
89
|
+
/** Read a shipped header/footer template (without its $schema line). */
|
|
90
|
+
export function readTemplate(name) {
|
|
91
|
+
if (!TEMPLATES.includes(name)) return null;
|
|
92
|
+
const data = JSON.parse(fs.readFileSync(path.join(templatesDir(), `${name}.json`), "utf8"));
|
|
93
|
+
delete data.$schema;
|
|
94
|
+
return data;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
98
|
+
|
|
99
|
+
function merge(base, over) {
|
|
100
|
+
const out = { ...base };
|
|
101
|
+
for (const [k, v] of Object.entries(over)) {
|
|
102
|
+
out[k] = isPlain(v) && isPlain(out[k]) ? merge(out[k], v) : v;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Expand `look` / `font` / `template` in one raw settings object.
|
|
109
|
+
* Unknown names are reported in `warnings` and ignored.
|
|
110
|
+
* @param {object} data
|
|
111
|
+
* @returns {{data: object, warnings: string[]}}
|
|
112
|
+
*/
|
|
113
|
+
export function applyPresets(data) {
|
|
114
|
+
if (!isPlain(data)) return { data, warnings: [] };
|
|
115
|
+
const { look, font, heading_font, template, ...explicit } = data;
|
|
116
|
+
if (look === undefined && font === undefined && heading_font === undefined && template === undefined) {
|
|
117
|
+
return { data, warnings: [] };
|
|
118
|
+
}
|
|
119
|
+
const warnings = [];
|
|
120
|
+
let base = {};
|
|
121
|
+
|
|
122
|
+
if (look !== undefined) {
|
|
123
|
+
const def = LOOKS[look];
|
|
124
|
+
if (!def) {
|
|
125
|
+
warnings.push(`unknown look "${look}" (use: ${Object.keys(LOOKS).join(", ")})`);
|
|
126
|
+
} else {
|
|
127
|
+
const { stylesheet, ...rest } = def.settings;
|
|
128
|
+
base = merge(base, rest);
|
|
129
|
+
if (stylesheet) base.stylesheet_path = path.join(looksDir(), stylesheet);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (template !== undefined) {
|
|
133
|
+
const tpl = typeof template === "string" ? readTemplate(template) : null;
|
|
134
|
+
if (!tpl) {
|
|
135
|
+
warnings.push(`unknown template "${template}" (use: ${TEMPLATES.join(", ")})`);
|
|
136
|
+
} else {
|
|
137
|
+
base = merge(base, tpl);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (font !== undefined) {
|
|
141
|
+
if (!FONTS[font]) warnings.push(`unknown font "${font}" (use: ${Object.keys(FONTS).join(", ")})`);
|
|
142
|
+
else base.font_family = FONTS[font];
|
|
143
|
+
}
|
|
144
|
+
if (heading_font !== undefined) {
|
|
145
|
+
if (!FONTS[heading_font]) {
|
|
146
|
+
warnings.push(`unknown heading_font "${heading_font}" (use: ${Object.keys(FONTS).join(", ")})`);
|
|
147
|
+
} else base.heading_font_family = FONTS[heading_font];
|
|
148
|
+
}
|
|
149
|
+
return { data: merge(base, explicit), warnings };
|
|
150
|
+
}
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Placeholder resolver for header/footer templates.
|
|
3
|
+
*
|
|
4
|
+
* This module handles:
|
|
5
|
+
* - Parsing placeholder syntax: {name} and {name:format}
|
|
6
|
+
* - Mapping page placeholders to Playwright span classes
|
|
7
|
+
* - Resolving date/time with date-fns formatting
|
|
8
|
+
* - Resolving document metadata (title, filename, author)
|
|
9
|
+
* - Supporting custom front matter variables
|
|
10
|
+
*
|
|
11
|
+
* @module placeholder-resolver
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// ── Lazy-loaded npm dependency ────────────────────────────────────────────────
|
|
15
|
+
// Loaded dynamically so the MCP handshake can succeed before `npm install` runs.
|
|
16
|
+
let formatDate = null;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Ensure the `date-fns` package is loaded. Must be called (and awaited)
|
|
20
|
+
* before any function in this module that depends on date formatting.
|
|
21
|
+
*/
|
|
22
|
+
export async function ensureDateFnsLoaded() {
|
|
23
|
+
if (!formatDate) {
|
|
24
|
+
formatDate = (await import("date-fns")).format;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
import { PLACEHOLDER_PATTERN, BUILTIN_PLACEHOLDERS } from "./types.mjs";
|
|
29
|
+
|
|
30
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
31
|
+
// Constants
|
|
32
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Default date format (ISO date).
|
|
36
|
+
* @type {string}
|
|
37
|
+
*/
|
|
38
|
+
const DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Default time format (ISO time).
|
|
42
|
+
* @type {string}
|
|
43
|
+
*/
|
|
44
|
+
const DEFAULT_TIME_FORMAT = "HH:mm:ss";
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Default datetime format.
|
|
48
|
+
* @type {string}
|
|
49
|
+
*/
|
|
50
|
+
const DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Mapping of placeholder names to Playwright span classes.
|
|
54
|
+
* These are rendered by Chromium at print time.
|
|
55
|
+
*
|
|
56
|
+
* @type {Readonly<Object.<string, string>>}
|
|
57
|
+
*/
|
|
58
|
+
const PLAYWRIGHT_SPANS = Object.freeze({
|
|
59
|
+
page: "pageNumber",
|
|
60
|
+
pages: "totalPages",
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
64
|
+
// Placeholder Parsing
|
|
65
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @typedef {Object} ParsedPlaceholder
|
|
69
|
+
* @property {string} full - Full match including braces, e.g., "{date:yyyy-MM-dd}"
|
|
70
|
+
* @property {string} name - Placeholder name, e.g., "date"
|
|
71
|
+
* @property {string|null} format - Optional format string, e.g., "yyyy-MM-dd"
|
|
72
|
+
* @property {number} start - Start index in the original string
|
|
73
|
+
* @property {number} end - End index in the original string
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Parse all placeholders in a string.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} text - Text containing placeholders
|
|
80
|
+
* @returns {ParsedPlaceholder[]} Array of parsed placeholders
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* parsePlaceholders("Page {page} of {pages}")
|
|
84
|
+
* // Returns: [
|
|
85
|
+
* // { full: "{page}", name: "page", format: null, start: 5, end: 11 },
|
|
86
|
+
* // { full: "{pages}", name: "pages", format: null, start: 15, end: 22 }
|
|
87
|
+
* // ]
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* parsePlaceholders("Date: {date:MM/dd/yyyy}")
|
|
91
|
+
* // Returns: [
|
|
92
|
+
* // { full: "{date:MM/dd/yyyy}", name: "date", format: "MM/dd/yyyy", start: 6, end: 23 }
|
|
93
|
+
* // ]
|
|
94
|
+
*/
|
|
95
|
+
export function parsePlaceholders(text) {
|
|
96
|
+
if (typeof text !== "string") {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const placeholders = [];
|
|
101
|
+
// Create a new regex instance to avoid state issues with lastIndex
|
|
102
|
+
const regex = new RegExp(PLACEHOLDER_PATTERN.source, "g");
|
|
103
|
+
let match;
|
|
104
|
+
|
|
105
|
+
while ((match = regex.exec(text)) !== null) {
|
|
106
|
+
placeholders.push({
|
|
107
|
+
full: match[0],
|
|
108
|
+
name: match[1].toLowerCase(),
|
|
109
|
+
format: match[2] || null,
|
|
110
|
+
start: match.index,
|
|
111
|
+
end: match.index + match[0].length,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return placeholders;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Check if a placeholder name is a built-in placeholder.
|
|
120
|
+
*
|
|
121
|
+
* @param {string} name - Placeholder name
|
|
122
|
+
* @returns {boolean}
|
|
123
|
+
*/
|
|
124
|
+
export function isBuiltinPlaceholder(name) {
|
|
125
|
+
return BUILTIN_PLACEHOLDERS.includes(name.toLowerCase());
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Check if a placeholder should be rendered as a Playwright span.
|
|
130
|
+
*
|
|
131
|
+
* @param {string} name - Placeholder name
|
|
132
|
+
* @returns {boolean}
|
|
133
|
+
*/
|
|
134
|
+
export function isPlaywrightPlaceholder(name) {
|
|
135
|
+
return name.toLowerCase() in PLAYWRIGHT_SPANS;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
139
|
+
// Date/Time Formatting
|
|
140
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Format a date using date-fns.
|
|
144
|
+
*
|
|
145
|
+
* @param {Date} date - Date to format
|
|
146
|
+
* @param {string} [formatStr] - date-fns format string
|
|
147
|
+
* @returns {string} Formatted date string
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* formatDateTime(new Date(2025, 0, 15), "MM/dd/yyyy") // "01/15/2025"
|
|
151
|
+
* formatDateTime(new Date(2025, 0, 15), "MMMM d, yyyy") // "January 15, 2025"
|
|
152
|
+
* formatDateTime(new Date(2025, 0, 15), "dd.MM.yyyy") // "15.01.2025" (EU format)
|
|
153
|
+
*/
|
|
154
|
+
export function formatDateTime(date, formatStr = DEFAULT_DATE_FORMAT) {
|
|
155
|
+
try {
|
|
156
|
+
return formatDate(date, formatStr);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
// If format string is invalid, return ISO date
|
|
159
|
+
console.warn(`Invalid date format "${formatStr}": ${error.message}`);
|
|
160
|
+
return formatDate(date, DEFAULT_DATE_FORMAT);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Get common date format presets.
|
|
166
|
+
*
|
|
167
|
+
* @returns {Object.<string, string>} Map of preset names to format strings
|
|
168
|
+
*/
|
|
169
|
+
export function getDateFormatPresets() {
|
|
170
|
+
return {
|
|
171
|
+
// ISO formats
|
|
172
|
+
iso: "yyyy-MM-dd",
|
|
173
|
+
"iso-time": "HH:mm:ss",
|
|
174
|
+
"iso-datetime": "yyyy-MM-dd HH:mm:ss",
|
|
175
|
+
|
|
176
|
+
// US formats
|
|
177
|
+
us: "MM/dd/yyyy",
|
|
178
|
+
"us-long": "MMMM d, yyyy",
|
|
179
|
+
"us-short": "M/d/yy",
|
|
180
|
+
|
|
181
|
+
// EU formats
|
|
182
|
+
eu: "dd/MM/yyyy",
|
|
183
|
+
"eu-long": "d MMMM yyyy",
|
|
184
|
+
"eu-short": "d/M/yy",
|
|
185
|
+
"eu-dot": "dd.MM.yyyy",
|
|
186
|
+
|
|
187
|
+
// Other common formats
|
|
188
|
+
full: "EEEE, MMMM d, yyyy",
|
|
189
|
+
medium: "MMM d, yyyy",
|
|
190
|
+
short: "M/d/yy",
|
|
191
|
+
year: "yyyy",
|
|
192
|
+
month: "MMMM",
|
|
193
|
+
day: "d",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A preset name ("iso", "us-long", …) → its format string; anything else as given. */
|
|
198
|
+
function namedFormat(format) {
|
|
199
|
+
if (!format) return format;
|
|
200
|
+
return Object.hasOwn(getDateFormatPresets(), format) ? getDateFormatPresets()[format] : format;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
204
|
+
// Placeholder Resolution
|
|
205
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Resolve a single placeholder to its value or HTML.
|
|
209
|
+
*
|
|
210
|
+
* @param {ParsedPlaceholder} placeholder - Parsed placeholder
|
|
211
|
+
* @param {import('./types.mjs').RenderContext} context - Render context
|
|
212
|
+
* @returns {string} Resolved value or HTML
|
|
213
|
+
*/
|
|
214
|
+
export function resolvePlaceholder(placeholder, context) {
|
|
215
|
+
const { name, format } = placeholder;
|
|
216
|
+
const { title, author, filename, now, customVariables = {} } = context;
|
|
217
|
+
|
|
218
|
+
switch (name) {
|
|
219
|
+
// Playwright-rendered placeholders (rendered at print time by Chromium)
|
|
220
|
+
case "page":
|
|
221
|
+
return `<span class="${PLAYWRIGHT_SPANS.page}"></span>`;
|
|
222
|
+
|
|
223
|
+
case "pages":
|
|
224
|
+
return `<span class="${PLAYWRIGHT_SPANS.pages}"></span>`;
|
|
225
|
+
|
|
226
|
+
// Date/time placeholders (resolved at export time)
|
|
227
|
+
case "date":
|
|
228
|
+
return formatDateTime(now, namedFormat(format) || DEFAULT_DATE_FORMAT);
|
|
229
|
+
|
|
230
|
+
case "time":
|
|
231
|
+
return formatDateTime(now, namedFormat(format) || DEFAULT_TIME_FORMAT);
|
|
232
|
+
|
|
233
|
+
case "datetime":
|
|
234
|
+
return formatDateTime(now, namedFormat(format) || DEFAULT_DATETIME_FORMAT);
|
|
235
|
+
|
|
236
|
+
// Document metadata
|
|
237
|
+
case "title":
|
|
238
|
+
return escapeHtml(title || "");
|
|
239
|
+
|
|
240
|
+
case "filename":
|
|
241
|
+
return escapeHtml(filename || "");
|
|
242
|
+
|
|
243
|
+
case "author":
|
|
244
|
+
return escapeHtml(author || "");
|
|
245
|
+
|
|
246
|
+
// Custom variables from front matter
|
|
247
|
+
default:
|
|
248
|
+
if (name in customVariables) {
|
|
249
|
+
return escapeHtml(String(customVariables[name]));
|
|
250
|
+
}
|
|
251
|
+
// Unknown placeholder - return as-is (might be intentional)
|
|
252
|
+
return placeholder.full;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Resolve all placeholders in a text string.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} text - Text containing placeholders
|
|
260
|
+
* @param {import('./types.mjs').RenderContext} context - Render context
|
|
261
|
+
* @returns {string} Text with all placeholders resolved
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* resolvePlaceholders("Page {page} of {pages}", context)
|
|
265
|
+
* // Returns: "Page <span class="pageNumber"></span> of <span class="totalPages"></span>"
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* resolvePlaceholders("Date: {date:MM/dd/yyyy}", { now: new Date(2025, 0, 15), ... })
|
|
269
|
+
* // Returns: "Date: 01/15/2025"
|
|
270
|
+
*/
|
|
271
|
+
export function resolvePlaceholders(text, context) {
|
|
272
|
+
if (typeof text !== "string") {
|
|
273
|
+
return "";
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const placeholders = parsePlaceholders(text);
|
|
277
|
+
|
|
278
|
+
if (placeholders.length === 0) {
|
|
279
|
+
return text;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Process placeholders from end to start to preserve indices
|
|
283
|
+
let result = text;
|
|
284
|
+
for (let i = placeholders.length - 1; i >= 0; i--) {
|
|
285
|
+
const placeholder = placeholders[i];
|
|
286
|
+
const resolved = resolvePlaceholder(placeholder, context);
|
|
287
|
+
result =
|
|
288
|
+
result.slice(0, placeholder.start) +
|
|
289
|
+
resolved +
|
|
290
|
+
result.slice(placeholder.end);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
297
|
+
// Context Creation
|
|
298
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* @typedef {Object} CreateContextOptions
|
|
302
|
+
* @property {string} inputPath - Path to the Markdown file
|
|
303
|
+
* @property {string} [title] - Document title (from front matter or H1)
|
|
304
|
+
* @property {string} [author] - Document author (from front matter)
|
|
305
|
+
* @property {Object.<string, any>} [frontMatter] - All front matter fields
|
|
306
|
+
* @property {Date} [now] - Current date/time (defaults to new Date())
|
|
307
|
+
*/
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Create a render context from document information.
|
|
311
|
+
*
|
|
312
|
+
* @param {CreateContextOptions} options - Context options
|
|
313
|
+
* @returns {import('./types.mjs').RenderContext}
|
|
314
|
+
*/
|
|
315
|
+
export function createRenderContext(options) {
|
|
316
|
+
const {
|
|
317
|
+
inputPath,
|
|
318
|
+
title = "",
|
|
319
|
+
author = "",
|
|
320
|
+
frontMatter = {},
|
|
321
|
+
now = new Date(),
|
|
322
|
+
} = options;
|
|
323
|
+
|
|
324
|
+
// Extract filename from path
|
|
325
|
+
const filename = inputPath ? inputPath.split(/[/\\]/).pop() || "" : "";
|
|
326
|
+
|
|
327
|
+
// Build custom variables from front matter (excluding known fields)
|
|
328
|
+
const knownFields = new Set(["title", "author", "date", "pdf"]);
|
|
329
|
+
const customVariables = {};
|
|
330
|
+
|
|
331
|
+
for (const [key, value] of Object.entries(frontMatter)) {
|
|
332
|
+
if (!knownFields.has(key) && value !== null && value !== undefined) {
|
|
333
|
+
customVariables[key.toLowerCase()] = value;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return {
|
|
338
|
+
title,
|
|
339
|
+
author,
|
|
340
|
+
filename,
|
|
341
|
+
inputPath,
|
|
342
|
+
now,
|
|
343
|
+
customVariables,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
348
|
+
// Placeholder Resolver Factory
|
|
349
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* @typedef {Object} PlaceholderResolver
|
|
353
|
+
* @property {(text: string) => string} resolve - Resolve all placeholders in text
|
|
354
|
+
* @property {(text: string) => ParsedPlaceholder[]} parse - Parse placeholders without resolving
|
|
355
|
+
* @property {() => import('./types.mjs').RenderContext} getContext - Get the current context
|
|
356
|
+
* @property {(updates: Partial<import('./types.mjs').RenderContext>) => void} updateContext - Update context
|
|
357
|
+
*/
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Create a placeholder resolver bound to a specific context.
|
|
361
|
+
*
|
|
362
|
+
* @param {import('./types.mjs').RenderContext} context - Initial render context
|
|
363
|
+
* @returns {PlaceholderResolver}
|
|
364
|
+
*
|
|
365
|
+
* @example
|
|
366
|
+
* const resolver = createPlaceholderResolver({
|
|
367
|
+
* title: "My Document",
|
|
368
|
+
* filename: "doc.md",
|
|
369
|
+
* inputPath: "/path/to/doc.md",
|
|
370
|
+
* now: new Date(),
|
|
371
|
+
* });
|
|
372
|
+
*
|
|
373
|
+
* resolver.resolve("Page {page} - {title}")
|
|
374
|
+
* // Returns: "Page <span class="pageNumber"></span> - My Document"
|
|
375
|
+
*/
|
|
376
|
+
export function createPlaceholderResolver(context) {
|
|
377
|
+
let currentContext = { ...context };
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
/**
|
|
381
|
+
* Resolve all placeholders in text.
|
|
382
|
+
* @param {string} text
|
|
383
|
+
* @returns {string}
|
|
384
|
+
*/
|
|
385
|
+
resolve(text) {
|
|
386
|
+
return resolvePlaceholders(text, currentContext);
|
|
387
|
+
},
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Parse placeholders without resolving.
|
|
391
|
+
* @param {string} text
|
|
392
|
+
* @returns {ParsedPlaceholder[]}
|
|
393
|
+
*/
|
|
394
|
+
parse(text) {
|
|
395
|
+
return parsePlaceholders(text);
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Get the current context.
|
|
400
|
+
* @returns {import('./types.mjs').RenderContext}
|
|
401
|
+
*/
|
|
402
|
+
getContext() {
|
|
403
|
+
return { ...currentContext };
|
|
404
|
+
},
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Update the context with new values.
|
|
408
|
+
* @param {Partial<import('./types.mjs').RenderContext>} updates
|
|
409
|
+
*/
|
|
410
|
+
updateContext(updates) {
|
|
411
|
+
currentContext = { ...currentContext, ...updates };
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
417
|
+
// Utility Functions
|
|
418
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Escape HTML special characters.
|
|
422
|
+
*
|
|
423
|
+
* @param {string} text - Text to escape
|
|
424
|
+
* @returns {string} Escaped text
|
|
425
|
+
*/
|
|
426
|
+
export function escapeHtml(text) {
|
|
427
|
+
if (typeof text !== "string") {
|
|
428
|
+
return "";
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return text
|
|
432
|
+
.replace(/&/g, "&")
|
|
433
|
+
.replace(/</g, "<")
|
|
434
|
+
.replace(/>/g, ">")
|
|
435
|
+
.replace(/"/g, """)
|
|
436
|
+
.replace(/'/g, "'");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* List all placeholders found in a text.
|
|
441
|
+
* Useful for validation and debugging.
|
|
442
|
+
*
|
|
443
|
+
* @param {string} text - Text to analyze
|
|
444
|
+
* @returns {{builtin: string[], custom: string[], playwright: string[]}}
|
|
445
|
+
*/
|
|
446
|
+
export function listPlaceholders(text) {
|
|
447
|
+
const parsed = parsePlaceholders(text);
|
|
448
|
+
const builtin = [];
|
|
449
|
+
const custom = [];
|
|
450
|
+
const playwright = [];
|
|
451
|
+
|
|
452
|
+
for (const p of parsed) {
|
|
453
|
+
if (isPlaywrightPlaceholder(p.name)) {
|
|
454
|
+
playwright.push(p.name);
|
|
455
|
+
} else if (isBuiltinPlaceholder(p.name)) {
|
|
456
|
+
builtin.push(p.name);
|
|
457
|
+
} else {
|
|
458
|
+
custom.push(p.name);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return {
|
|
463
|
+
builtin: [...new Set(builtin)],
|
|
464
|
+
custom: [...new Set(custom)],
|
|
465
|
+
playwright: [...new Set(playwright)],
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Validate that all custom placeholders in text have values in context.
|
|
471
|
+
*
|
|
472
|
+
* @param {string} text - Text to validate
|
|
473
|
+
* @param {import('./types.mjs').RenderContext} context - Render context
|
|
474
|
+
* @returns {{valid: boolean, missing: string[]}}
|
|
475
|
+
*/
|
|
476
|
+
export function validatePlaceholders(text, context) {
|
|
477
|
+
const { custom } = listPlaceholders(text);
|
|
478
|
+
const missing = [];
|
|
479
|
+
|
|
480
|
+
for (const name of custom) {
|
|
481
|
+
if (!(name in (context.customVariables || {}))) {
|
|
482
|
+
missing.push(name);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return {
|
|
487
|
+
valid: missing.length === 0,
|
|
488
|
+
missing,
|
|
489
|
+
};
|
|
490
|
+
}
|