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/cli.mjs
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* markdown-pdf-export — CLI front-end for the Markdown → PDF core.
|
|
4
|
+
*
|
|
5
|
+
* markdown-pdf-export <file.md> [options] export a file
|
|
6
|
+
* markdown-pdf-export studio design pages in the browser (live preview)
|
|
7
|
+
* markdown-pdf-export doctor [file.md] check browser + settings
|
|
8
|
+
* markdown-pdf-export init [--template t] create the settings file
|
|
9
|
+
* markdown-pdf-export setup [editor] print editor task + MCP snippets
|
|
10
|
+
* markdown-pdf-export install-browser download Playwright's Chromium (~200 MB)
|
|
11
|
+
* markdown-pdf-export mcp run as an MCP server on stdio
|
|
12
|
+
*
|
|
13
|
+
* Export options are generated from the same JSON schema the MCP tool uses
|
|
14
|
+
* (tool-schemas.mjs), so the CLI and MCP surfaces cannot drift apart.
|
|
15
|
+
*
|
|
16
|
+
* Exit codes: 0 success · 1 runtime error · 2 usage error.
|
|
17
|
+
* On success the output PDF path is printed on stdout (everything else → stderr).
|
|
18
|
+
*/
|
|
19
|
+
import { spawn } from "node:child_process";
|
|
20
|
+
import fs from "node:fs";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import process from "node:process";
|
|
23
|
+
import readline from "node:readline/promises";
|
|
24
|
+
import { fileURLToPath } from "node:url";
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
SERVER_VERSION,
|
|
28
|
+
doctorMarkdownPdf,
|
|
29
|
+
exportMarkdownPdf,
|
|
30
|
+
installBrowser,
|
|
31
|
+
reloadSettings,
|
|
32
|
+
setSettings,
|
|
33
|
+
} from "./export.mjs";
|
|
34
|
+
import { EXPORT_INPUT_SCHEMA } from "./tool-schemas.mjs";
|
|
35
|
+
import {
|
|
36
|
+
PROJECT_SETTINGS_FILENAME,
|
|
37
|
+
prepareSettings,
|
|
38
|
+
userSettingsPath,
|
|
39
|
+
} from "./lib/settings-loader.mjs";
|
|
40
|
+
import { formatDoctor } from "./lib/doctor-report.mjs";
|
|
41
|
+
import { LOOKS, FONTS, applyPresets } from "./lib/looks.mjs";
|
|
42
|
+
import { EDITOR_IDS, applySetupItem, buildEditorSetup, launchSpec } from "./lib/editor-setup.mjs";
|
|
43
|
+
|
|
44
|
+
const BIN = "markdown-pdf-export";
|
|
45
|
+
const CLI_PATH = fileURLToPath(import.meta.url);
|
|
46
|
+
const TEMPLATES_DIR = path.join(path.dirname(CLI_PATH), "templates");
|
|
47
|
+
|
|
48
|
+
class UsageError extends Error {}
|
|
49
|
+
|
|
50
|
+
const kebab = (name) => name.replaceAll("_", "-");
|
|
51
|
+
const snake = (name) => name.replaceAll("-", "_");
|
|
52
|
+
|
|
53
|
+
// Options whose schema type is "object" accept JSON; margin also accepts "10mm".
|
|
54
|
+
const SCHEMA_PROPS = EXPORT_INPUT_SCHEMA.properties;
|
|
55
|
+
const FLAG_ALIASES = { o: "output_path", output: "output_path" };
|
|
56
|
+
|
|
57
|
+
function usage() {
|
|
58
|
+
const lines = Object.entries(SCHEMA_PROPS)
|
|
59
|
+
.filter(([name]) => name !== "input_path")
|
|
60
|
+
.map(([name, def]) => {
|
|
61
|
+
const flag = `--${kebab(name)}`;
|
|
62
|
+
const kind =
|
|
63
|
+
def.type === "boolean"
|
|
64
|
+
? "[=true|false]"
|
|
65
|
+
: def.type === "object"
|
|
66
|
+
? "<json>"
|
|
67
|
+
: def.type === "number"
|
|
68
|
+
? "<n>"
|
|
69
|
+
: "<value>";
|
|
70
|
+
const first = (def.description ?? "").split(/(?<=\.)\s/)[0];
|
|
71
|
+
return ` ${`${flag} ${kind}`.padEnd(37)} ${first}`;
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
return `${BIN} ${SERVER_VERSION}
|
|
75
|
+
|
|
76
|
+
Usage:
|
|
77
|
+
${BIN} <file.md> [options]
|
|
78
|
+
${BIN} (no arguments: guided menu)
|
|
79
|
+
${BIN} studio [--project] [--file <doc.md>] design pages in the browser
|
|
80
|
+
${BIN} doctor [file.md] [--json]
|
|
81
|
+
${BIN} init [--look <n>] [--font <n>] [--template <n>] [--project] [--force] [--list]
|
|
82
|
+
${BIN} setup [${EDITOR_IDS.join("|")}|all] [--write]
|
|
83
|
+
${BIN} install-browser
|
|
84
|
+
${BIN} mcp
|
|
85
|
+
|
|
86
|
+
Options (for export):
|
|
87
|
+
-o, --output <file.pdf> Output PDF path (alias of --output-path).
|
|
88
|
+
${lines.join("\n")}
|
|
89
|
+
--settings <json|file.json> Default settings (same shape as the MCP "settings" block).
|
|
90
|
+
--margin <10mm> --margin also accepts one value for all four sides.
|
|
91
|
+
--watch Re-export when the file or a settings file changes.
|
|
92
|
+
|
|
93
|
+
Booleans: --flag, --flag=false or --no-flag.
|
|
94
|
+
Objects take JSON, e.g. --margin '{"top":"10mm"}'.
|
|
95
|
+
|
|
96
|
+
Settings (lowest to highest priority):
|
|
97
|
+
built-in defaults
|
|
98
|
+
user file ${userSettingsPath()}
|
|
99
|
+
(replaced by MARKDOWN_PDF_SETTINGS or --settings when set)
|
|
100
|
+
project file nearest ${PROJECT_SETTINGS_FILENAME}, searched upward from the Markdown file
|
|
101
|
+
options above, then the front matter "pdf:" block
|
|
102
|
+
|
|
103
|
+
Environment:
|
|
104
|
+
MARKDOWN_PDF_SETTINGS Settings as JSON or a file path (replaces the user file).
|
|
105
|
+
MARKDOWN_PDF_BROWSER chrome | msedge | chromium | /path/to/browser
|
|
106
|
+
MARKDOWN_PDF_DEBUG 1 (or a file path) to enable the debug log
|
|
107
|
+
`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function coerce(name, def, raw) {
|
|
111
|
+
switch (def.type) {
|
|
112
|
+
case "boolean": {
|
|
113
|
+
if (raw === undefined || raw === "true") return true;
|
|
114
|
+
if (raw === "false") return false;
|
|
115
|
+
throw new UsageError(`--${kebab(name)} expects true or false, got "${raw}"`);
|
|
116
|
+
}
|
|
117
|
+
case "number": {
|
|
118
|
+
const n = Number(raw);
|
|
119
|
+
if (raw === undefined || raw === "" || Number.isNaN(n)) {
|
|
120
|
+
throw new UsageError(`--${kebab(name)} expects a number, got "${raw}"`);
|
|
121
|
+
}
|
|
122
|
+
return n;
|
|
123
|
+
}
|
|
124
|
+
case "object": {
|
|
125
|
+
if (raw === undefined) throw new UsageError(`--${kebab(name)} needs a value`);
|
|
126
|
+
if (name === "margin" && !/^\s*\{/.test(raw)) {
|
|
127
|
+
return { top: raw, right: raw, bottom: raw, left: raw };
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(raw);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
throw new UsageError(`--${kebab(name)} expects JSON: ${error.message}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
default: {
|
|
136
|
+
if (raw === undefined) throw new UsageError(`--${kebab(name)} needs a value`);
|
|
137
|
+
if (def.enum && !def.enum.includes(raw)) {
|
|
138
|
+
throw new UsageError(
|
|
139
|
+
`--${kebab(name)} must be one of ${def.enum.join(", ")} (got "${raw}")`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
return raw;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function parseArgs(argv) {
|
|
148
|
+
const positional = [];
|
|
149
|
+
const options = {};
|
|
150
|
+
let settings;
|
|
151
|
+
let watch = false;
|
|
152
|
+
|
|
153
|
+
for (let i = 0; i < argv.length; i++) {
|
|
154
|
+
const arg = argv[i];
|
|
155
|
+
|
|
156
|
+
if (arg === "--") {
|
|
157
|
+
positional.push(...argv.slice(i + 1));
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
if (!arg.startsWith("-") || arg === "-") {
|
|
161
|
+
positional.push(arg);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const isLong = arg.startsWith("--");
|
|
166
|
+
const body = arg.slice(isLong ? 2 : 1);
|
|
167
|
+
const eq = body.indexOf("=");
|
|
168
|
+
let key = eq === -1 ? body : body.slice(0, eq);
|
|
169
|
+
let value = eq === -1 ? undefined : body.slice(eq + 1);
|
|
170
|
+
|
|
171
|
+
if (key === "help" || key === "h") return { help: true, positional, options };
|
|
172
|
+
if (key === "version" || key === "v") return { version: true, positional, options };
|
|
173
|
+
if (key === "watch" && isLong) {
|
|
174
|
+
watch = true;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
let negate = false;
|
|
179
|
+
if (isLong && key.startsWith("no-") && SCHEMA_PROPS[snake(key.slice(3))]) {
|
|
180
|
+
negate = true;
|
|
181
|
+
key = key.slice(3);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const name = FLAG_ALIASES[key] ?? snake(key);
|
|
185
|
+
|
|
186
|
+
if (name === "settings") {
|
|
187
|
+
if (value === undefined) value = argv[++i];
|
|
188
|
+
if (value === undefined) throw new UsageError("--settings needs a value");
|
|
189
|
+
settings = value;
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const def = SCHEMA_PROPS[name];
|
|
194
|
+
if (!def || name === "input_path") {
|
|
195
|
+
throw new UsageError(`Unknown option: ${arg}`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Non-boolean options take the next argument when no "=value" was given.
|
|
199
|
+
if (def.type !== "boolean" && value === undefined) value = argv[++i];
|
|
200
|
+
|
|
201
|
+
options[name] = negate ? false : coerce(name, def, value);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return { positional, options, settings, watch };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function loadSettingsArg(value) {
|
|
208
|
+
if (value === undefined) return null;
|
|
209
|
+
const inline = /^\s*\{/.test(value);
|
|
210
|
+
const file = inline ? null : path.resolve(value);
|
|
211
|
+
const text = inline ? value : fs.readFileSync(file, "utf8");
|
|
212
|
+
let data;
|
|
213
|
+
try {
|
|
214
|
+
data = JSON.parse(text);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
throw new UsageError(`--settings is not valid JSON: ${error.message}`);
|
|
217
|
+
}
|
|
218
|
+
// Same expansion as a settings file: look / font / template presets, and
|
|
219
|
+
// for a file, paths relative to it. Inline JSON keeps its paths as written.
|
|
220
|
+
const { data: prepared, warnings } = file ? prepareSettings(data, path.dirname(file)) : applyPresets(data);
|
|
221
|
+
for (const warning of warnings) console.error(`--settings: ${warning}`);
|
|
222
|
+
return { data: prepared, file };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function main(argv) {
|
|
226
|
+
const [first, ...rest] = argv;
|
|
227
|
+
|
|
228
|
+
if (first === undefined && process.stdin.isTTY && process.stderr.isTTY) {
|
|
229
|
+
return runMenu();
|
|
230
|
+
}
|
|
231
|
+
if (first === undefined || first === "-h" || first === "--help" || first === "help") {
|
|
232
|
+
process.stdout.write(usage());
|
|
233
|
+
return first === undefined ? 2 : 0;
|
|
234
|
+
}
|
|
235
|
+
if (first === "-v" || first === "--version" || first === "version") {
|
|
236
|
+
process.stdout.write(`${BIN} ${SERVER_VERSION}\n`);
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (first === "mcp") {
|
|
241
|
+
// Importing the module starts the stdio server; it keeps the process alive.
|
|
242
|
+
await import("./mcp.mjs");
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (first === "install-browser") {
|
|
247
|
+
process.stderr.write("Downloading Chromium (~200 MB)…\n");
|
|
248
|
+
await installBrowser({ onOutput: (text) => process.stderr.write(text) });
|
|
249
|
+
process.stderr.write("Chromium installed.\n");
|
|
250
|
+
return 0;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (first === "studio") return runStudio(rest);
|
|
254
|
+
if (first === "init") return runInit(rest);
|
|
255
|
+
if (first === "setup") return runSetup(rest);
|
|
256
|
+
|
|
257
|
+
const isDoctor = first === "doctor";
|
|
258
|
+
const asJson = isDoctor && rest.includes("--json");
|
|
259
|
+
const { positional, options, settings, watch, help, version } = parseArgs(
|
|
260
|
+
isDoctor ? rest.filter((a) => a !== "--json") : argv,
|
|
261
|
+
);
|
|
262
|
+
if (help) {
|
|
263
|
+
process.stdout.write(usage());
|
|
264
|
+
return 0;
|
|
265
|
+
}
|
|
266
|
+
if (version) {
|
|
267
|
+
process.stdout.write(`${BIN} ${SERVER_VERSION}\n`);
|
|
268
|
+
return 0;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const fromArg = loadSettingsArg(settings);
|
|
272
|
+
if (fromArg) setSettings(fromArg.data, fromArg.file);
|
|
273
|
+
|
|
274
|
+
if (isDoctor) {
|
|
275
|
+
const report = await doctorMarkdownPdf({ input_path: positional[0] });
|
|
276
|
+
if (asJson) {
|
|
277
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
278
|
+
return report.browser.available ? 0 : 1;
|
|
279
|
+
}
|
|
280
|
+
const { text, ok } = formatDoctor(report, { bin: BIN });
|
|
281
|
+
process.stdout.write(text);
|
|
282
|
+
return ok ? 0 : 1;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (positional.length !== 1) {
|
|
286
|
+
throw new UsageError(
|
|
287
|
+
positional.length === 0
|
|
288
|
+
? "Missing input file."
|
|
289
|
+
: `Expected one input file, got ${positional.length}: ${positional.join(" ")}`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const args = { ...options, input_path: positional[0] };
|
|
294
|
+
if (watch) {
|
|
295
|
+
return runWatch(args, () =>
|
|
296
|
+
fromArg ? setSettings(loadSettingsArg(settings).data, fromArg.file) : reloadSettings(),
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const result = await exportMarkdownPdf(args);
|
|
301
|
+
process.stdout.write(`${result.output_path}\n`);
|
|
302
|
+
return 0;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── menu (no arguments, interactive terminal) ───────────────────────────────
|
|
306
|
+
|
|
307
|
+
async function runMenu() {
|
|
308
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
309
|
+
try {
|
|
310
|
+
process.stderr.write(
|
|
311
|
+
`\n${BIN} ${SERVER_VERSION} — Markdown to PDF\n\n` +
|
|
312
|
+
" 1) Set up my editor (VS Code, Zed, Cursor, Claude…)\n" +
|
|
313
|
+
" 2) Design my pages: style, font, header and footer (opens Studio)\n" +
|
|
314
|
+
" 3) Check that everything works\n" +
|
|
315
|
+
" 4) Show all commands\n\n",
|
|
316
|
+
);
|
|
317
|
+
const pick = (await rl.question("Choose 1-4: ")).trim();
|
|
318
|
+
rl.close();
|
|
319
|
+
if (pick === "1") return runSetup([]);
|
|
320
|
+
if (pick === "2") return runStudio([]);
|
|
321
|
+
if (pick === "3") {
|
|
322
|
+
const { text, ok } = formatDoctor(await doctorMarkdownPdf({}), { bin: BIN });
|
|
323
|
+
process.stdout.write(text);
|
|
324
|
+
return ok ? 0 : 1;
|
|
325
|
+
}
|
|
326
|
+
process.stdout.write(usage());
|
|
327
|
+
return 0;
|
|
328
|
+
} finally {
|
|
329
|
+
rl.close();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ── studio ───────────────────────────────────────────────────────────────────
|
|
334
|
+
|
|
335
|
+
function openInBrowser(url) {
|
|
336
|
+
const [cmd, args] =
|
|
337
|
+
process.platform === "darwin"
|
|
338
|
+
? ["open", [url]]
|
|
339
|
+
: process.platform === "win32"
|
|
340
|
+
? ["cmd", ["/C", "start", "", url]]
|
|
341
|
+
: ["xdg-open", [url]];
|
|
342
|
+
try {
|
|
343
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
344
|
+
child.on("error", () => {});
|
|
345
|
+
child.unref();
|
|
346
|
+
} catch {
|
|
347
|
+
// the link is printed below either way
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async function runStudio(argv) {
|
|
352
|
+
const flags = parseSubArgs(argv, {
|
|
353
|
+
project: "boolean",
|
|
354
|
+
file: "string",
|
|
355
|
+
port: "string",
|
|
356
|
+
"no-open": "boolean",
|
|
357
|
+
});
|
|
358
|
+
if (flags.help) {
|
|
359
|
+
process.stdout.write(
|
|
360
|
+
`Usage: ${BIN} studio [--project] [--file <doc.md>] [--port <n>] [--no-open]\n\n` +
|
|
361
|
+
"Opens a page in your browser to choose the page style, font, header and\n" +
|
|
362
|
+
"footer, with a live preview of the real PDF. Saves to\n" +
|
|
363
|
+
` ${userSettingsPath()}\n` +
|
|
364
|
+
`or, with --project, to ./${PROJECT_SETTINGS_FILENAME} for this folder only.\n` +
|
|
365
|
+
"--file previews one of your own documents instead of the sample.\n",
|
|
366
|
+
);
|
|
367
|
+
return 0;
|
|
368
|
+
}
|
|
369
|
+
const port = flags.port === undefined ? 0 : Number(flags.port);
|
|
370
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
371
|
+
throw new UsageError(`--port needs a number between 0 and 65535, got "${flags.port}"`);
|
|
372
|
+
}
|
|
373
|
+
const { startStudio } = await import("./lib/studio-server.mjs");
|
|
374
|
+
let studio = null;
|
|
375
|
+
const stop = async (message) => {
|
|
376
|
+
if (message) process.stderr.write(`${message}\n`);
|
|
377
|
+
await studio?.close();
|
|
378
|
+
process.exit(0);
|
|
379
|
+
};
|
|
380
|
+
studio = await startStudio({
|
|
381
|
+
scope: flags.project ? "project" : "user",
|
|
382
|
+
file: flags.file ?? flags._[0],
|
|
383
|
+
port,
|
|
384
|
+
onIdle: () => void stop("Studio page closed. Stopping."),
|
|
385
|
+
});
|
|
386
|
+
process.on("SIGINT", () => void stop(""));
|
|
387
|
+
process.on("SIGTERM", () => void stop(""));
|
|
388
|
+
|
|
389
|
+
process.stderr.write(
|
|
390
|
+
`\nStudio is running. It edits this settings file:\n ${studio.settingsPath}\n\n` +
|
|
391
|
+
(flags["no-open"]
|
|
392
|
+
? "Open this private link in your browser:\n"
|
|
393
|
+
: "Your browser should open now. If it does not, use this private link:\n"),
|
|
394
|
+
);
|
|
395
|
+
process.stdout.write(`${studio.url}\n`);
|
|
396
|
+
process.stderr.write("\nPress Ctrl+C here when you are done.\n");
|
|
397
|
+
if (!flags["no-open"]) openInBrowser(studio.url);
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// ── init ─────────────────────────────────────────────────────────────────────
|
|
402
|
+
|
|
403
|
+
/** Parse "--flag", "--flag value" and "--flag=value" for the small subcommands. */
|
|
404
|
+
function parseSubArgs(argv, spec) {
|
|
405
|
+
const out = { _: [] };
|
|
406
|
+
for (let i = 0; i < argv.length; i++) {
|
|
407
|
+
const arg = argv[i];
|
|
408
|
+
if (!arg.startsWith("--")) {
|
|
409
|
+
out._.push(arg);
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
const [key, inline] = arg.slice(2).split(/=(.*)/s, 2);
|
|
413
|
+
if (key === "help") {
|
|
414
|
+
out.help = true;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (!(key in spec)) throw new UsageError(`Unknown option: ${arg}`);
|
|
418
|
+
if (spec[key] === "boolean") {
|
|
419
|
+
out[key] = inline === undefined ? true : inline !== "false";
|
|
420
|
+
} else {
|
|
421
|
+
const value = inline ?? argv[++i];
|
|
422
|
+
if (value === undefined) throw new UsageError(`--${key} needs a value`);
|
|
423
|
+
out[key] = value;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return out;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function listTemplates() {
|
|
430
|
+
return fs
|
|
431
|
+
.readdirSync(TEMPLATES_DIR)
|
|
432
|
+
.filter((name) => name.endsWith(".json"))
|
|
433
|
+
.map((name) => name.slice(0, -".json".length))
|
|
434
|
+
.sort();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function readTemplate(name) {
|
|
438
|
+
const file = path.join(TEMPLATES_DIR, `${name}.json`);
|
|
439
|
+
if (!fs.existsSync(file)) {
|
|
440
|
+
throw new UsageError(
|
|
441
|
+
`Unknown template "${name}". Available: ${listTemplates().join(", ")}`,
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Ask for one item of a list by number or name. */
|
|
448
|
+
async function choose(rl, title, names, describe, fallback) {
|
|
449
|
+
process.stderr.write(`\n${title}\n`);
|
|
450
|
+
names.forEach((n, i) => process.stderr.write(` ${i + 1}) ${n.padEnd(10)} ${describe(n)}\n`));
|
|
451
|
+
const raw = (await rl.question(`Choose 1-${names.length} [${fallback}]: `)).trim();
|
|
452
|
+
if (!raw) return fallback;
|
|
453
|
+
const byNumber = names[Number(raw) - 1];
|
|
454
|
+
return byNumber ?? (names.includes(raw) ? raw : fallback);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const TEMPLATE_HINTS = {
|
|
458
|
+
minimal: "title and page number only",
|
|
459
|
+
simple: "title + date on top, page x of y at the bottom",
|
|
460
|
+
corporate: "logo, title, date, blue rule",
|
|
461
|
+
academic: "author left, title right, page number centred below",
|
|
462
|
+
"two-logo": "two logos, confidential footer",
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
/** Short interactive prompt (TTY only): look, font, header/footer, page, logo. */
|
|
466
|
+
async function promptInit(templates) {
|
|
467
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
468
|
+
try {
|
|
469
|
+
const look = await choose(rl, "Page style", Object.keys(LOOKS), (n) => LOOKS[n].description, "clean");
|
|
470
|
+
const font = await choose(rl, "Font", Object.keys(FONTS), () => "", "sans");
|
|
471
|
+
const template = await choose(
|
|
472
|
+
rl,
|
|
473
|
+
"Header and footer",
|
|
474
|
+
templates,
|
|
475
|
+
(n) => TEMPLATE_HINTS[n] ?? "",
|
|
476
|
+
"minimal",
|
|
477
|
+
);
|
|
478
|
+
const pageFormat = (await rl.question("\nPage format (A4, Letter, …) [A4]: ")).trim();
|
|
479
|
+
const logo = (await rl.question("Logo image for the header (path, optional): ")).trim();
|
|
480
|
+
return { template, look, font, pageFormat, logo };
|
|
481
|
+
} finally {
|
|
482
|
+
rl.close();
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async function runInit(argv) {
|
|
487
|
+
const flags = parseSubArgs(argv, {
|
|
488
|
+
template: "string",
|
|
489
|
+
look: "string",
|
|
490
|
+
font: "string",
|
|
491
|
+
project: "boolean",
|
|
492
|
+
force: "boolean",
|
|
493
|
+
list: "boolean",
|
|
494
|
+
});
|
|
495
|
+
if (flags.help) {
|
|
496
|
+
process.stdout.write(
|
|
497
|
+
`Usage: ${BIN} init [--look <n>] [--font <n>] [--template <n>] [--project] [--force] [--list]\n\n` +
|
|
498
|
+
`Creates ${userSettingsPath()}\n` +
|
|
499
|
+
`(or ./${PROJECT_SETTINGS_FILENAME} with --project) from a template.\n`,
|
|
500
|
+
);
|
|
501
|
+
return 0;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const templates = listTemplates();
|
|
505
|
+
if (flags.list) {
|
|
506
|
+
process.stdout.write(`${templates.join("\n")}\n`);
|
|
507
|
+
return 0;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const target = flags.project
|
|
511
|
+
? path.resolve(PROJECT_SETTINGS_FILENAME)
|
|
512
|
+
: userSettingsPath();
|
|
513
|
+
if (fs.existsSync(target) && !flags.force) {
|
|
514
|
+
process.stderr.write(
|
|
515
|
+
`${BIN}: ${target} already exists — not overwriting (use --force).\n`,
|
|
516
|
+
);
|
|
517
|
+
return 1;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (flags.look && !LOOKS[flags.look]) {
|
|
521
|
+
throw new UsageError(`Unknown look "${flags.look}". Available: ${Object.keys(LOOKS).join(", ")}`);
|
|
522
|
+
}
|
|
523
|
+
if (flags.font && !FONTS[flags.font]) {
|
|
524
|
+
throw new UsageError(`Unknown font "${flags.font}". Available: ${Object.keys(FONTS).join(", ")}`);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const interactive =
|
|
528
|
+
!flags.template && !flags.look && !flags.font && process.stdin.isTTY && process.stderr.isTTY;
|
|
529
|
+
const answers = interactive
|
|
530
|
+
? await promptInit(templates)
|
|
531
|
+
: {
|
|
532
|
+
template: flags.template ?? "minimal",
|
|
533
|
+
look: flags.look,
|
|
534
|
+
font: flags.font,
|
|
535
|
+
pageFormat: "",
|
|
536
|
+
logo: "",
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
// Short form when a look/font is chosen: the file stays 3 lines and readable.
|
|
540
|
+
const short = Boolean(answers.look || answers.font);
|
|
541
|
+
const data = short
|
|
542
|
+
? {
|
|
543
|
+
$schema: readTemplate(answers.template).$schema,
|
|
544
|
+
...(answers.look ? { look: answers.look } : {}),
|
|
545
|
+
...(answers.font ? { font: answers.font } : {}),
|
|
546
|
+
template: answers.template,
|
|
547
|
+
}
|
|
548
|
+
: readTemplate(answers.template);
|
|
549
|
+
if (answers.pageFormat) data.page_format = answers.pageFormat;
|
|
550
|
+
if (answers.logo) {
|
|
551
|
+
// A logo needs the header spelled out, so expand the template in place.
|
|
552
|
+
if (short) {
|
|
553
|
+
const tpl = readTemplate(answers.template);
|
|
554
|
+
delete tpl.$schema;
|
|
555
|
+
delete data.template;
|
|
556
|
+
Object.assign(data, tpl);
|
|
557
|
+
}
|
|
558
|
+
data.header = { height: "18mm", padding: "0 15mm", ...data.header };
|
|
559
|
+
data.header.left_image = path.resolve(answers.logo);
|
|
560
|
+
data.header.left_image_height ??= "12mm";
|
|
561
|
+
data.margin = { top: "25mm", ...data.margin };
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
565
|
+
fs.writeFileSync(target, `${JSON.stringify(data, null, 2)}\n`);
|
|
566
|
+
process.stderr.write(`Wrote ${answers.template} settings to:\n`);
|
|
567
|
+
process.stdout.write(`${target}\n`);
|
|
568
|
+
|
|
569
|
+
if (data.assets_directory && !answers.logo) {
|
|
570
|
+
const assets = path.resolve(path.dirname(target), data.assets_directory);
|
|
571
|
+
process.stderr.write(
|
|
572
|
+
`Put the logo files referenced as "@/…" in ${assets}\n`,
|
|
573
|
+
);
|
|
574
|
+
}
|
|
575
|
+
return 0;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// ── setup ────────────────────────────────────────────────────────────────────
|
|
579
|
+
|
|
580
|
+
async function runSetup(argv) {
|
|
581
|
+
const flags = parseSubArgs(argv, { write: "boolean" });
|
|
582
|
+
if (flags.help) {
|
|
583
|
+
process.stdout.write(
|
|
584
|
+
`Usage: ${BIN} setup [${EDITOR_IDS.join("|")}|all] [--write]\n\n` +
|
|
585
|
+
"Prints the task and MCP snippets for your editors (detected ones by default).\n" +
|
|
586
|
+
"--write creates config files that do not exist yet and runs editor CLIs;\n" +
|
|
587
|
+
"existing files are never modified.\n",
|
|
588
|
+
);
|
|
589
|
+
return 0;
|
|
590
|
+
}
|
|
591
|
+
const [which] = flags._;
|
|
592
|
+
const launch = launchSpec(CLI_PATH);
|
|
593
|
+
|
|
594
|
+
let setups;
|
|
595
|
+
if (which && which !== "all") {
|
|
596
|
+
setups = [buildEditorSetup(which, launch)];
|
|
597
|
+
} else {
|
|
598
|
+
const every = EDITOR_IDS.map((id) => buildEditorSetup(id, launch));
|
|
599
|
+
setups = which === "all" ? every : every.filter((s) => s.detected);
|
|
600
|
+
if (setups.length === 0) {
|
|
601
|
+
process.stderr.write("No editor config directory detected — showing all.\n");
|
|
602
|
+
setups = every;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const out = process.stdout;
|
|
607
|
+
for (const setup of setups) {
|
|
608
|
+
out.write(`\n━━ ${setup.name}${setup.detected ? "" : " (not detected)"} ━━\n`);
|
|
609
|
+
for (const item of setup.items) {
|
|
610
|
+
out.write(`\n▸ ${item.label}\n`);
|
|
611
|
+
if (item.file) out.write(` file: ${item.file}\n`);
|
|
612
|
+
out.write(`${item.snippet}\n`);
|
|
613
|
+
if (!flags.write) continue;
|
|
614
|
+
|
|
615
|
+
const { done, message } = applySetupItem(item);
|
|
616
|
+
out.write(` ${done ? "✓" : item.write === "print" ? "→" : "✗"} ${message}\n`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
out.write(
|
|
621
|
+
`\nSettings file: ${userSettingsPath()}` +
|
|
622
|
+
`${fs.existsSync(userSettingsPath()) ? "" : ` (missing — create it with: ${BIN} init)`}\n`,
|
|
623
|
+
);
|
|
624
|
+
const report = await doctorMarkdownPdf({});
|
|
625
|
+
out.write(
|
|
626
|
+
report.browser.available
|
|
627
|
+
? `Browser: ${report.browser.version} ✓\n`
|
|
628
|
+
: `Browser: not found — ${report.browser.hint}\n`,
|
|
629
|
+
);
|
|
630
|
+
return report.browser.available ? 0 : 1;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// ── watch ────────────────────────────────────────────────────────────────────
|
|
634
|
+
|
|
635
|
+
async function runWatch(args, reload) {
|
|
636
|
+
const watchers = new Map();
|
|
637
|
+
let timer = null;
|
|
638
|
+
let running = false;
|
|
639
|
+
let again = false;
|
|
640
|
+
|
|
641
|
+
const watchFile = (file) => {
|
|
642
|
+
if (watchers.has(file)) return;
|
|
643
|
+
// Watch the directory: editors often replace the file on save.
|
|
644
|
+
const watcher = fs.watch(path.dirname(file), (_event, name) => {
|
|
645
|
+
if (name && path.basename(file) !== String(name)) return;
|
|
646
|
+
clearTimeout(timer);
|
|
647
|
+
timer = setTimeout(exportOnce, 200);
|
|
648
|
+
});
|
|
649
|
+
watchers.set(file, watcher);
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
const exportOnce = async () => {
|
|
653
|
+
if (running) {
|
|
654
|
+
again = true;
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
running = true;
|
|
658
|
+
try {
|
|
659
|
+
reload();
|
|
660
|
+
const result = await exportMarkdownPdf(args);
|
|
661
|
+
process.stderr.write(`[${new Date().toLocaleTimeString()}] ✓ ${result.output_path}\n`);
|
|
662
|
+
for (const file of result.settings_files ?? []) watchFile(file);
|
|
663
|
+
} catch (error) {
|
|
664
|
+
process.stderr.write(
|
|
665
|
+
`[${new Date().toLocaleTimeString()}] ✗ ${error instanceof Error ? error.message : error}\n`,
|
|
666
|
+
);
|
|
667
|
+
} finally {
|
|
668
|
+
running = false;
|
|
669
|
+
if (again) {
|
|
670
|
+
again = false;
|
|
671
|
+
void exportOnce();
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
|
|
676
|
+
watchFile(path.resolve(args.input_path));
|
|
677
|
+
await exportOnce();
|
|
678
|
+
process.stderr.write("Watching for changes — Ctrl+C to stop.\n");
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
main(process.argv.slice(2)).then(
|
|
683
|
+
(code) => {
|
|
684
|
+
if (code !== null) process.exitCode = code;
|
|
685
|
+
},
|
|
686
|
+
(error) => {
|
|
687
|
+
if (error instanceof UsageError) {
|
|
688
|
+
process.stderr.write(`${BIN}: ${error.message}\nTry '${BIN} --help'.\n`);
|
|
689
|
+
process.exitCode = 2;
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
process.stderr.write(`${BIN}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
693
|
+
process.exitCode = 1;
|
|
694
|
+
},
|
|
695
|
+
);
|