@projektemacher/vivliostyle-batch-cli 0.0.1

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,878 @@
1
+ import { Command } from 'commander';
2
+ import { build, preview } from '@vivliostyle/cli';
3
+ import { resolve, dirname, posix, join } from 'node:path';
4
+ import { existsSync, readFileSync, mkdtempSync, writeFileSync, rmSync, statSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { tmpdir } from 'node:os';
7
+ import { lookup } from 'mime-types';
8
+ import express from 'express';
9
+ import serveStatic from 'serve-static';
10
+ import { JSDOM } from 'jsdom';
11
+
12
+ const validFormats = ["pdf", "epub", "webpub"];
13
+ const validLogLevels = ["silent", "info", "verbose", "debug"];
14
+ const validModes = ["build", "preview"];
15
+ // ---------------------------------------------------------------------------
16
+ // HTML input detection
17
+ // ---------------------------------------------------------------------------
18
+ /**
19
+ * Returns true when the input file should be treated as HTML.
20
+ * Vivliostyle also accepts publication manifests (JSON/TOML/JS config files);
21
+ * we detect HTML by extension to avoid trying to parse those as markup.
22
+ */
23
+ function isHtmlInput(inputAbs) {
24
+ return /\.html?$/i.test(inputAbs);
25
+ }
26
+ // ---------------------------------------------------------------------------
27
+ // Debug logger
28
+ // ---------------------------------------------------------------------------
29
+ function makeDbg(enabled) {
30
+ return (_label, _value) => {
31
+ if (!enabled)
32
+ return;
33
+ if (_value === undefined) {
34
+ console.error(`[debug] ${_label}`);
35
+ }
36
+ else {
37
+ console.error(`[debug] ${_label}`, JSON.stringify(_value, null, 2));
38
+ }
39
+ };
40
+ }
41
+ // ---------------------------------------------------------------------------
42
+ // Arg splitting
43
+ // ---------------------------------------------------------------------------
44
+ function splitArgsAtDoubleDash(argv) {
45
+ const dd = argv.indexOf("--");
46
+ if (dd === -1)
47
+ return { cliArgv: argv, extraArgs: [] };
48
+ return { cliArgv: argv.slice(0, dd), extraArgs: argv.slice(dd + 1) };
49
+ }
50
+ function makeMimeHeaders(res, filePath) {
51
+ const mime = lookup(filePath);
52
+ if (mime)
53
+ res.setHeader("Content-Type", mime);
54
+ }
55
+ function isFile(localPath) {
56
+ try {
57
+ return statSync(localPath).isFile();
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ function applyStaticMounts(app, staticMap, assetBases, dbg) {
64
+ for (const [virtual, localBase] of Object.entries(staticMap)) {
65
+ const absLocal = resolve(localBase);
66
+ if (isFile(absLocal)) {
67
+ app.get(virtual, (_req, res) => {
68
+ dbg("[static-server] serving file", { virtual, absLocal });
69
+ const mime = lookup(absLocal);
70
+ if (mime)
71
+ res.type(mime);
72
+ res.sendFile(absLocal);
73
+ });
74
+ console.log(`[static-server] File route: GET ${virtual} → ${absLocal}`);
75
+ }
76
+ else {
77
+ const mountPath = virtual.endsWith("/") ? virtual : `${virtual}/`;
78
+ app.use(mountPath, serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
79
+ console.log(`[static-server] Dir mount: ${mountPath} → ${absLocal}`);
80
+ }
81
+ dbg("[static-server] mount", { virtual, absLocal });
82
+ }
83
+ for (const ab of assetBases) {
84
+ const absLocal = resolve(ab.localBase);
85
+ app.use("/", serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
86
+ dbg("[static-server] assetBase fallback mount", absLocal);
87
+ console.log(`[static-server] Fallback mount: / → ${absLocal}`);
88
+ }
89
+ }
90
+ function startStaticServer(staticMap, assetBases, htmlFilePath, dbg, port = 0) {
91
+ const app = express();
92
+ app.disable("x-powered-by");
93
+ if (htmlFilePath !== null) {
94
+ const absHtmlPath = resolve(htmlFilePath);
95
+ app.get("/index.html", (_req, res) => {
96
+ dbg("[static-server] serving HTML entry", absHtmlPath);
97
+ res.type("text/html").sendFile(absHtmlPath);
98
+ });
99
+ console.log(`[static-server] HTML entry: /index.html → ${absHtmlPath}`);
100
+ }
101
+ applyStaticMounts(app, staticMap, assetBases, dbg);
102
+ app.use((req, res) => {
103
+ dbg("[static-server] 404", req.url);
104
+ res.status(404).type("text").send(`404 Not Found: ${req.url}`);
105
+ });
106
+ return new Promise((resolvePromise, reject) => {
107
+ const httpServer = app.listen(port, "127.0.0.1", () => {
108
+ const addr = httpServer.address();
109
+ const baseUrl = `http://127.0.0.1:${addr.port}`;
110
+ console.log(`[static-server] Listening on ${baseUrl}`);
111
+ dbg("[static-server] staticMap", staticMap);
112
+ dbg("[static-server] assetBase roots", assetBases.map((ab) => ab.localBase));
113
+ let closed = false;
114
+ const close = () => {
115
+ if (closed)
116
+ return;
117
+ closed = true;
118
+ httpServer.close((err) => {
119
+ if (err)
120
+ console.warn(`[static-server] close error: ${err.message}`);
121
+ else
122
+ dbg("[static-server] stopped");
123
+ });
124
+ };
125
+ resolvePromise({ baseUrl, close });
126
+ });
127
+ httpServer.once("error", reject);
128
+ });
129
+ }
130
+ // ---------------------------------------------------------------------------
131
+ // DOM-level rewriters
132
+ // ---------------------------------------------------------------------------
133
+ const URL_ATTR_SELECTORS = [
134
+ ["link[href]", "href"],
135
+ ["script[src]", "src"],
136
+ ["img[src]", "src"],
137
+ ["source[src]", "src"],
138
+ ["video[src]", "src"],
139
+ ["audio[src]", "src"],
140
+ ["video[poster]", "poster"],
141
+ ["input[src]", "src"]
142
+ ];
143
+ function rewriteAbsoluteUrlsInDom(document, assetBases) {
144
+ if (assetBases.length === 0)
145
+ return false;
146
+ let changed = false;
147
+ for (const [selector, attr] of URL_ATTR_SELECTORS) {
148
+ for (const el of document.querySelectorAll(selector)) {
149
+ const val = el.getAttribute(attr) ?? "";
150
+ const mapped = mapAbsoluteUrlToLocal(val, assetBases);
151
+ if (mapped) {
152
+ el.setAttribute(attr, mapped.virtualPath);
153
+ changed = true;
154
+ }
155
+ }
156
+ }
157
+ return changed;
158
+ }
159
+ function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl) {
160
+ let changed = false;
161
+ const shouldRewrite = (path) => {
162
+ if (!path.startsWith("/"))
163
+ return false;
164
+ return staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
165
+ };
166
+ for (const [selector, attr] of URL_ATTR_SELECTORS) {
167
+ for (const el of document.querySelectorAll(selector)) {
168
+ const val = el.getAttribute(attr) ?? "";
169
+ if (shouldRewrite(val)) {
170
+ el.setAttribute(attr, `${serverBaseUrl}${val}`);
171
+ changed = true;
172
+ }
173
+ }
174
+ }
175
+ return changed;
176
+ }
177
+ // ---------------------------------------------------------------------------
178
+ // String-level wrappers (kept for external callers / tests)
179
+ // ---------------------------------------------------------------------------
180
+ function rewriteAbsoluteUrls(htmlContent, assetBases) {
181
+ if (assetBases.length === 0)
182
+ return htmlContent;
183
+ const dom = new JSDOM(htmlContent);
184
+ const changed = rewriteAbsoluteUrlsInDom(dom.window.document, assetBases);
185
+ return changed ? dom.serialize() : htmlContent;
186
+ }
187
+ function rewriteVirtualPathsToServer(htmlContent, staticMap, serverBaseUrl) {
188
+ const keys = Object.keys(staticMap);
189
+ if (keys.length === 0)
190
+ return htmlContent;
191
+ const dom = new JSDOM(htmlContent);
192
+ const changed = rewriteVirtualPathsToServerInDom(dom.window.document, keys, serverBaseUrl);
193
+ return changed ? dom.serialize() : htmlContent;
194
+ }
195
+ // ---------------------------------------------------------------------------
196
+ // HTML asset extraction
197
+ // ---------------------------------------------------------------------------
198
+ function extractUrlsFromHtml(htmlPath, includeScripts = true, doc) {
199
+ let document;
200
+ if (doc) {
201
+ document = doc;
202
+ }
203
+ else {
204
+ let content;
205
+ try {
206
+ content = readFileSync(htmlPath, "utf-8");
207
+ }
208
+ catch (err) {
209
+ throw new Error(`Error reading HTML file: ${htmlPath}\n${String(err)}`);
210
+ }
211
+ document = new JSDOM(content).window.document;
212
+ }
213
+ const urls = new Set();
214
+ for (const el of document.querySelectorAll("link[href]")) {
215
+ const href = el.getAttribute("href")?.trim();
216
+ if (href)
217
+ urls.add(href);
218
+ }
219
+ if (includeScripts) {
220
+ for (const el of document.querySelectorAll("script[src]")) {
221
+ const src = el.getAttribute("src")?.trim();
222
+ if (src)
223
+ urls.add(src);
224
+ }
225
+ }
226
+ return [...urls];
227
+ }
228
+ // ---------------------------------------------------------------------------
229
+ // Preview HTML builder
230
+ // ---------------------------------------------------------------------------
231
+ /**
232
+ * Rewrites absolute external URLs to root-relative virtual paths and writes
233
+ * the result as a sibling of the original input file so that
234
+ * cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
235
+ *
236
+ * The output filename uses a non-dotfile prefix so Vite's static server
237
+ * (which ignores dotfiles by default) can serve it correctly.
238
+ *
239
+ * Also derives extra static mounts from each assetBase so that secondary
240
+ * assets referenced from CSS (fonts, images) are served by Vivliostyle's
241
+ * own Vite server without needing Express.
242
+ *
243
+ * Returns:
244
+ * - htmlPath – sibling file path, or inputAbs if no rewriting was needed
245
+ * - extraStatic – virtual→local entries for assetBase roots to merge into
246
+ * the static map passed to Vivliostyle
247
+ * - cleanup – deletes the sibling file (no-op if inputAbs was returned)
248
+ */
249
+ function buildPreviewHtml(inputAbs, assetBases, dbg) {
250
+ let content;
251
+ try {
252
+ content = readFileSync(inputAbs, "utf-8");
253
+ }
254
+ catch (err) {
255
+ throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
256
+ }
257
+ // Derive extra static mounts for each assetBase root so secondary assets
258
+ // referenced from CSS are also reachable through Vivliostyle's Vite server.
259
+ const extraStatic = {};
260
+ for (const ab of assetBases) {
261
+ let virtualPrefix;
262
+ try {
263
+ virtualPrefix = new URL(ab.urlBase).pathname;
264
+ }
265
+ catch {
266
+ virtualPrefix = "/";
267
+ }
268
+ if (!virtualPrefix.endsWith("/"))
269
+ virtualPrefix = `${virtualPrefix}/`;
270
+ const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
271
+ if (Object.hasOwn(extraStatic, mapKey)) {
272
+ console.warn(`[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`);
273
+ }
274
+ extraStatic[mapKey] = resolve(ab.localBase);
275
+ dbg("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
276
+ }
277
+ const dom = new JSDOM(content);
278
+ const document = dom.window.document;
279
+ const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
280
+ if (changed)
281
+ dbg("buildPreviewHtml: rewrote absolute URLs → virtual paths");
282
+ if (!changed) {
283
+ dbg("buildPreviewHtml: no URL rewrites needed, using original file");
284
+ return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
285
+ }
286
+ const inputDir = dirname(inputAbs);
287
+ const inputBase = inputAbs.slice(inputDir.length + 1);
288
+ const outputBase = `_vivliostyle_preview_${inputBase}`;
289
+ const htmlPath = join(inputDir, outputBase);
290
+ writeFileSync(htmlPath, dom.serialize(), "utf-8");
291
+ dbg("buildPreviewHtml: wrote rewritten HTML alongside original", htmlPath);
292
+ console.log(`[preview] Wrote rewritten HTML: ${htmlPath}`);
293
+ const cleanup = () => {
294
+ try {
295
+ rmSync(htmlPath, { force: true });
296
+ dbg("buildPreviewHtml: removed rewritten HTML", htmlPath);
297
+ }
298
+ catch (err) {
299
+ console.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
300
+ }
301
+ };
302
+ return { htmlPath, extraStatic, cleanup };
303
+ }
304
+ // ---------------------------------------------------------------------------
305
+ // Build HTML builder
306
+ // ---------------------------------------------------------------------------
307
+ /**
308
+ * Prepares the HTML for BUILD mode.
309
+ * Both rewrite passes (absolute → virtual, virtual → absolute server URL)
310
+ * are applied in a single DOM parse.
311
+ * If nothing changed the original file path is returned with a no-op cleanup.
312
+ */
313
+ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl, dbg) {
314
+ let content;
315
+ try {
316
+ content = readFileSync(inputAbs, "utf-8");
317
+ }
318
+ catch (err) {
319
+ throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
320
+ }
321
+ const dom = new JSDOM(content);
322
+ const document = dom.window.document;
323
+ const staticMapKeys = Object.keys(staticMap);
324
+ const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
325
+ if (absChanged)
326
+ dbg("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
327
+ const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl);
328
+ if (srvChanged)
329
+ dbg("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
330
+ if (!absChanged && !srvChanged) {
331
+ dbg("prepareInputHtmlForBuild: no changes, using original file");
332
+ return { vivliostyleInput: inputAbs, cleanup: () => undefined };
333
+ }
334
+ const tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
335
+ const tmpHtml = join(tmpDir, "index.html");
336
+ writeFileSync(tmpHtml, dom.serialize(), "utf-8");
337
+ console.log(`[html] Prepared input HTML → ${tmpHtml}`);
338
+ dbg("prepareInputHtmlForBuild: written to temp file", tmpHtml);
339
+ const cleanup = () => {
340
+ try {
341
+ rmSync(tmpDir, { recursive: true, force: true });
342
+ dbg("prepareInputHtmlForBuild: removed temp dir", tmpDir);
343
+ }
344
+ catch (err) {
345
+ console.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
346
+ }
347
+ };
348
+ return { vivliostyleInput: tmpHtml, cleanup };
349
+ }
350
+ // ---------------------------------------------------------------------------
351
+ // Asset base / ignore helpers
352
+ // ---------------------------------------------------------------------------
353
+ function normalizeUrlBase(urlBase) {
354
+ return urlBase.endsWith("/") ? urlBase : `${urlBase}/`;
355
+ }
356
+ function normalizeIgnoreAssetPath(pathValue) {
357
+ const trimmed = pathValue.trim();
358
+ if (!trimmed)
359
+ throw new Error("Invalid --ignore-asset value: must not be empty");
360
+ return trimmed.startsWith("/") ? posix.normalize(trimmed) : posix.resolve("/", trimmed);
361
+ }
362
+ function shouldIgnoreVirtualPath(virtualPath, ignoredAssets) {
363
+ return ignoredAssets.has(posix.normalize(virtualPath));
364
+ }
365
+ function parseAssetBaseMapping(value) {
366
+ const eqIdx = value.indexOf("=");
367
+ if (eqIdx === -1) {
368
+ throw new Error(`Invalid --asset-base value: "${value}"\nExpected format: <urlBase>=<localBase>`);
369
+ }
370
+ const urlBase = value.slice(0, eqIdx).trim();
371
+ const localBase = value.slice(eqIdx + 1).trim();
372
+ if (!urlBase || !localBase) {
373
+ throw new Error(`Invalid --asset-base value: "${value}"\nBoth urlBase and localBase are required`);
374
+ }
375
+ return { urlBase: normalizeUrlBase(urlBase), localBase };
376
+ }
377
+ function mapAbsoluteUrlToLocal(url, assetBases) {
378
+ for (const mapping of assetBases) {
379
+ if (!url.startsWith(mapping.urlBase))
380
+ continue;
381
+ let cleanRelative;
382
+ try {
383
+ cleanRelative = new URL(url).pathname.slice(1);
384
+ }
385
+ catch {
386
+ const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
387
+ cleanRelative = noQuery.split("#")[0];
388
+ }
389
+ if (!cleanRelative)
390
+ return null;
391
+ const virtualPath = posix.resolve("/", cleanRelative);
392
+ const localPath = resolve(mapping.localBase, cleanRelative);
393
+ return { virtualPath, localPath };
394
+ }
395
+ return null;
396
+ }
397
+ function urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg) {
398
+ const trimmed = url.trim();
399
+ if (!trimmed)
400
+ return { kind: "skipped", url, reason: "empty URL" };
401
+ if (trimmed.startsWith("#"))
402
+ return { kind: "skipped", url, reason: "fragment-only URL" };
403
+ const absoluteMapped = mapAbsoluteUrlToLocal(trimmed, assetBases);
404
+ if (absoluteMapped) {
405
+ if (shouldIgnoreVirtualPath(absoluteMapped.virtualPath, ignoredAssets)) {
406
+ dbg("urlToStaticMapping: ignored (asset-base match)", { url, ...absoluteMapped });
407
+ return {
408
+ kind: "skipped",
409
+ url,
410
+ reason: `matches --ignore-asset "${absoluteMapped.virtualPath}"`
411
+ };
412
+ }
413
+ if (!existsSync(absoluteMapped.localPath)) {
414
+ console.warn(`[html] Warning: asset-base mapped path does not exist\n` +
415
+ ` url : ${url}\n` +
416
+ ` virtual : ${absoluteMapped.virtualPath}\n` +
417
+ ` local : ${absoluteMapped.localPath}`);
418
+ }
419
+ return {
420
+ kind: "mapped",
421
+ mapping: `${absoluteMapped.virtualPath}:${absoluteMapped.localPath}`
422
+ };
423
+ }
424
+ if (trimmed.startsWith("//")) {
425
+ return { kind: "skipped", url, reason: "protocol-relative external URL" };
426
+ }
427
+ if (/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(trimmed)) {
428
+ const protocol = trimmed.slice(0, trimmed.indexOf(":"));
429
+ return {
430
+ kind: "skipped",
431
+ url,
432
+ reason: `external URL (protocol: ${protocol}:) — add --asset-base to map it locally`
433
+ };
434
+ }
435
+ const [cleanUrl] = trimmed.split(/[?#]/);
436
+ if (!cleanUrl) {
437
+ return { kind: "skipped", url, reason: "URL is empty after stripping query/fragment" };
438
+ }
439
+ const localPath = resolve(htmlDir, cleanUrl);
440
+ const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
441
+ if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
442
+ dbg("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
443
+ return {
444
+ kind: "skipped",
445
+ url,
446
+ reason: `matches --ignore-asset "${virtualPath}"`
447
+ };
448
+ }
449
+ if (!existsSync(localPath)) {
450
+ console.warn(`[html] Warning: referenced path does not exist\n` +
451
+ ` url : ${url}\n` +
452
+ ` virtual : ${virtualPath}\n` +
453
+ ` local : ${localPath}`);
454
+ }
455
+ return { kind: "mapped", mapping: `${virtualPath}:${localPath}` };
456
+ }
457
+ function parseStaticMapping(mapping) {
458
+ if (!mapping.startsWith("/")) {
459
+ throw new Error(`Invalid --static mapping: "${mapping}"\nExpected format: /virtual/path:/local/path`);
460
+ }
461
+ const colonIdx = mapping.indexOf(":", 1);
462
+ if (colonIdx === -1) {
463
+ throw new Error(`Invalid --static mapping: "${mapping}"\nExpected format: /virtual/path:/local/path`);
464
+ }
465
+ const virtual = mapping.slice(0, colonIdx);
466
+ const local = mapping.slice(colonIdx + 1);
467
+ if (!local)
468
+ throw new Error(`Local path missing in --static mapping: "${mapping}"`);
469
+ return { virtual, local };
470
+ }
471
+ // ---------------------------------------------------------------------------
472
+ // Static map builder
473
+ // ---------------------------------------------------------------------------
474
+ function buildStaticMap(rawMappings) {
475
+ const map = {};
476
+ for (const mapping of rawMappings) {
477
+ const { virtual, local } = parseStaticMapping(mapping);
478
+ if (Object.hasOwn(map, virtual)) {
479
+ console.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
480
+ }
481
+ map[virtual] = local;
482
+ }
483
+ return map;
484
+ }
485
+ // ---------------------------------------------------------------------------
486
+ // Extra args parser
487
+ // ---------------------------------------------------------------------------
488
+ function parseExtraArgs(extraArgs) {
489
+ const extraConfig = {};
490
+ for (let i = 0; i < extraArgs.length; i++) {
491
+ const arg = extraArgs[i];
492
+ if (!arg.startsWith("--")) {
493
+ if (arg.startsWith("-")) {
494
+ console.warn(`[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
495
+ ` Use the long-form --flag equivalent instead.`);
496
+ }
497
+ continue;
498
+ }
499
+ if (arg.includes("=")) {
500
+ const eqIdx = arg.indexOf("=");
501
+ const key = arg.slice(2, eqIdx);
502
+ const val = arg.slice(eqIdx + 1);
503
+ extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
504
+ continue;
505
+ }
506
+ const key = arg.slice(2);
507
+ const next = extraArgs[i + 1];
508
+ if (next === "true") {
509
+ extraConfig[key] = true;
510
+ i++;
511
+ }
512
+ else if (next === "false") {
513
+ extraConfig[key] = false;
514
+ i++;
515
+ }
516
+ else if (next && !next.startsWith("-")) {
517
+ extraConfig[key] = next;
518
+ i++;
519
+ }
520
+ else {
521
+ extraConfig[key] = true;
522
+ }
523
+ }
524
+ return extraConfig;
525
+ }
526
+ // ---------------------------------------------------------------------------
527
+ // Shared option helpers
528
+ // ---------------------------------------------------------------------------
529
+ function pickDefinedStrings(source, keys) {
530
+ const result = {};
531
+ for (const key of keys) {
532
+ const val = source[key];
533
+ if (val !== undefined && val !== "")
534
+ result[key] = val;
535
+ }
536
+ return result;
537
+ }
538
+ // ---------------------------------------------------------------------------
539
+ // Program definition
540
+ // ---------------------------------------------------------------------------
541
+ function buildProgram() {
542
+ return new Command()
543
+ .name("vivliostyle-cli")
544
+ .description([
545
+ "Vivliostyle CLI wrapper with extended static-asset and HTML-parsing support.",
546
+ "",
547
+ "Examples:",
548
+ " # Build a PDF from an HTML file",
549
+ " vivliostyle-cli -i index.html -o out.pdf",
550
+ "",
551
+ " # Preview an HTML file in browser",
552
+ " vivliostyle-cli -i index.html --preview",
553
+ "",
554
+ " # Build with explicit static asset mapping",
555
+ " vivliostyle-cli -i index.html -o out.pdf \\",
556
+ " --static /assets:/home/user/project/assets",
557
+ "",
558
+ " # Map an absolute CDN URL to a local directory",
559
+ " vivliostyle-cli -i index.html -o out.pdf \\",
560
+ " --asset-base https://cdn.example.com/=/home/user/cdn-cache",
561
+ "",
562
+ " # Pass extra Vivliostyle options after --",
563
+ " vivliostyle-cli -i index.html -o out.pdf -- --timeout 60000"
564
+ ].join("\n"))
565
+ .requiredOption("-i, --input <input>", "Input HTML or publication manifest file")
566
+ .option("-o, --output <file>", "Output file path", "output.pdf")
567
+ .option("--title <title>", "Document title (overrides the one in the source)")
568
+ .option("--author <author>", "Document author")
569
+ .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
570
+ .option("--static <mapping>", [
571
+ "Map a virtual path to a local directory or file.",
572
+ "Format: /virtual/path:/absolute/local/path",
573
+ "Repeatable: --static /css:/dist/css --static /fonts:/dist/fonts"
574
+ ].join("\n "), (val, prev) => prev.concat(val), [])
575
+ .option("--no-scripts", [
576
+ "Do not map <script src> tags as static assets.",
577
+ "Recommended for PDF builds to avoid JS identifier conflicts",
578
+ "in the Vivliostyle viewer.",
579
+ "Only applies when the input is an HTML file."
580
+ ].join("\n "))
581
+ .option("--asset-base <urlBase=localBase>", [
582
+ "Map all asset URLs that start with <urlBase> to files under <localBase>.",
583
+ "Format: <urlBase>=<localBase>",
584
+ "Example: https://cdn.example.com/=/home/user/cdn-cache",
585
+ "The localBase is also used as fallback root for secondary assets.",
586
+ "Repeatable. Only applies when the input is an HTML file."
587
+ ].join("\n "), (val, prev) => prev.concat(val), [])
588
+ .option("--ignore-asset <path>", [
589
+ "Skip a specific virtual path when deriving static mappings.",
590
+ "Example: --ignore-asset /livereload.js",
591
+ "Repeatable. Only applies when the input is an HTML file."
592
+ ].join("\n "), (val, prev) => prev.concat(val), [])
593
+ .option("--cwd <dir>", "Working directory for Vivliostyle (default: directory of --input)")
594
+ .option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
595
+ .option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
596
+ .option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
597
+ .option("--preview", "Shorthand for --mode preview — open result in browser")
598
+ .option("-d, --debug", "Print every resolved config value to stderr before running")
599
+ .addHelpText("after", [
600
+ "",
601
+ "Notes:",
602
+ " • HTML input (.html/.htm) is detected automatically from the file extension.",
603
+ " • For HTML input, <link href> and <script src> are parsed and auto-mapped.",
604
+ " • Options after -- are forwarded verbatim to Vivliostyle.",
605
+ " • --debug sets --log-level to debug automatically.",
606
+ " • --preview and --mode preview are equivalent.",
607
+ " • In preview mode Vivliostyle serves everything via its own Vite server.",
608
+ " • In build mode an Express server is started to serve assets.",
609
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets."
610
+ ].join("\n"));
611
+ }
612
+ function printHelp() {
613
+ buildProgram().help();
614
+ }
615
+ function parseArgs(argv) {
616
+ const { cliArgv, extraArgs } = splitArgsAtDoubleDash(argv);
617
+ if (cliArgv.slice(2).length === 0)
618
+ return null;
619
+ const program = buildProgram();
620
+ program.exitOverride();
621
+ try {
622
+ program.parse(cliArgv);
623
+ }
624
+ catch (err) {
625
+ const code = err.code ?? "";
626
+ if (code === "commander.helpDisplayed" || code === "commander.version")
627
+ return null;
628
+ throw err;
629
+ }
630
+ return { options: program.opts(), extraArgs };
631
+ }
632
+ // ---------------------------------------------------------------------------
633
+ // Core execute
634
+ // ---------------------------------------------------------------------------
635
+ async function execute(options, extraArgs = []) {
636
+ const debugEnabled = !!(options.debug || options.logLevel === "debug");
637
+ const dbg = makeDbg(debugEnabled);
638
+ dbg("raw CLI options", options);
639
+ dbg("extra args (after --)", extraArgs);
640
+ if (!options.input)
641
+ throw new Error("Missing required option: --input");
642
+ const inputAbs = resolve(options.input);
643
+ dbg("resolved input", inputAbs);
644
+ if (!existsSync(inputAbs))
645
+ throw new Error(`Input file does not exist: ${inputAbs}`);
646
+ const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
647
+ if (!existsSync(cwd)) {
648
+ throw new Error(`Working directory does not exist: ${cwd}`);
649
+ }
650
+ dbg("cwd", cwd);
651
+ const outputAbs = resolve(options.output);
652
+ dbg("resolved output", outputAbs);
653
+ if (!validFormats.includes(options.format)) {
654
+ throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
655
+ }
656
+ const format = options.format;
657
+ if (!validLogLevels.includes(options.logLevel)) {
658
+ throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
659
+ }
660
+ const logLevel = options.debug ? "debug" : options.logLevel;
661
+ dbg("logLevel", logLevel);
662
+ const mode = (options.preview ? "preview" : options.mode);
663
+ if (!validModes.includes(mode)) {
664
+ throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
665
+ }
666
+ dbg("mode", mode);
667
+ const htmlMode = isHtmlInput(inputAbs);
668
+ dbg("htmlMode (auto-detected)", htmlMode);
669
+ if (!htmlMode) {
670
+ if (options.assetBase.length > 0) {
671
+ console.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
672
+ }
673
+ if (options.ignoreAsset.length > 0) {
674
+ console.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
675
+ }
676
+ }
677
+ const assetBases = options.assetBase.map(parseAssetBaseMapping);
678
+ dbg("parsed assetBases", assetBases);
679
+ const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
680
+ dbg("ignoredAssets", [...ignoredAssets]);
681
+ // ── HTML-derived mappings ────────────────────────────────────────────────
682
+ const derivedMappings = [];
683
+ if (htmlMode) {
684
+ const htmlDir = dirname(inputAbs);
685
+ console.log(`[html] Analysing input as HTML: ${inputAbs}`);
686
+ const includeScripts = mode === "preview" ? true : options.scripts;
687
+ const urls = extractUrlsFromHtml(inputAbs, includeScripts);
688
+ if (urls.length === 0) {
689
+ console.log("[html] No URLs found in input HTML");
690
+ }
691
+ else {
692
+ console.log(`[html] Found URLs (${urls.length}):`);
693
+ }
694
+ for (const url of urls) {
695
+ const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg);
696
+ if (result.kind === "skipped") {
697
+ console.log(` → Skipped (${result.reason}): ${url}`);
698
+ continue;
699
+ }
700
+ console.log(` → Mapping: ${result.mapping}`);
701
+ derivedMappings.push(result.mapping);
702
+ }
703
+ dbg("derived static mappings from HTML", derivedMappings);
704
+ }
705
+ // ── static map ────────────────────────────────────────────────────────────
706
+ const allStaticMappings = [...options.static, ...derivedMappings];
707
+ dbg("all raw static mappings", allStaticMappings);
708
+ const staticMap = buildStaticMap(allStaticMappings);
709
+ dbg("assembled staticMap", staticMap);
710
+ const hasStatic = Object.keys(staticMap).length > 0;
711
+ for (const [virtualPath, localPath] of Object.entries(staticMap)) {
712
+ if (!existsSync(localPath)) {
713
+ console.warn(`[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`);
714
+ }
715
+ }
716
+ const extraConfig = parseExtraArgs(extraArgs);
717
+ dbg("extraConfig (parsed from -- args)", extraConfig);
718
+ const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
719
+ console.log(`Starting Vivliostyle in mode: ${mode}`);
720
+ // ── BUILD mode ─────────────────────────────────────────────────────────────
721
+ if (mode === "build") {
722
+ let vivliostyleInput = inputAbs;
723
+ let htmlCleanup = () => undefined;
724
+ if (hasStatic || assetBases.length > 0) {
725
+ const server = await startStaticServer(staticMap, assetBases, null, dbg);
726
+ try {
727
+ if (htmlMode) {
728
+ ({ vivliostyleInput, cleanup: htmlCleanup } = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, dbg));
729
+ }
730
+ dbg("vivliostyleInput (final)", vivliostyleInput);
731
+ const config = {
732
+ cwd,
733
+ input: vivliostyleInput,
734
+ output: [{ path: outputAbs, format }],
735
+ ...metaFields,
736
+ logLevel,
737
+ ...(options.debug ? { debug: true } : {}),
738
+ ...extraConfig
739
+ };
740
+ dbg("final BuildConfig", config);
741
+ await build(config);
742
+ console.log(`✓ Document created: ${outputAbs}`);
743
+ }
744
+ finally {
745
+ htmlCleanup();
746
+ server.close();
747
+ }
748
+ }
749
+ else {
750
+ dbg("vivliostyleInput (final)", vivliostyleInput);
751
+ const config = {
752
+ cwd,
753
+ input: vivliostyleInput,
754
+ output: [{ path: outputAbs, format }],
755
+ ...metaFields,
756
+ logLevel,
757
+ ...(options.debug ? { debug: true } : {}),
758
+ ...extraConfig
759
+ };
760
+ dbg("final BuildConfig", config);
761
+ await build(config);
762
+ console.log(`✓ Document created: ${outputAbs}`);
763
+ }
764
+ // ── PREVIEW mode ───────────────────────────────────────────────────────────
765
+ }
766
+ else {
767
+ let previewInput = inputAbs;
768
+ let htmlCleanup = () => undefined;
769
+ const previewStaticMap = { ...staticMap };
770
+ if (htmlMode) {
771
+ const { htmlPath, extraStatic, cleanup } = buildPreviewHtml(inputAbs, assetBases, dbg);
772
+ previewInput = htmlPath;
773
+ htmlCleanup = cleanup;
774
+ for (const [virtual, local] of Object.entries(extraStatic)) {
775
+ if (!Object.hasOwn(previewStaticMap, virtual)) {
776
+ previewStaticMap[virtual] = local;
777
+ console.log(`[preview] AssetBase static mount: ${virtual} → ${local}`);
778
+ }
779
+ else {
780
+ dbg("preview: skipping assetBase mount shadowed by explicit --static", {
781
+ virtual,
782
+ local
783
+ });
784
+ }
785
+ }
786
+ if (htmlPath !== inputAbs) {
787
+ console.log(`[preview] Using rewritten HTML: ${htmlPath}`);
788
+ }
789
+ }
790
+ dbg("preview input (final)", previewInput);
791
+ dbg("previewStaticMap (final)", previewStaticMap);
792
+ const hasPreviewStatic = Object.keys(previewStaticMap).length > 0;
793
+ const previewCwd = dirname(previewInput);
794
+ dbg("previewCwd", previewCwd);
795
+ const previewEntry = previewInput.slice(previewCwd.length + 1);
796
+ dbg("previewEntry (relative, for configData only)", previewEntry);
797
+ const config = {
798
+ cwd: previewCwd,
799
+ input: previewInput,
800
+ logLevel,
801
+ enableStaticServe: true,
802
+ openViewer: true,
803
+ singleDoc: true,
804
+ ...(hasPreviewStatic
805
+ ? {
806
+ configData: [
807
+ {
808
+ entry: previewEntry,
809
+ ...metaFields,
810
+ static: previewStaticMap
811
+ }
812
+ ]
813
+ }
814
+ : {}),
815
+ ...(options.debug ? { debug: true } : {}),
816
+ ...extraConfig
817
+ };
818
+ dbg("final PreviewConfig", config);
819
+ const shutdown = () => {
820
+ htmlCleanup();
821
+ process.exit(0);
822
+ };
823
+ process.once("SIGINT", shutdown);
824
+ process.once("SIGTERM", shutdown);
825
+ try {
826
+ await preview(config);
827
+ }
828
+ catch (err) {
829
+ process.off("SIGINT", shutdown);
830
+ process.off("SIGTERM", shutdown);
831
+ htmlCleanup();
832
+ console.error("[preview] Full error:", err);
833
+ const message = err instanceof Error ? err.message : String(err);
834
+ throw new Error(`preview() failed:\n${message}`);
835
+ }
836
+ process.off("SIGINT", shutdown);
837
+ process.off("SIGTERM", shutdown);
838
+ htmlCleanup();
839
+ }
840
+ }
841
+ // ---------------------------------------------------------------------------
842
+ // Direct execution
843
+ // ---------------------------------------------------------------------------
844
+ let _resolvedEntry = null;
845
+ try {
846
+ _resolvedEntry = resolve(fileURLToPath(import.meta.url));
847
+ }
848
+ catch {
849
+ // ESM import.meta.url not available — not a direct invocation
850
+ }
851
+ function isDirectExecution() {
852
+ const entry = process.argv[1];
853
+ if (!entry || _resolvedEntry === null)
854
+ return false;
855
+ try {
856
+ return resolve(entry) === _resolvedEntry;
857
+ }
858
+ catch {
859
+ return false;
860
+ }
861
+ }
862
+ if (isDirectExecution()) {
863
+ if (process.argv.slice(2).length === 0) {
864
+ printHelp();
865
+ }
866
+ const parsed = parseArgs(process.argv);
867
+ if (!parsed) {
868
+ printHelp();
869
+ }
870
+ else {
871
+ execute(parsed.options, parsed.extraArgs).catch((err) => {
872
+ console.error(err instanceof Error ? err.message : err);
873
+ process.exit(1);
874
+ });
875
+ }
876
+ }
877
+
878
+ export { buildPreviewHtml, execute, extractUrlsFromHtml, isHtmlInput, mapAbsoluteUrlToLocal, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseStaticMapping, prepareInputHtmlForBuild, printHelp, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, splitArgsAtDoubleDash, startStaticServer, urlToStaticMapping };