@projektemacher/vivliostyle-batch-cli 0.1.2 → 0.3.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.
@@ -1,38 +1,46 @@
1
+ // src/vivliostyle-cli.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
1
6
  import { Command } from "commander";
2
- import { build, preview } from "@vivliostyle/cli";
3
- import { resolve, dirname, posix, join } from "node:path";
4
- import { readFileSync, existsSync, mkdtempSync, writeFileSync, rmSync, statSync, realpathSync } from "node:fs";
7
+ import { resolve, dirname, posix, join, basename, relative, isAbsolute, sep } from "node:path";
8
+ import { readFileSync, existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync, realpathSync } from "node:fs";
5
9
  import { fileURLToPath } from "node:url";
6
10
  import { tmpdir } from "node:os";
7
- import { AddressInfo } from "node:net";
8
- import { lookup as mimeLookup } from "mime-types";
9
- import express from "express";
10
- import serveStatic from "serve-static";
11
11
  import { JSDOM } from "jsdom";
12
-
13
- type BuildConfig = Parameters<typeof build>[0];
14
- type PreviewConfig = Parameters<typeof preview>[0];
15
- type VivliostyleConfigSchema = NonNullable<PreviewConfig["configData"]>;
16
- type StaticMap = VivliostyleConfigSchema extends { static?: infer S } ? NonNullable<S> : Record<string, string>;
17
-
18
- type OutputFormat = "pdf" | "epub" | "webpub";
12
+ import log, { type LogLevelDesc } from "loglevel";
13
+ import { VIEWER_PAGE_NAME, startStaticServer, type AssetBaseMapping, type SettleGate, type StaticMap } from "./server.js";
14
+ import { buildViewerUrl, renderPdf, type ViewerParams } from "./render/pdf.js";
15
+ import { resolveViewerLibDir } from "./render/viewer.js";
16
+ import { loadDefaultIccProfile } from "./render/pdf-postprocess.js";
17
+ import {
18
+ extractMetadataFromDocument,
19
+ extractMetadataFromManifest,
20
+ parsePdfaLabel,
21
+ parsePdfxLabel,
22
+ resolveMetadata,
23
+ type DocumentMetadata
24
+ } from "./metadata.js";
25
+ import type { PdfLabel } from "./render/xmp.js";
26
+
27
+ type OutputFormat = "pdf";
19
28
  type LogLevel = "silent" | "info" | "verbose" | "debug";
20
29
  type Mode = "build" | "preview";
21
30
 
22
- type AssetBaseMapping = {
23
- urlBase: string;
24
- localBase: string;
25
- };
26
-
27
31
  type CliOptions = {
28
32
  input: string;
29
33
  output: string;
30
34
  title?: string;
31
35
  author?: string;
36
+ subject?: string;
37
+ keywords?: string;
32
38
  language?: string;
39
+ pdfa?: string;
40
+ pdfx?: string;
41
+ iccProfile?: string;
33
42
  static: string[];
34
43
  scripts: boolean;
35
- cwd?: string;
36
44
  format: string;
37
45
  logLevel: string;
38
46
  debug?: boolean;
@@ -40,44 +48,357 @@ type CliOptions = {
40
48
  ignoreAsset: string[];
41
49
  mode: string;
42
50
  preview?: boolean;
51
+ allowRemote?: boolean;
52
+ fetchMissing?: boolean;
53
+ dumpHtml?: string;
54
+ waitForContent?: string | boolean;
55
+ pixelRatio?: string;
56
+ timeout?: string;
57
+ quietMs?: string;
43
58
  };
44
59
 
45
- // ---------------------------------------------------------------------------
46
- // Shared debug callback type
47
- // ---------------------------------------------------------------------------
48
-
49
- type Dbg = (_label: string, _value?: unknown) => void;
60
+ /**
61
+ * Options shared by the build-mode and preview-mode HTML rewriters.
62
+ */
63
+ export type HtmlRewriteOptions = {
64
+ /** Keep references that would be fetched from the network. Off by default. */
65
+ allowRemote?: boolean;
66
+ /** Write the rewritten HTML here (and keep it) instead of a temp file. */
67
+ dumpDir?: string | null;
68
+ /** Let the browser load references without a local file from the web. */
69
+ fetchMissing?: boolean;
70
+ /** Delay pagination until the page's own async work finished. */
71
+ settle?: SettleGate | null;
72
+ /** Origin that page-script requests are routed to. */
73
+ shimOrigin?: string | null;
74
+ /** Base that page-relative URLs resolve against (the page's directory). */
75
+ documentBaseUrl?: string | null;
76
+ /** Remote references that turned out not to exist. */
77
+ unavailableUrls?: Set<string>;
78
+ /** Extra CSS handed to the viewer (`@page` rules, print tweaks). */
79
+ css?: string;
80
+ /** Additional user stylesheet for the viewer. */
81
+ userStyle?: string;
82
+ };
50
83
 
51
- const validFormats: readonly OutputFormat[] = ["pdf", "epub", "webpub"];
84
+ const validFormats: readonly OutputFormat[] = ["pdf"];
52
85
  const validLogLevels: readonly LogLevel[] = ["silent", "info", "verbose", "debug"];
53
86
  const validModes: readonly Mode[] = ["build", "preview"];
54
87
 
88
+ /**
89
+ * Wrapper log levels mapped onto loglevel. Diagnostics are written to the trace
90
+ * channel, so `--log-level verbose` stays quiet while `debug` shows them.
91
+ */
92
+ const LOG_LEVELS: Record<LogLevel, LogLevelDesc> = {
93
+ silent: log.levels.SILENT,
94
+ info: log.levels.INFO,
95
+ verbose: log.levels.DEBUG,
96
+ debug: log.levels.TRACE
97
+ };
98
+
99
+ /**
100
+ * Send every level to the console channel the CLI contract uses: progress to
101
+ * stdout, diagnostics and problems to stderr. The method is resolved per call so
102
+ * that patched consoles stay visible.
103
+ */
104
+ const CONSOLE_CHANNEL: Record<string, "log" | "warn" | "error"> = {
105
+ trace: "error",
106
+ debug: "error",
107
+ info: "log",
108
+ warn: "warn",
109
+ error: "error"
110
+ };
111
+
112
+ log.methodFactory =
113
+ (methodName: string) =>
114
+ (...args: unknown[]): void => {
115
+ (console[CONSOLE_CHANNEL[methodName] ?? "log"] as (...values: unknown[]) => void)(...args);
116
+ };
117
+
55
118
  // ---------------------------------------------------------------------------
56
- // HTML input detection
119
+ // Site path + settle gate helpers
57
120
  // ---------------------------------------------------------------------------
58
121
 
122
+ /** Directory part of a site path, without a trailing slash (`""` for the root). */
123
+ export function siteDirectory(sitePath: string): string {
124
+ const dir = posix.dirname(sitePath);
125
+ return dir === "/" ? "" : dir;
126
+ }
127
+
59
128
  /**
60
- * Returns true when the input file should be treated as HTML.
61
- * Vivliostyle also accepts publication manifests (JSON/TOML/JS config files);
62
- * we detect HTML by extension to avoid trying to parse those as markup.
129
+ * Path the document has on the mapped site, e.g. `/post/tag-pairs/article.html`
130
+ * for `<localBase>/post/tag-pairs/article.html`. Used as the URL Vivliostyle
131
+ * loads, so page-relative and root-relative references resolve like they do on
132
+ * the real site.
63
133
  */
64
- export function isHtmlInput(inputAbs: string): boolean {
65
- return /\.html?$/i.test(inputAbs);
134
+ export function deriveSitePath(inputAbs: string, assetBases: AssetBaseMapping[]): string | null {
135
+ for (const ab of assetBases) {
136
+ const relativePath = relative(resolve(ab.localBase), resolve(inputAbs));
137
+ if (relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath)) continue;
138
+ return `/${relativePath.split(sep).join("/")}`;
139
+ }
140
+ return null;
66
141
  }
67
142
 
68
- // ---------------------------------------------------------------------------
69
- // Debug logger
70
- // ---------------------------------------------------------------------------
143
+ /**
144
+ * Tracker injected into the document. It wraps fetch/XHR, watches the document
145
+ * for late content and reports back once nothing is pending and the height has
146
+ * been stable for `quietMs` — or when the deadline is reached.
147
+ */
148
+ export type RuntimeScriptOptions = {
149
+ origin: string;
150
+ documentBaseUrl: string;
151
+ gate: SettleGate | null;
152
+ /**
153
+ * Open every `<details>` element. Vivliostyle loads the page's scripts itself
154
+ * and only re-dispatches `DOMContentLoaded` on the window, so scripts that
155
+ * wait for it on the document — the usual way to expand collapsible content —
156
+ * never run and their content would be missing from the PDF.
157
+ */
158
+ expandDetails?: boolean;
159
+ };
71
160
 
72
- function makeDbg(enabled: boolean): Dbg {
73
- return (_label: string, _value?: unknown): void => {
74
- if (!enabled) return;
75
- if (_value === undefined) {
76
- console.error(`[debug] ${_label}`);
77
- } else {
78
- console.error(`[debug] ${_label}`, JSON.stringify(_value, null, 2));
161
+ /**
162
+ * Opens every `<details>` element, now and for any the page adds later.
163
+ *
164
+ * Print output has to contain the collapsed content too, and the page's own
165
+ * print script cannot do it: Vivliostyle re-dispatches `DOMContentLoaded` on
166
+ * the window rather than on the document, so a `document`-level listener never
167
+ * runs.
168
+ */
169
+ export const EXPAND_DETAILS_SNIPPET = `function expandDetails(root){
170
+ var open=function(el){
171
+ if(el.tagName!=="DETAILS"||el.open)return;
172
+ el.open=true;
173
+ el.setAttribute("data-viv-details-expanded","");
174
+ };
175
+ if(root.nodeType!==1)return;
176
+ [].forEach.call(root.querySelectorAll("details"),open);
177
+ open(root);
178
+ }
179
+ expandDetails(document);
180
+ try{new MutationObserver(function(records){
181
+ for(var i=0;i<records.length;i++){
182
+ var added=records[i].addedNodes;
183
+ for(var j=0;j<added.length;j++)expandDetails(added[j]);
184
+ }
185
+ }).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
186
+ `;
187
+
188
+ /** Gate image Vivliostyle waits for before it paginates. */
189
+ export function buildSettleGateImage(origin: string): string {
190
+ // Out of flow and invisible, but rendered: Vivliostyle only loads resources of
191
+ // elements that end up in the render tree, so `display:none` would be skipped.
192
+ return `<img src="${origin}/__viv-settle" alt="" width="1" height="1" style="position:absolute;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none" data-vivliostyle-settle-gate>`;
193
+ }
194
+
195
+ /**
196
+ * The script injected into the document: it routes the URLs that page scripts
197
+ * create to our server and tracks whether the page has finished.
198
+ *
199
+ * Everything lives in one scope on purpose — the settle tracker wraps the same
200
+ * `fetch`/XHR that the routing patches.
201
+ */
202
+ export function buildRuntimeScript(options: RuntimeScriptOptions): string {
203
+ const { origin, documentBaseUrl, gate } = options;
204
+ const expandDetails = options.expandDetails === true ? EXPAND_DETAILS_SNIPPET : "";
205
+ // Vivliostyle paginates incrementally, so collapsed content has to be opened
206
+ // again while it lays the document out, not just once up front.
207
+ const expandDetailsTick = options.expandDetails === true ? "expandDetails(document);" : "";
208
+
209
+ return `(function(){
210
+ var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
211
+ var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
212
+ var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
213
+ // Force preserveDrawingBuffer on every WebGL context the page creates:
214
+ // print-to-PDF otherwise captures the cleared drawing buffer and WebGL
215
+ // content ships empty, even though the browser shows it composited.
216
+ try {
217
+ var origGetContext = HTMLCanvasElement.prototype.getContext;
218
+ HTMLCanvasElement.prototype.getContext = function (type, attrs) {
219
+ if (typeof type === "string" && /^webgl/.test(type)) {
220
+ attrs = Object.assign({}, attrs || {});
221
+ attrs.preserveDrawingBuffer = true;
222
+ return origGetContext.call(this, type, attrs);
79
223
  }
224
+ return origGetContext.call(this, type, attrs);
225
+ };
226
+ } catch (e) {}
227
+ // Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
228
+ // waiting for it on the document (framework bootstraps, print scripts, asset
229
+ // bootstraps) never run. Re-dispatch the lifecycle events properly once
230
+ // loading finished.
231
+ try {
232
+ var redeliver = function () {
233
+ setTimeout(function () {
234
+ try {
235
+ document.dispatchEvent(new Event("DOMContentLoaded"));
236
+ window.dispatchEvent(new Event("DOMContentLoaded"));
237
+ window.dispatchEvent(new Event("load"));
238
+ } catch (e) {}
239
+ }, 0);
80
240
  };
241
+ if (document.readyState === "complete") redeliver();
242
+ else window.addEventListener("load", redeliver, { once: true });
243
+ } catch (e) {}
244
+ var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
245
+
246
+ // Root-relative URLs resolve against the site root, document-relative ones
247
+ // against the directory the page has on the site (e.g. model/x.glb next to it).
248
+ function fix(u){
249
+ if(typeof u!=="string"||u==="")return u;
250
+ if(u.slice(0,2)==="//"||u.charAt(0)==="#"||u.charAt(0)==="?")return u;
251
+ if(/^[a-z][a-z0-9+.-]*:/i.test(u))return u;
252
+ return u.charAt(0)==="/"?ORIGIN+u:BASE+u;
253
+ }
254
+
255
+ function canvases(){
256
+ try{return[].map.call(document.querySelectorAll("canvas"),function(c){
257
+ return c.width+"x"+c.height+"@"+Math.round(c.clientWidth)+"x"+Math.round(c.clientHeight);}).join(",");}catch(e){return"";}
258
+ }
259
+ // Canvases with real backing pixels and layout size: the minimum for charts,
260
+ // three.js, maps and OSD tiles to survive print-to-PDF as sharp raster.
261
+ function paintedCanvases(){
262
+ try{return[].filter.call(document.querySelectorAll("canvas"),function(c){
263
+ return c.width>2&&c.height>2&&c.clientWidth>0&&c.clientHeight>0;}).length;}catch(e){return 0;}
264
+ }
265
+ // Sizes of the containers pages fill at runtime; zero means the layout has not
266
+ // happened yet, which is what breaks canvas and chart initialisation.
267
+ function containers(){
268
+ try{return[].map.call(document.querySelectorAll(".script,[class*=script]"),function(el){
269
+ return (el.id||el.className)+"@"+Math.round(el.clientWidth)+"x"+Math.round(el.clientHeight);}).join(",");}catch(e){return"";}
270
+ }
271
+
272
+ function signal(why){
273
+ if(done)return;done=true;
274
+ var at=Math.round(performance.now());
275
+ state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
276
+ var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
277
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
278
+ "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
279
+ "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
280
+ try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
281
+ }
282
+
283
+ // An embed that never fires load must not hold the layout open forever.
284
+ function watchFrame(frame){
285
+ if(frame.__vivWatched)return;frame.__vivWatched=true;frames++;
286
+ var settled=false;
287
+ function finish(){if(settled)return;settled=true;frames--;last=performance.now();}
288
+ frame.addEventListener("load",finish);
289
+ frame.addEventListener("error",finish);
290
+ try{ if(frame.contentDocument&&frame.contentDocument.readyState==="complete"){finish();return;} }catch(e){}
291
+ setTimeout(finish,FRAME_GRACE);
292
+ }
293
+ function watchFrames(root){
294
+ try{
295
+ [].forEach.call(root.querySelectorAll("iframe"),watchFrame);
296
+ if(root.tagName==="IFRAME")watchFrame(root);
297
+ }catch(e){}
298
+ }
299
+
300
+ var of=window.fetch;
301
+ if(of){window.fetch=function(input,init){
302
+ try{
303
+ if(typeof input==="string")input=fix(input);
304
+ else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
305
+ }catch(e){}
306
+ pending++;last=performance.now();
307
+ var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
308
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();
309
+ try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
310
+ return v;},
311
+ function(e){pending--;last=performance.now();
312
+ try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
313
+ throw e;});};}
314
+ var XHR=window.XMLHttpRequest;
315
+ if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
316
+ XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
317
+ XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
318
+ this.addEventListener("loadend",function(){pending--;last=performance.now();
319
+ try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
320
+ return send.apply(this,arguments);};}
321
+ // WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
322
+ // alone would report idle mid-compile. Hold pending through it.
323
+ var WA=window.WebAssembly;
324
+ if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
325
+ var orig=WA[n];if(typeof orig!=="function")return;
326
+ WA[n]=function(){pending++;last=performance.now();
327
+ var result;
328
+ try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
329
+ if(result&&typeof result.then==="function"){
330
+ return result.then(function(v){pending--;last=performance.now();return v;},
331
+ function(e){pending--;last=performance.now();throw e;});
332
+ }
333
+ pending--;last=performance.now();return result;};});}
334
+ // Heavy main-thread work (script eval, wasm compile, shader/layout jank)
335
+ // emits no network or DOM signal; long tasks keep the quiet window open.
336
+ try{var PO=window.PerformanceObserver;
337
+ if(typeof PO==="function"){new PO(function(list){
338
+ var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
339
+ }).observe({entryTypes:["longtask"]});}}catch(e){}
340
+ ["Image","Audio"].forEach(function(n){
341
+ var Orig=window[n];if(!Orig)return;
342
+ var Wrapped=function(u){return new Orig(fix(u));};
343
+ Wrapped.prototype=Orig.prototype;
344
+ try{window[n]=Wrapped;}catch(e){}
345
+ });
346
+ ["HTMLImageElement","HTMLIFrameElement","HTMLScriptElement","HTMLSourceElement","HTMLVideoElement","HTMLAudioElement"].forEach(function(n){
347
+ var C=window[n];if(!C)return;
348
+ var d=Object.getOwnPropertyDescriptor(C.prototype,"src");
349
+ if(!d||!d.set)return;
350
+ try{Object.defineProperty(C.prototype,"src",{configurable:true,enumerable:d.enumerable,get:d.get,
351
+ set:function(v){d.set.call(this,fix(v));if(n==="HTMLIFrameElement")watchFrame(this);}});}catch(e){}
352
+ });
353
+ try{Object.defineProperty(document,"baseURI",{configurable:true,get:function(){return BASE;}});}catch(e){}
354
+ try{new MutationObserver(function(){mutations++;watchFrames(document.documentElement);last=performance.now();})
355
+ .observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
356
+ try{new ResizeObserver(function(){last=performance.now();}).observe(document.documentElement);}catch(e){}
357
+ ${expandDetails}watchFrames(document.documentElement);
358
+ last=performance.now();
359
+ (function check(){
360
+ if(done)return;
361
+ ${expandDetailsTick}
362
+ var now=performance.now();
363
+ if(now>=DEADLINE){signal("deadline");return;}
364
+ // Webfonts loading late would leave canvas text painted with fallbacks.
365
+ try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
366
+ // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
367
+ // painted instead of making the gate guess from network quietness. Shader
368
+ // compile and tile decode finish after the last fetch, so readiness wins.
369
+ if(window.__vivReady===true&&pending===0&&frames===0){signal("ready");return;}
370
+ if(pending===0&&frames===0&&now-last>=QUIET){signal("quiet");return;}
371
+ setTimeout(check,50);
372
+ })();
373
+ })();`;
374
+ }
375
+
376
+ /**
377
+ * Injects the runtime script as the first thing in `<head>` (so it wraps `fetch`
378
+ * before any page script runs) and the gate image at the end of `<body>`.
379
+ */
380
+ export function injectRuntimeScriptInDom(document: Document, options: RuntimeScriptOptions): void {
381
+ const head = document.head;
382
+ const anchor = head.firstChild;
383
+
384
+ const base = document.createElement("base");
385
+ base.setAttribute("href", options.documentBaseUrl);
386
+ head.insertBefore(base, anchor);
387
+
388
+ const script = document.createElement("script");
389
+ script.textContent = buildRuntimeScript(options);
390
+ head.insertBefore(script, anchor);
391
+
392
+ if (options.gate === null) return;
393
+ document.body?.insertAdjacentHTML("beforeend", buildSettleGateImage(options.origin));
394
+ }
395
+
396
+ // ---------------------------------------------------------------------------
397
+ // HTML input detection
398
+ // ---------------------------------------------------------------------------
399
+
400
+ export function isHtmlInput(inputAbs: string): boolean {
401
+ return /\.html?$/i.test(inputAbs);
81
402
  }
82
403
 
83
404
  // ---------------------------------------------------------------------------
@@ -94,167 +415,464 @@ export function splitArgsAtDoubleDash(argv: string[]): {
94
415
  }
95
416
 
96
417
  // ---------------------------------------------------------------------------
97
- // Static HTTP server (build mode only)
418
+ // Static mappings
98
419
  // ---------------------------------------------------------------------------
99
420
 
100
- type StaticServer = {
101
- baseUrl: string;
102
- close: () => void;
103
- };
421
+ /**
422
+ * Serve a single local file directly, bypassing Vite's transform pipeline.
423
+ * Returns true if the file was served, false if it should fall through.
424
+ */
425
+
426
+ // ---------------------------------------------------------------------------
427
+ // DOM-level rewriters
428
+ // ---------------------------------------------------------------------------
429
+
430
+ const URL_ATTR_SELECTORS: Array<[string, string]> = [
431
+ ["link[href]", "href"],
432
+ ["script[src]", "src"],
433
+ ["img[src]", "src"],
434
+ ["source[src]", "src"],
435
+ ["video[src]", "src"],
436
+ ["audio[src]", "src"],
437
+ ["video[poster]", "poster"],
438
+ ["input[src]", "src"]
439
+ ];
440
+
441
+ /**
442
+ * Subresource attributes that would trigger a network request. Hyperlink
443
+ * attributes (`<a href>`) are deliberately absent: a link is not fetched.
444
+ */
445
+ const SUBRESOURCE_ATTR_SELECTORS: Array<[string, string]> = [
446
+ ...URL_ATTR_SELECTORS,
447
+ ["img[srcset]", "srcset"],
448
+ ["source[srcset]", "srcset"],
449
+ ["iframe[src]", "src"],
450
+ ["object[data]", "data"],
451
+ ["embed[src]", "src"],
452
+ // A-Frame keeps its assets in custom elements
453
+ ["a-asset-item[src]", "src"]
454
+ ];
455
+
456
+ /** URL schemes that never leave the document. */
457
+ const INLINE_URL_SCHEME_RE = /^(?:data|blob|about|javascript|mailto|tel):/i;
458
+
459
+ /**
460
+ * Applies `transform` to every URL of every subresource attribute.
461
+ *
462
+ * A `srcset` candidate list is transformed candidate by candidate, keeping the
463
+ * descriptors (`1x`, `480w`). Returning `null` drops the candidate; an attribute
464
+ * without any remaining candidate is removed.
465
+ */
466
+ export function rewriteUrlAttributes(document: Document, transform: (url: string) => string | null): boolean {
467
+ let changed = false;
468
+
469
+ const apply = (el: Element, attr: string): void => {
470
+ const raw = el.getAttribute(attr);
471
+ if (raw === null) return;
472
+
473
+ if (attr !== "srcset") {
474
+ const current = raw.trim();
475
+ const next = transform(current);
476
+ if (next === null) {
477
+ el.removeAttribute(attr);
478
+ changed = true;
479
+ return;
480
+ }
481
+ if (next === current) return;
482
+ el.setAttribute(attr, next);
483
+ changed = true;
484
+ return;
485
+ }
486
+
487
+ const candidates = raw
488
+ .split(",")
489
+ .map((candidate) => candidate.trim())
490
+ .filter(Boolean);
491
+
492
+ const kept: string[] = [];
493
+ let touched = false;
494
+
495
+ for (const candidate of candidates) {
496
+ const [url, ...descriptor] = candidate.split(/\s+/);
497
+ const next = transform(url);
498
+ if (next === null) {
499
+ touched = true;
500
+ continue;
501
+ }
502
+ if (next !== url) touched = true;
503
+ kept.push([next, ...descriptor].join(" "));
504
+ }
505
+
506
+ if (!touched) return;
507
+ changed = true;
508
+ if (kept.length === 0) el.removeAttribute(attr);
509
+ else el.setAttribute(attr, kept.join(", "));
510
+ };
104
511
 
105
- function makeMimeHeaders(res: express.Response, filePath: string): void {
106
- const mime = mimeLookup(filePath);
107
- if (mime) res.setHeader("Content-Type", mime);
512
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
513
+ for (const el of document.querySelectorAll(selector)) apply(el, attr);
514
+ }
515
+
516
+ return changed;
108
517
  }
109
518
 
110
- function isFile(localPath: string): boolean {
111
- try {
112
- return statSync(localPath).isFile();
113
- } catch {
114
- return false;
519
+ /**
520
+ * True when the browser would have to fetch the URL over the network.
521
+ */
522
+ export function isRemoteUrl(value: string): boolean {
523
+ const trimmed = value.trim();
524
+ if (!trimmed) return false;
525
+ if (trimmed.startsWith("//")) return true;
526
+ return /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !INLINE_URL_SCHEME_RE.test(trimmed);
527
+ }
528
+
529
+ /**
530
+ * Drops subresource references that are not available locally so nothing is
531
+ * fetched from the web. `srcset` candidates are filtered individually; an
532
+ * attribute whose candidates are all remote is removed entirely.
533
+ *
534
+ * `isAllowed` exempts URLs that are served by the wrapper itself, e.g. the
535
+ * static server URLs produced by the virtual-path rewrite.
536
+ *
537
+ * Returns every dropped URL.
538
+ */
539
+ export function dropRemoteReferencesInDom(document: Document, isAllowed: (url: string) => boolean = () => false): string[] {
540
+ const dropped: string[] = [];
541
+
542
+ const droppedSet = new Set<string>();
543
+ rewriteUrlAttributes(document, (url) => {
544
+ if (isAllowed(url) || !isRemoteUrl(url)) return url;
545
+ droppedSet.add(url);
546
+ return null;
547
+ });
548
+ dropped.push(...droppedSet);
549
+
550
+ // A meta refresh navigates the document, which is a fetch just like a
551
+ // subresource. Redirect stubs are dropped as well.
552
+ for (const el of document.querySelectorAll("meta[http-equiv]")) {
553
+ if ((el.getAttribute("http-equiv") ?? "").toLowerCase() !== "refresh") continue;
554
+ const target = parseMetaRefreshTarget(el.getAttribute("content") ?? "");
555
+ if (target === null || !isRemoteUrl(target) || isAllowed(target)) continue;
556
+ el.remove();
557
+ dropped.push(target);
115
558
  }
559
+
560
+ return dropped;
116
561
  }
117
562
 
118
- function applyStaticMounts(app: express.Express, staticMap: Record<string, string>, assetBases: AssetBaseMapping[], dbg: Dbg): void {
119
- for (const [virtual, localBase] of Object.entries(staticMap)) {
120
- const absLocal = resolve(localBase);
121
- if (isFile(absLocal)) {
122
- app.get(virtual, (_req, res) => {
123
- dbg("[static-server] serving file", { virtual, absLocal });
124
- const mime = mimeLookup(absLocal);
125
- if (mime) res.type(mime);
126
- res.sendFile(absLocal);
127
- });
128
- console.log(`[static-server] File route: GET ${virtual} → ${absLocal}`);
129
- } else {
130
- const mountPath = virtual.endsWith("/") ? virtual : `${virtual}/`;
131
- app.use(
132
- mountPath,
133
- serveStatic(absLocal, {
134
- fallthrough: true,
135
- setHeaders: makeMimeHeaders
136
- })
137
- );
138
- console.log(`[static-server] Dir mount: ${mountPath} → ${absLocal}`);
563
+ /**
564
+ * Extracts the target of `<meta http-equiv="refresh" content="0; url=…">`.
565
+ */
566
+ export function parseMetaRefreshTarget(content: string): string | null {
567
+ const match = /^\s*[\d.]*\s*;?\s*url\s*=\s*(.*)$/i.exec(content);
568
+ if (match === null) return null;
569
+ const target = match[1].trim().replace(/^["']|["']$/g, "");
570
+ return target === "" ? null : target;
571
+ }
572
+
573
+ /**
574
+ * Root-relative subresource paths that survive the rewrites and therefore end
575
+ * up resolved against the file system location of the input document. They are
576
+ * broken unless something else provides them (e.g. the input is served over
577
+ * HTTP), so they are worth reporting.
578
+ */
579
+ export function collectUnservedVirtualPaths(
580
+ document: Document,
581
+ staticMapKeys: string[],
582
+ isServable?: (virtualPath: string) => boolean
583
+ ): string[] {
584
+ const isMapped = (path: string): boolean =>
585
+ staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
586
+
587
+ const unserved = new Set<string>();
588
+
589
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
590
+ for (const el of document.querySelectorAll(selector)) {
591
+ const raw = el.getAttribute(attr);
592
+ if (raw === null) continue;
593
+
594
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
595
+ for (const value of values) {
596
+ if (!value.startsWith("/")) continue;
597
+ if (isMapped(value)) continue;
598
+ if (isServable !== undefined && isServable(value)) continue;
599
+ unserved.add(value);
600
+ }
139
601
  }
140
- dbg("[static-server] mount", { virtual, absLocal });
141
602
  }
142
603
 
143
- for (const ab of assetBases) {
144
- const absLocal = resolve(ab.localBase);
145
- app.use("/", serveStatic(absLocal, { fallthrough: true, setHeaders: makeMimeHeaders }));
146
- dbg("[static-server] assetBase fallback mount", absLocal);
147
- console.log(`[static-server] Fallback mount: / → ${absLocal}`);
148
- }
604
+ return [...unserved];
149
605
  }
150
606
 
151
- export function startStaticServer(
152
- staticMap: Record<string, string>,
153
- assetBases: AssetBaseMapping[],
154
- htmlFilePath: string | null,
155
- dbg: Dbg,
156
- port = 0
157
- ): Promise<StaticServer> {
158
- const app = express();
159
- app.disable("x-powered-by");
160
-
161
- if (htmlFilePath !== null) {
162
- const absHtmlPath = resolve(htmlFilePath);
163
- app.get("/index.html", (_req, res) => {
164
- dbg("[static-server] serving HTML entry", absHtmlPath);
165
- res.type("text/html").sendFile(absHtmlPath);
166
- });
167
- console.log(`[static-server] HTML entry: /index.html → ${absHtmlPath}`);
607
+ /** Remote subresource URLs a document would have to fetch. */
608
+ export function collectRemoteReferences(document: Document): string[] {
609
+ const urls = new Set<string>();
610
+
611
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
612
+ for (const el of document.querySelectorAll(selector)) {
613
+ const raw = el.getAttribute(attr);
614
+ if (raw === null) continue;
615
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
616
+ for (const value of values) {
617
+ if (isRemoteUrl(value)) urls.add(value);
618
+ }
619
+ }
168
620
  }
169
621
 
170
- applyStaticMounts(app, staticMap, assetBases, dbg);
622
+ return [...urls];
623
+ }
171
624
 
172
- app.use((req: express.Request, res: express.Response) => {
173
- dbg("[static-server] 404", req.url);
174
- res.status(404).type("text").send(`404 Not Found: ${req.url}`);
175
- });
625
+ /**
626
+ * Whether a remote reference is worth probing on the live site.
627
+ *
628
+ * A reference that resolves to a local file is served from disk, so only that
629
+ * file decides whether it stays: the live site may have moved on (a new CSS
630
+ * hash, a rotated upload) while our copy of the page still has what it needs.
631
+ */
632
+ export function referencesToProbe(url: string, assetBases: AssetBaseMapping[]): boolean {
633
+ const mapped = mapAbsoluteUrlToLocal(url, assetBases);
634
+ return mapped.kind === "mapped" ? !existsSync(mapped.localPath) : true;
635
+ }
176
636
 
177
- return new Promise((resolvePromise, reject) => {
178
- const httpServer = app.listen(port, "127.0.0.1", () => {
179
- const addr = httpServer.address() as AddressInfo;
180
- const baseUrl = `http://127.0.0.1:${addr.port}`;
181
- console.log(`[static-server] Listening on ${baseUrl}`);
182
- dbg("[static-server] staticMap", staticMap);
183
- dbg(
184
- "[static-server] assetBase roots",
185
- assetBases.map((ab) => ab.localBase)
186
- );
637
+ /**
638
+ * Checks which remote references actually exist, so that content that is gone
639
+ * (a deleted slide deck, a retired CSS file) is dropped instead of leaving a
640
+ * broken embed that never finishes loading.
641
+ */
642
+ export async function probeRemoteReferences(urls: string[], timeoutMs = 8000): Promise<Set<string>> {
643
+ const unavailable = new Set<string>();
187
644
 
188
- let closed = false;
189
- const close = (): void => {
190
- if (closed) return;
191
- closed = true;
192
- httpServer.close((err) => {
193
- if (err) console.warn(`[static-server] close error: ${err.message}`);
194
- else dbg("[static-server] stopped");
195
- });
196
- };
645
+ await Promise.all(
646
+ urls.map(async (url) => {
647
+ try {
648
+ const response = await fetch(url, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
649
+ // Only a definite "gone" counts: servers that reject HEAD still have the file.
650
+ if (response.status === 404 || response.status === 410) unavailable.add(url);
651
+ log.trace("probeRemoteReferences", { url, status: response.status });
652
+ } catch (err) {
653
+ // A failed probe is no proof that the resource is gone: Chromium loads
654
+ // it with a browser user agent, which many sites accept where a HEAD
655
+ // request from Node is rejected or blocked outright.
656
+ log.trace("probeRemoteReferences failed", { url, error: String(err) });
657
+ }
658
+ })
659
+ );
197
660
 
198
- resolvePromise({ baseUrl, close });
199
- });
200
- httpServer.once("error", reject);
201
- });
661
+ return unavailable;
662
+ }
663
+
664
+ /** Removes the attributes that point at the given URLs. */
665
+ export function dropUnavailableReferencesInDom(document: Document, unavailable: Set<string>): string[] {
666
+ if (unavailable.size === 0) return [];
667
+ const dropped: string[] = [];
668
+
669
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
670
+ for (const el of document.querySelectorAll(selector)) {
671
+ const raw = el.getAttribute(attr);
672
+ if (raw === null) continue;
673
+ const values = attr === "srcset" ? raw.split(",").map((entry) => entry.trim().split(/\s+/)[0] ?? "") : [raw.trim()];
674
+ const hit = values.filter((value) => unavailable.has(value));
675
+ if (hit.length === 0) continue;
676
+
677
+ dropped.push(...hit);
678
+ const kept =
679
+ attr === "srcset"
680
+ ? raw
681
+ .split(",")
682
+ .map((e) => e.trim())
683
+ .filter((c) => !unavailable.has(c.split(/\s+/)[0] ?? ""))
684
+ : [];
685
+ if (kept.length === 0) el.removeAttribute(attr);
686
+ else el.setAttribute(attr, kept.join(", "));
687
+ }
688
+ }
689
+
690
+ for (const url of new Set(dropped)) {
691
+ log.warn(`[fetch] Dropped unavailable remote reference: ${url}`);
692
+ }
693
+ return dropped;
694
+ }
695
+
696
+ /**
697
+ * Exempts the wrapper's own static server from the offline pass: URLs pointing
698
+ * at it are served from the local file system, never from the web.
699
+ */
700
+ export function isStaticServerUrl(serverBaseUrl: string): (url: string) => boolean {
701
+ return (url: string): boolean => serverBaseUrl !== "" && url.startsWith(serverBaseUrl);
702
+ }
703
+
704
+ function reportDroppedRemoteRefs(dropped: string[]): void {
705
+ for (const url of new Set(dropped)) {
706
+ log.info(`[offline] Dropped remote reference: ${url}`);
707
+ }
708
+ log.trace("dropRemoteReferencesInDom: dropped", dropped);
709
+ }
710
+
711
+ function reportUnservedVirtualPaths(unserved: string[]): void {
712
+ for (const path of unserved) {
713
+ log.warn(`[html] Warning: reference is not available and will not resolve: ${path}`);
714
+ }
202
715
  }
203
716
 
204
717
  // ---------------------------------------------------------------------------
205
- // DOM-level rewriters
718
+ // Asset base match result
206
719
  // ---------------------------------------------------------------------------
207
720
 
208
- const URL_ATTR_SELECTORS: Array<[string, string]> = [
209
- ["link[href]", "href"],
210
- ["script[src]", "src"],
211
- ["img[src]", "src"],
212
- ["source[src]", "src"],
213
- ["video[src]", "src"],
214
- ["audio[src]", "src"],
215
- ["video[poster]", "poster"],
216
- ["input[src]", "src"]
217
- ];
721
+ /**
722
+ * Discriminated union returned by mapAbsoluteUrlToLocal.
723
+ *
724
+ * - "mapped" — the URL matched an asset-base prefix and has a sub-path that
725
+ * can be mapped to a local file.
726
+ * - "root-only" — the URL matched a prefix but carried no sub-path (i.e. the
727
+ * URL is exactly the base root). The caller should skip it
728
+ * with a precise message rather than treating it as an
729
+ * unrecognised external URL.
730
+ * - "no-match" — no asset-base prefix matched; caller handles as usual.
731
+ */
732
+ type AssetBaseMatch = { kind: "mapped"; virtualPath: string; localPath: string } | { kind: "root-only" } | { kind: "no-match" };
218
733
 
219
- export function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[]): boolean {
220
- if (assetBases.length === 0) return false;
221
- let changed = false;
734
+ export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): AssetBaseMatch {
735
+ for (const mapping of assetBases) {
736
+ if (!url.startsWith(mapping.urlBase)) continue;
222
737
 
223
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
224
- for (const el of document.querySelectorAll(selector)) {
225
- const val = el.getAttribute(attr) ?? "";
226
- const mapped = mapAbsoluteUrlToLocal(val, assetBases);
227
- if (mapped) {
228
- el.setAttribute(attr, mapped.virtualPath);
229
- changed = true;
230
- }
738
+ let cleanRelative: string;
739
+ try {
740
+ cleanRelative = new URL(url).pathname.slice(1);
741
+ } catch {
742
+ const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
743
+ cleanRelative = noQuery.split("#")[0];
231
744
  }
232
- }
233
745
 
234
- return changed;
746
+ if (!cleanRelative) {
747
+ // The URL points to the asset-base root itself
748
+ // (e.g. https://cdn.example.com/ with no sub-path).
749
+ return { kind: "root-only" };
750
+ }
751
+
752
+ const virtualPath = posix.resolve("/", cleanRelative);
753
+ const localPath = resolve(mapping.localBase, cleanRelative);
754
+ return { kind: "mapped", virtualPath, localPath };
755
+ }
756
+ return { kind: "no-match" };
235
757
  }
236
758
 
237
- export function rewriteVirtualPathsToServerInDom(document: Document, staticMapKeys: string[], serverBaseUrl: string): boolean {
238
- let changed = false;
759
+ export function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[], keepMissing = false): boolean {
760
+ if (assetBases.length === 0) return false;
761
+
762
+ // "root-only" and "no-match" — leave the URL unchanged. With `keepMissing`,
763
+ // URLs whose local file does not exist keep their absolute form so the browser
764
+ // can load them from the mapped origin.
765
+ return rewriteUrlAttributes(document, (url) => {
766
+ const match = mapAbsoluteUrlToLocal(url, assetBases);
767
+ if (match.kind !== "mapped") return url;
768
+ if (keepMissing && !existsSync(match.localPath)) return url;
769
+ return match.virtualPath;
770
+ });
771
+ }
239
772
 
773
+ export function rewriteVirtualPathsToServerInDom(
774
+ document: Document,
775
+ staticMapKeys: string[],
776
+ serverBaseUrl: string,
777
+ isServable?: (virtualPath: string) => boolean
778
+ ): boolean {
240
779
  const shouldRewrite = (path: string): boolean => {
241
780
  if (!path.startsWith("/")) return false;
242
- return staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`));
781
+ if (staticMapKeys.some((virtual) => path === virtual || path.startsWith(virtual.endsWith("/") ? virtual : `${virtual}/`))) return true;
782
+ return isServable !== undefined && isServable(path);
243
783
  };
244
784
 
245
- for (const [selector, attr] of URL_ATTR_SELECTORS) {
246
- for (const el of document.querySelectorAll(selector)) {
247
- const val = el.getAttribute(attr) ?? "";
248
- if (shouldRewrite(val)) {
249
- el.setAttribute(attr, `${serverBaseUrl}${val}`);
250
- changed = true;
251
- }
785
+ return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
786
+ }
787
+
788
+ /**
789
+ * Resolves relative URLs on custom elements (`<a-asset-item>`,
790
+ * `<model-viewer>`, and any tag name containing a dash) to absolute server
791
+ * URLs.
792
+ *
793
+ * Vivliostyle resolves the subresource attributes it knows (`<img>`,
794
+ * `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
795
+ * understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
796
+ * `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
797
+ * the viewer those instead. Standard elements are left alone (the viewer and
798
+ * the runtime URL shim already handle them); only dash-tagged elements, whose
799
+ * attributes the viewer cannot be trusted with, are rewritten.
800
+ */
801
+ export function rewriteCustomElementUrlsInDom(document: Document, documentDirUrl: string): boolean {
802
+ let changed = false;
803
+
804
+ const resolveOne = (url: string): string => {
805
+ const current = url.trim();
806
+ if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//")) return current;
807
+ // Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
808
+ // are covered by the server-URL rewrite.
809
+ if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/")) return current;
810
+ try {
811
+ const resolved = new URL(current, documentDirUrl).href;
812
+ return resolved === current ? current : resolved;
813
+ } catch {
814
+ return current;
252
815
  }
816
+ };
817
+
818
+ const apply = (el: Element, attr: "src" | "srcset"): void => {
819
+ const raw = el.getAttribute(attr);
820
+ if (raw === null) return;
821
+ if (attr === "src") {
822
+ const next = resolveOne(raw);
823
+ if (next === raw.trim() || next === raw) return;
824
+ el.setAttribute(attr, next);
825
+ changed = true;
826
+ return;
827
+ }
828
+ const kept = raw
829
+ .split(",")
830
+ .map((candidate) => candidate.trim())
831
+ .filter(Boolean)
832
+ .map((candidate) => {
833
+ const [url, ...descriptor] = candidate.split(/\s+/);
834
+ return [resolveOne(url), ...descriptor].join(" ");
835
+ });
836
+ const next = kept.join(", ");
837
+ if (next === raw) return;
838
+ el.setAttribute(attr, next);
839
+ changed = true;
840
+ };
841
+
842
+ for (const el of document.querySelectorAll("[src],[srcset]")) {
843
+ // Tag names are upper-cased in HTML documents; the dash test is case-free.
844
+ if (!el.tagName.includes("-")) continue;
845
+ apply(el, "src");
846
+ apply(el, "srcset");
253
847
  }
254
848
 
255
849
  return changed;
256
850
  }
257
851
 
852
+ /**
853
+ * Returns a predicate that reports whether a root-relative path can be served
854
+ * from one of the configured asset-base local roots.
855
+ *
856
+ * Absolute URLs that were rewritten to root-relative virtual paths (see
857
+ * rewriteAbsoluteUrlsInDom) are not necessarily part of the static map — an
858
+ * `<img src>` is never collected by extractUrlsFromHtml — but the static server
859
+ * resolves any request path against an asset-base localBase, so those paths are
860
+ * servable and must be pointed at the server instead of being resolved against
861
+ * the file system location of the input document.
862
+ */
863
+ export function createAssetBasePathProbe(assetBases: AssetBaseMapping[]): (virtualPath: string) => boolean {
864
+ return (virtualPath: string): boolean => {
865
+ for (const ab of assetBases) {
866
+ const localPath = resolve(ab.localBase, virtualPath.replace(/^\//, ""));
867
+ if (existsSync(localPath)) {
868
+ log.trace("createAssetBasePathProbe: servable via asset-base", { virtualPath, localPath });
869
+ return true;
870
+ }
871
+ }
872
+ return false;
873
+ };
874
+ }
875
+
258
876
  // ---------------------------------------------------------------------------
259
877
  // String-level wrappers (kept for external callers / tests)
260
878
  // ---------------------------------------------------------------------------
@@ -295,15 +913,26 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
295
913
 
296
914
  const urls = new Set<string>();
297
915
 
298
- for (const el of document.querySelectorAll("link[href]")) {
299
- const href = el.getAttribute("href")?.trim();
300
- if (href) urls.add(href);
301
- }
916
+ // Every subresource is collected, not just <link> and <script>: an <img> that
917
+ // is not part of the static map can only be resolved by the fallback roots of
918
+ // the static server, and a missing one would fail silently.
919
+ for (const [selector, attr] of SUBRESOURCE_ATTR_SELECTORS) {
920
+ if (selector === "script[src]" && !includeScripts) continue;
921
+
922
+ for (const el of document.querySelectorAll(selector)) {
923
+ const raw = el.getAttribute(attr);
924
+ if (raw === null) continue;
925
+
926
+ if (attr !== "srcset") {
927
+ const url = raw.trim();
928
+ if (url) urls.add(url);
929
+ continue;
930
+ }
302
931
 
303
- if (includeScripts) {
304
- for (const el of document.querySelectorAll("script[src]")) {
305
- const src = el.getAttribute("src")?.trim();
306
- if (src) urls.add(src);
932
+ for (const candidate of raw.split(",")) {
933
+ const url = candidate.trim().split(/\s+/)[0] ?? "";
934
+ if (url) urls.add(url);
935
+ }
307
936
  }
308
937
  }
309
938
 
@@ -314,29 +943,15 @@ export function extractUrlsFromHtml(htmlPath: string, includeScripts = true, doc
314
943
  // Preview HTML builder
315
944
  // ---------------------------------------------------------------------------
316
945
 
317
- /**
318
- * Rewrites absolute external URLs to root-relative virtual paths and writes
319
- * the result as a sibling of the original input file so that
320
- * cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
321
- *
322
- * The output filename uses a non-dotfile prefix so Vite's static server
323
- * (which ignores dotfiles by default) can serve it correctly.
324
- *
325
- * Also derives extra static mounts from each assetBase so that secondary
326
- * assets referenced from CSS (fonts, images) are served by Vivliostyle's
327
- * own Vite server without needing Express.
328
- *
329
- * Returns:
330
- * - htmlPath – sibling file path, or inputAbs if no rewriting was needed
331
- * - extraStatic – virtual→local entries for assetBase roots to merge into
332
- * the static map passed to Vivliostyle
333
- * - cleanup – deletes the sibling file (no-op if inputAbs was returned)
334
- */
335
946
  export function buildPreviewHtml(
336
947
  inputAbs: string,
337
948
  assetBases: AssetBaseMapping[],
338
- dbg: Dbg
339
- ): { htmlPath: string; extraStatic: Record<string, string>; cleanup: () => void } {
949
+ options: HtmlRewriteOptions = {}
950
+ ): {
951
+ htmlPath: string;
952
+ extraStatic: Record<string, string>;
953
+ cleanup: () => void;
954
+ } {
340
955
  let content: string;
341
956
  try {
342
957
  content = readFileSync(inputAbs, "utf-8");
@@ -344,8 +959,6 @@ export function buildPreviewHtml(
344
959
  throw new Error(`Error reading HTML file: ${inputAbs}\n${String(err)}`);
345
960
  }
346
961
 
347
- // Derive extra static mounts for each assetBase root so secondary assets
348
- // referenced from CSS are also reachable through Vivliostyle's Vite server.
349
962
  const extraStatic: Record<string, string> = {};
350
963
  for (const ab of assetBases) {
351
964
  let virtualPrefix: string;
@@ -357,42 +970,55 @@ export function buildPreviewHtml(
357
970
  if (!virtualPrefix.endsWith("/")) virtualPrefix = `${virtualPrefix}/`;
358
971
  const mapKey = virtualPrefix === "/" ? "/" : virtualPrefix.slice(0, -1);
359
972
  if (Object.hasOwn(extraStatic, mapKey)) {
360
- console.warn(
973
+ log.warn(
361
974
  `[buildPreviewHtml] Duplicate assetBase virtual prefix "${mapKey}" — overwriting "${extraStatic[mapKey]}" with "${resolve(ab.localBase)}"`
362
975
  );
363
976
  }
364
977
  extraStatic[mapKey] = resolve(ab.localBase);
365
- dbg("buildPreviewHtml: assetBase extra static mount", {
366
- mapKey,
367
- local: ab.localBase
368
- });
978
+ log.trace("buildPreviewHtml: assetBase extra static mount", { mapKey, local: ab.localBase });
369
979
  }
370
980
 
371
981
  const dom = new JSDOM(content);
372
982
  const document = dom.window.document;
373
983
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
374
- if (changed) dbg("buildPreviewHtml: rewrote absolute URLs → virtual paths");
375
-
376
- if (!changed) {
377
- dbg("buildPreviewHtml: no URL rewrites needed, using original file");
984
+ if (changed) log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
985
+
986
+ // Same custom-element fix as the build path: the viewer mangles relative
987
+ // URLs on elements it does not understand. Only applied when the caller
988
+ // knows the document's directory on the server (see startPreview).
989
+ const customChanged =
990
+ options.documentBaseUrl === undefined || options.documentBaseUrl === null
991
+ ? false
992
+ : rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
993
+ if (customChanged) log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
994
+
995
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
996
+ if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
997
+
998
+ if (!changed && !customChanged && dropped.length === 0) {
999
+ log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
378
1000
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
379
1001
  }
380
1002
 
381
- const inputDir = dirname(inputAbs);
382
- const inputBase = inputAbs.slice(inputDir.length + 1);
383
- const outputBase = `_vivliostyle_preview_${inputBase}`;
384
- const htmlPath = join(inputDir, outputBase);
1003
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
1004
+ const htmlPath =
1005
+ dumpDir === null ? join(dirname(inputAbs), `_vivliostyle_preview_${basename(inputAbs)}`) : join(dumpDir, basename(inputAbs));
385
1006
 
1007
+ if (dumpDir !== null) mkdirSync(dumpDir, { recursive: true });
386
1008
  writeFileSync(htmlPath, dom.serialize(), "utf-8");
387
- dbg("buildPreviewHtml: wrote rewritten HTML alongside original", htmlPath);
388
- console.log(`[preview] Wrote rewritten HTML: ${htmlPath}`);
1009
+ log.trace("buildPreviewHtml: wrote rewritten HTML", htmlPath);
1010
+ log.info(`[preview] Wrote rewritten HTML: ${htmlPath}`);
389
1011
 
390
1012
  const cleanup = (): void => {
1013
+ if (dumpDir !== null) {
1014
+ log.trace("buildPreviewHtml: keeping dumped HTML", htmlPath);
1015
+ return;
1016
+ }
391
1017
  try {
392
1018
  rmSync(htmlPath, { force: true });
393
- dbg("buildPreviewHtml: removed rewritten HTML", htmlPath);
1019
+ log.trace("buildPreviewHtml: removed rewritten HTML", htmlPath);
394
1020
  } catch (err) {
395
- console.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
1021
+ log.warn(`[preview] Warning: could not remove ${htmlPath}\n${String(err)}`);
396
1022
  }
397
1023
  };
398
1024
 
@@ -403,18 +1029,12 @@ export function buildPreviewHtml(
403
1029
  // Build HTML builder
404
1030
  // ---------------------------------------------------------------------------
405
1031
 
406
- /**
407
- * Prepares the HTML for BUILD mode.
408
- * Both rewrite passes (absolute → virtual, virtual → absolute server URL)
409
- * are applied in a single DOM parse.
410
- * If nothing changed the original file path is returned with a no-op cleanup.
411
- */
412
1032
  export function prepareInputHtmlForBuild(
413
1033
  inputAbs: string,
414
1034
  assetBases: AssetBaseMapping[],
415
1035
  staticMap: Record<string, string>,
416
1036
  serverBaseUrl: string,
417
- dbg: Dbg
1037
+ options: HtmlRewriteOptions = {}
418
1038
  ): { vivliostyleInput: string; cleanup: () => void } {
419
1039
  let content: string;
420
1040
  try {
@@ -427,29 +1047,76 @@ export function prepareInputHtmlForBuild(
427
1047
  const document = dom.window.document;
428
1048
  const staticMapKeys = Object.keys(staticMap);
429
1049
 
430
- const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases);
431
- if (absChanged) dbg("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
1050
+ const absChanged = rewriteAbsoluteUrlsInDom(document, assetBases, options.fetchMissing === true);
1051
+ if (absChanged) log.trace("prepareInputHtmlForBuild: rewrote absolute URLs → virtual paths");
1052
+
1053
+ const probe = assetBases.length > 0 ? createAssetBasePathProbe(assetBases) : undefined;
1054
+ const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
1055
+ if (srvChanged) log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
1056
+
1057
+ const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
1058
+ const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
1059
+ if (customChanged) log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
1060
+
1061
+ const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
432
1062
 
433
- const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl);
434
- if (srvChanged) dbg("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
1063
+ const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
1064
+ if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
435
1065
 
436
- if (!absChanged && !srvChanged) {
437
- dbg("prepareInputHtmlForBuild: no changes, using original file");
1066
+ const unserved = collectUnservedVirtualPaths(document, staticMapKeys, probe);
1067
+ if (unserved.length > 0) reportUnservedVirtualPaths(unserved);
1068
+
1069
+ // The runtime script only matters for pages that run scripts; injecting it
1070
+ // into a plain document would rewrite the file for nothing.
1071
+ const hasScripts = document.querySelector("script") !== null;
1072
+ const wantsRuntime = (options.shimOrigin != null && hasScripts) || options.settle != null;
1073
+ if (wantsRuntime) {
1074
+ const origin = options.shimOrigin ?? serverBaseUrl;
1075
+ const documentBaseUrl = options.documentBaseUrl ?? `${origin}/`;
1076
+ // Only the PDF run expands `<details>`; the preview stays interactive.
1077
+ injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
1078
+ log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
1079
+ }
1080
+
1081
+ if (
1082
+ !absChanged &&
1083
+ !srvChanged &&
1084
+ !customChanged &&
1085
+ dropped.length === 0 &&
1086
+ gone.length === 0 &&
1087
+ options.settle == null &&
1088
+ !wantsRuntime
1089
+ ) {
1090
+ log.trace("prepareInputHtmlForBuild: no changes, using original file");
438
1091
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
439
1092
  }
440
1093
 
441
- const tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
442
- const tmpHtml = join(tmpDir, "index.html");
1094
+ const dumpDir = options.dumpDir ? resolve(options.dumpDir) : null;
1095
+ let tmpDir: string | null = null;
1096
+ let tmpHtml: string;
1097
+
1098
+ if (dumpDir !== null) {
1099
+ mkdirSync(dumpDir, { recursive: true });
1100
+ tmpHtml = join(dumpDir, basename(inputAbs));
1101
+ } else {
1102
+ tmpDir = mkdtempSync(join(tmpdir(), "vivliostyle-"));
1103
+ tmpHtml = join(tmpDir, "index.html");
1104
+ }
1105
+
443
1106
  writeFileSync(tmpHtml, dom.serialize(), "utf-8");
444
- console.log(`[html] Prepared input HTML → ${tmpHtml}`);
445
- dbg("prepareInputHtmlForBuild: written to temp file", tmpHtml);
1107
+ log.info(`[html] ${dumpDir === null ? "Prepared" : "Dumped"} input HTML → ${tmpHtml}`);
1108
+ log.trace("prepareInputHtmlForBuild: written", tmpHtml);
446
1109
 
447
1110
  const cleanup = (): void => {
1111
+ if (tmpDir === null) {
1112
+ log.trace("prepareInputHtmlForBuild: keeping dumped HTML", tmpHtml);
1113
+ return;
1114
+ }
448
1115
  try {
449
1116
  rmSync(tmpDir, { recursive: true, force: true });
450
- dbg("prepareInputHtmlForBuild: removed temp dir", tmpDir);
1117
+ log.trace("prepareInputHtmlForBuild: removed temp dir", tmpDir);
451
1118
  } catch (err) {
452
- console.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
1119
+ log.warn(`[html] Warning: could not remove temp dir ${tmpDir}\n${String(err)}`);
453
1120
  }
454
1121
  };
455
1122
 
@@ -487,27 +1154,6 @@ export function parseAssetBaseMapping(value: string): AssetBaseMapping {
487
1154
  return { urlBase: normalizeUrlBase(urlBase), localBase };
488
1155
  }
489
1156
 
490
- export function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): { virtualPath: string; localPath: string } | null {
491
- for (const mapping of assetBases) {
492
- if (!url.startsWith(mapping.urlBase)) continue;
493
-
494
- let cleanRelative: string;
495
- try {
496
- cleanRelative = new URL(url).pathname.slice(1);
497
- } catch {
498
- const noQuery = url.slice(mapping.urlBase.length).split("?")[0];
499
- cleanRelative = noQuery.split("#")[0];
500
- }
501
-
502
- if (!cleanRelative) return null;
503
-
504
- const virtualPath = posix.resolve("/", cleanRelative);
505
- const localPath = resolve(mapping.localBase, cleanRelative);
506
- return { virtualPath, localPath };
507
- }
508
- return null;
509
- }
510
-
511
1157
  // ---------------------------------------------------------------------------
512
1158
  // MappingResult + urlToStaticMapping
513
1159
  // ---------------------------------------------------------------------------
@@ -518,46 +1164,49 @@ export function urlToStaticMapping(
518
1164
  url: string,
519
1165
  htmlDir: string,
520
1166
  assetBases: AssetBaseMapping[],
521
- ignoredAssets: Set<string>,
522
- dbg: Dbg
1167
+ ignoredAssets: Set<string>
523
1168
  ): MappingResult {
524
1169
  const trimmed = url.trim();
525
1170
  if (!trimmed) return { kind: "skipped", url, reason: "empty URL" };
526
1171
  if (trimmed.startsWith("#")) return { kind: "skipped", url, reason: "fragment-only URL" };
527
1172
 
528
- const absoluteMapped = mapAbsoluteUrlToLocal(trimmed, assetBases);
529
- if (absoluteMapped) {
530
- if (shouldIgnoreVirtualPath(absoluteMapped.virtualPath, ignoredAssets)) {
531
- dbg("urlToStaticMapping: ignored (asset-base match)", {
532
- url,
533
- ...absoluteMapped
534
- });
1173
+ const assetMatch = mapAbsoluteUrlToLocal(trimmed, assetBases);
1174
+
1175
+ if (assetMatch.kind === "root-only") {
1176
+ return {
1177
+ kind: "skipped",
1178
+ url,
1179
+ reason: "URL matches an asset-base prefix but has no path component (root URL)"
1180
+ };
1181
+ }
1182
+
1183
+ if (assetMatch.kind === "mapped") {
1184
+ if (shouldIgnoreVirtualPath(assetMatch.virtualPath, ignoredAssets)) {
1185
+ log.trace("urlToStaticMapping: ignored (asset-base match)", { url, ...assetMatch });
535
1186
  return {
536
1187
  kind: "skipped",
537
1188
  url,
538
- reason: `matches --ignore-asset "${absoluteMapped.virtualPath}"`
1189
+ reason: `matches --ignore-asset "${assetMatch.virtualPath}"`
539
1190
  };
540
1191
  }
541
- if (!existsSync(absoluteMapped.localPath)) {
542
- console.warn(
1192
+ if (!existsSync(assetMatch.localPath)) {
1193
+ log.warn(
543
1194
  `[html] Warning: asset-base mapped path does not exist\n` +
544
1195
  ` url : ${url}\n` +
545
- ` virtual : ${absoluteMapped.virtualPath}\n` +
546
- ` local : ${absoluteMapped.localPath}`
1196
+ ` virtual : ${assetMatch.virtualPath}\n` +
1197
+ ` local : ${assetMatch.localPath}`
547
1198
  );
548
1199
  }
549
1200
  return {
550
1201
  kind: "mapped",
551
- mapping: `${absoluteMapped.virtualPath}:${absoluteMapped.localPath}`
1202
+ mapping: `${assetMatch.virtualPath}:${assetMatch.localPath}`
552
1203
  };
553
1204
  }
554
1205
 
1206
+ // assetMatch.kind === "no-match" — proceed to local / external handling
1207
+
555
1208
  if (trimmed.startsWith("//")) {
556
- return {
557
- kind: "skipped",
558
- url,
559
- reason: "protocol-relative external URL"
560
- };
1209
+ return { kind: "skipped", url, reason: "protocol-relative external URL" };
561
1210
  }
562
1211
 
563
1212
  if (/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(trimmed)) {
@@ -582,10 +1231,7 @@ export function urlToStaticMapping(
582
1231
  const virtualPath = cleanUrl.startsWith("/") ? posix.normalize(cleanUrl) : posix.resolve("/", posix.relative(htmlDir, localPath));
583
1232
 
584
1233
  if (shouldIgnoreVirtualPath(virtualPath, ignoredAssets)) {
585
- dbg("urlToStaticMapping: ignored (ignore-asset match)", {
586
- url,
587
- virtualPath
588
- });
1234
+ log.trace("urlToStaticMapping: ignored (ignore-asset match)", { url, virtualPath });
589
1235
  return {
590
1236
  kind: "skipped",
591
1237
  url,
@@ -594,7 +1240,7 @@ export function urlToStaticMapping(
594
1240
  }
595
1241
 
596
1242
  if (!existsSync(localPath)) {
597
- console.warn(
1243
+ log.warn(
598
1244
  `[html] Warning: referenced path does not exist\n` +
599
1245
  ` url : ${url}\n` +
600
1246
  ` virtual : ${virtualPath}\n` +
@@ -605,10 +1251,7 @@ export function urlToStaticMapping(
605
1251
  return { kind: "mapped", mapping: `${virtualPath}:${localPath}` };
606
1252
  }
607
1253
 
608
- export function parseStaticMapping(mapping: string): {
609
- virtual: string;
610
- local: string;
611
- } {
1254
+ export function parseStaticMapping(mapping: string): { virtual: string; local: string } {
612
1255
  if (!mapping.startsWith("/")) {
613
1256
  throw new Error(`Invalid --static mapping: "${mapping}"\nExpected format: /virtual/path:/local/path`);
614
1257
  }
@@ -631,7 +1274,7 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
631
1274
  for (const mapping of rawMappings) {
632
1275
  const { virtual, local } = parseStaticMapping(mapping);
633
1276
  if (Object.hasOwn(map, virtual)) {
634
- console.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
1277
+ log.warn(`[static] Warning: duplicate virtual path "${virtual}" — ` + `"${map[virtual]}" overwritten by "${local}"`);
635
1278
  }
636
1279
  map[virtual] = local;
637
1280
  }
@@ -642,15 +1285,35 @@ function buildStaticMap(rawMappings: string[]): Record<string, string> {
642
1285
  // Extra args parser
643
1286
  // ---------------------------------------------------------------------------
644
1287
 
1288
+ /**
1289
+ * Vivliostyle's config object uses camelCase keys (`viewerParam`, `userStyle`)
1290
+ * and typed values, so `--viewer-param` has to arrive as `viewerParam` and
1291
+ * `--timeout 60000` as the number 60000.
1292
+ */
1293
+ export function normalizeExtraKey(key: string): string {
1294
+ return key.replace(/-([a-z0-9])/g, (_match, char: string) => char.toUpperCase());
1295
+ }
1296
+
1297
+ export function coerceExtraValue(value: string): string | number | boolean {
1298
+ if (value === "true") return true;
1299
+ if (value === "false") return false;
1300
+ // Only plain integers, so that version-like strings ("1.9.2") stay strings.
1301
+ return /^-?\d+$/.test(value) ? Number.parseInt(value, 10) : value;
1302
+ }
1303
+
645
1304
  export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
646
1305
  const extraConfig: Record<string, unknown> = {};
647
1306
 
1307
+ const assign = (rawKey: string, rawValue: string | boolean): void => {
1308
+ extraConfig[normalizeExtraKey(rawKey)] = typeof rawValue === "boolean" ? rawValue : coerceExtraValue(rawValue);
1309
+ };
1310
+
648
1311
  for (let i = 0; i < extraArgs.length; i++) {
649
1312
  const arg = extraArgs[i];
650
1313
 
651
1314
  if (!arg.startsWith("--")) {
652
1315
  if (arg.startsWith("-")) {
653
- console.warn(
1316
+ log.warn(
654
1317
  `[extra-args] Warning: short flag "${arg}" after -- is not supported and will be ignored.\n` +
655
1318
  ` Use the long-form --flag equivalent instead.`
656
1319
  );
@@ -660,26 +1323,21 @@ export function parseExtraArgs(extraArgs: string[]): Record<string, unknown> {
660
1323
 
661
1324
  if (arg.includes("=")) {
662
1325
  const eqIdx = arg.indexOf("=");
663
- const key = arg.slice(2, eqIdx);
664
- const val = arg.slice(eqIdx + 1);
665
- extraConfig[key] = val === "true" ? true : val === "false" ? false : val;
1326
+ assign(arg.slice(2, eqIdx), arg.slice(eqIdx + 1));
666
1327
  continue;
667
1328
  }
668
1329
 
669
1330
  const key = arg.slice(2);
670
1331
  const next = extraArgs[i + 1];
671
1332
 
672
- if (next === "true") {
673
- extraConfig[key] = true;
1333
+ if (next === "true" || next === "false") {
1334
+ assign(key, next === "true");
674
1335
  i++;
675
- } else if (next === "false") {
676
- extraConfig[key] = false;
677
- i++;
678
- } else if (next && !next.startsWith("-")) {
679
- extraConfig[key] = next;
1336
+ } else if (next !== undefined && !next.startsWith("-")) {
1337
+ assign(key, next);
680
1338
  i++;
681
1339
  } else {
682
- extraConfig[key] = true;
1340
+ extraConfig[normalizeExtraKey(key)] = true;
683
1341
  }
684
1342
  }
685
1343
 
@@ -733,7 +1391,40 @@ function buildProgram(): Command {
733
1391
  .option("-o, --output <file>", "Output file path", "output.pdf")
734
1392
  .option("--title <title>", "Document title (overrides the one in the source)")
735
1393
  .option("--author <author>", "Document author")
736
- .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
1394
+ .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
1395
+ .option("--keywords <keywords>", "Document keywords, comma separated")
1396
+ .option(
1397
+ "--language <lang>",
1398
+ "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'"
1399
+ )
1400
+ .option(
1401
+ "--pdfa <level>",
1402
+ [
1403
+ "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
1404
+ "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
1405
+ "--icc-profile is given) and a file identifier are written.",
1406
+ "Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
1407
+ "This is a label only: the content is neither converted nor checked,",
1408
+ "so conformance of the content is the author's responsibility."
1409
+ ].join("\n ")
1410
+ )
1411
+ .option(
1412
+ "--pdfx <version>",
1413
+ [
1414
+ "Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
1415
+ "identification metadata as XMP, X-1a:2003 into the information",
1416
+ "dictionary. Both embed the --icc-profile as the OutputIntent.",
1417
+ "Same label-only semantics as --pdfa."
1418
+ ].join("\n ")
1419
+ )
1420
+ .option(
1421
+ "--icc-profile <path>",
1422
+ [
1423
+ "ICC profile embedded as the PDF output intent, e.g. a print",
1424
+ "provider's profile. Required for --pdfx; --pdfa defaults to the",
1425
+ "bundled sRGB profile."
1426
+ ].join("\n ")
1427
+ )
737
1428
  .option(
738
1429
  "--static <mapping>",
739
1430
  [
@@ -775,7 +1466,59 @@ function buildProgram(): Command {
775
1466
  (val: string, prev: string[]) => prev.concat(val),
776
1467
  []
777
1468
  )
778
- .option("--cwd <dir>", "Working directory for Vivliostyle (default: directory of --input)")
1469
+ .option(
1470
+ "--allow-remote",
1471
+ [
1472
+ "Keep subresource references that would be fetched from the network.",
1473
+ "By default every reference without a local file is removed from the",
1474
+ "input HTML so that nothing is loaded from the web.",
1475
+ "Hyperlinks (<a href>) are never touched. See also --fetch-missing."
1476
+ ].join("\n ")
1477
+ )
1478
+ .option(
1479
+ "--fetch-missing",
1480
+ [
1481
+ "Load references without a local file from the mapped origin instead of",
1482
+ "dropping them. The local server redirects missing files to the site",
1483
+ "origin, which also covers data that page scripts fetch by relative URL.",
1484
+ "Implies --allow-remote, so remote iframes and scripts are loaded too.",
1485
+ "Nothing is written to the input directory."
1486
+ ].join("\n ")
1487
+ )
1488
+ .option(
1489
+ "--wait-for-content [ms]",
1490
+ [
1491
+ "Delay pagination until the page's own async work finished: no request in",
1492
+ "flight, no wasm compiling, no long task running and the document height",
1493
+ "stable for --quiet-ms (default 400). Pages with <script> wait",
1494
+ "automatically (deadline 10000ms); 0 disables, larger values capped at",
1495
+ "25000ms."
1496
+ ].join("\n ")
1497
+ )
1498
+ .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
1499
+ .option(
1500
+ "--timeout <ms>",
1501
+ ["Give up on a page after <ms> (Vivliostyle default: 300000).", "Lower it for pages with embeds that never finish loading."].join(
1502
+ "\n "
1503
+ )
1504
+ )
1505
+ .option(
1506
+ "--pixel-ratio <n>",
1507
+ [
1508
+ "Render at n times the output resolution (Vivliostyle pixelRatio), e.g. 2.",
1509
+ "Layout and raster resolution increase while the page keeps its size,",
1510
+ "which removes pixel artifacts in canvas and WebGL content.",
1511
+ "Pages exposing window.__vivResize(factor) are also redrawn at n×",
1512
+ "backing pixels before printing, so output past 96dpi stays sharp."
1513
+ ].join("\n ")
1514
+ )
1515
+ .option(
1516
+ "--dump-html <dir>",
1517
+ [
1518
+ "Write the rewritten input HTML into <dir> and keep it, instead of a",
1519
+ "temporary file. Use it to inspect what Vivliostyle actually renders."
1520
+ ].join("\n ")
1521
+ )
779
1522
  .option("--format <format>", `Output format: ${validFormats.join(" | ")}`, "pdf")
780
1523
  .option("--log-level <level>", `Vivliostyle log level: ${validLogLevels.join(" | ")}`, "info")
781
1524
  .option("--mode <mode>", `Execution mode: ${validModes.join(" | ")}`, "build")
@@ -788,12 +1531,17 @@ function buildProgram(): Command {
788
1531
  "Notes:",
789
1532
  " • HTML input (.html/.htm) is detected automatically from the file extension.",
790
1533
  " • For HTML input, <link href> and <script src> are parsed and auto-mapped.",
1534
+ " • References without a local file are dropped (offline by default); use --allow-remote to keep them.",
791
1535
  " • Options after -- are forwarded verbatim to Vivliostyle.",
792
1536
  " • --debug sets --log-level to debug automatically.",
793
1537
  " • --preview and --mode preview are equivalent.",
794
- " • In preview mode Vivliostyle serves everything via its own Vite server.",
795
- " • In build mode an Express server is started to serve assets.",
796
- " • --asset-base localBase is also a fallback root for CSS-referenced assets."
1538
+ " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
1539
+ " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1540
+ " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
1541
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
1542
+ " • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
1543
+ " • values read from the document or the publication manifest; language falls",
1544
+ " • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
797
1545
  ].join("\n")
798
1546
  );
799
1547
  }
@@ -823,31 +1571,185 @@ export function parseArgs(argv: string[]): {
823
1571
  return { options: program.opts<CliOptions>(), extraArgs };
824
1572
  }
825
1573
 
1574
+ // ---------------------------------------------------------------------------
1575
+ // Build runner helper
1576
+ // ---------------------------------------------------------------------------
1577
+
1578
+ /** Metadata fields the CLI layer resolves before handing them to the renderer. */
1579
+ type MetadataFieldName = "title" | "author" | "subject" | "keywords" | "language";
1580
+
1581
+ /** ICC profile bytes with the name they get in the PDF's OutputIntent. */
1582
+ type IccProfile = { bytes: Uint8Array; name: string };
1583
+
1584
+ type RenderParams = {
1585
+ documentUrl: string;
1586
+ viewerPageUrl: string;
1587
+ outputAbs: string;
1588
+ metaFields: Partial<Record<MetadataFieldName, string>>;
1589
+ viewerParams: ViewerParams;
1590
+ timeoutMs?: number;
1591
+ waitForSettle: boolean;
1592
+ chromeExecutable?: string;
1593
+ canvasScale?: number;
1594
+ pdfLabel?: PdfLabel;
1595
+ iccProfile?: IccProfile;
1596
+ };
1597
+
1598
+ async function runRender(params: RenderParams): Promise<void> {
1599
+ const request = {
1600
+ documentUrl: params.documentUrl,
1601
+ viewerPageUrl: params.viewerPageUrl,
1602
+ output: params.outputAbs,
1603
+ viewerParams: params.viewerParams,
1604
+ timeoutMs: params.timeoutMs,
1605
+ waitForSettle: params.waitForSettle,
1606
+ ...(params.chromeExecutable === undefined ? {} : { chromeExecutable: params.chromeExecutable }),
1607
+ ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
1608
+ ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
1609
+ ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
1610
+ ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
1611
+ ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
1612
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
1613
+ ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
1614
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
1615
+ };
1616
+
1617
+ log.trace("renderPdf request", request);
1618
+ const result = await renderPdf(request);
1619
+ log.trace("renderPdf result", { pageCount: result.pageCount, bytes: result.bytes, settle: result.settle });
1620
+ log.info(`✓ Document created: ${result.output} (${result.pageCount} pages)`);
1621
+ }
1622
+
826
1623
  // ---------------------------------------------------------------------------
827
1624
  // Core execute
828
1625
  // ---------------------------------------------------------------------------
829
1626
 
830
- export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
831
- const debugEnabled = !!(options.debug || options.logLevel === "debug");
832
- const dbg = makeDbg(debugEnabled);
1627
+ /**
1628
+ * Log level for the wrapper's own output. `-d` wins over `--log-level`, which
1629
+ * is also forwarded to Vivliostyle unchanged.
1630
+ */
1631
+ function resolveInternalLogLevel(options: CliOptions): LogLevel {
1632
+ if (options.debug === true) return "debug";
1633
+ const level = options.logLevel as LogLevel;
1634
+ return validLogLevels.includes(level) ? level : "info";
1635
+ }
1636
+
1637
+ /**
1638
+ * `--wait-for-content [ms]`: hold the document's load event until the page's own
1639
+ * async work finished. Vivliostyle stops waiting for images after 30s, so the
1640
+ * hard limit is capped below that.
1641
+ */
1642
+ const MAX_SETTLE_DEADLINE_MS = 25_000;
1643
+
1644
+ /** Deadline for the automatic wait on script-driven pages (see below). */
1645
+ const AUTO_SETTLE_DEADLINE_MS = 10_000;
1646
+
1647
+ export function resolveSettleGate(options: CliOptions): SettleGate | null {
1648
+ const raw = options.waitForContent;
1649
+ if (raw === undefined || raw === false) return null;
1650
+ // Explicit 0 disables the wait — including the automatic one for pages
1651
+ // with scripts (see resolveEffectiveSettle).
1652
+ if (raw === "0") return null;
1653
+
1654
+ const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
1655
+ if (!Number.isFinite(requested) || requested <= 0) throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
1656
+
1657
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
1658
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0) throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
1659
+
1660
+ return {
1661
+ quietMs: quietRaw,
1662
+ deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
1663
+ };
1664
+ }
1665
+
1666
+ /**
1667
+ * Settle gate that actually applies: an explicit `--wait-for-content` wins;
1668
+ * otherwise pages that run scripts wait automatically (charts, wasm, WebGL
1669
+ * would otherwise race pagination), static pages don't wait at all.
1670
+ */
1671
+ export function resolveEffectiveSettle(options: CliOptions, hasScripts: boolean): { gate: SettleGate | null; autoArmed: boolean } {
1672
+ const explicit = resolveSettleGate(options);
1673
+ if (explicit !== null || options.waitForContent !== undefined) return { gate: explicit, autoArmed: false };
1674
+ if (!hasScripts) return { gate: null, autoArmed: false };
1675
+
1676
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
1677
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0) throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
1678
+ return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
1679
+ }
1680
+
1681
+ // ---------------------------------------------------------------------------
1682
+ // PDF metadata + standards labeling resolution
1683
+ // ---------------------------------------------------------------------------
1684
+
1685
+ function describePdfLabel(label: PdfLabel): string {
1686
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
1687
+ }
1688
+
1689
+ /**
1690
+ * `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
1691
+ */
1692
+ export function resolvePdfLabel(options: Pick<CliOptions, "pdfa" | "pdfx">): PdfLabel | undefined {
1693
+ if (options.pdfa !== undefined && options.pdfx !== undefined) {
1694
+ throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
1695
+ }
1696
+ if (options.pdfa !== undefined) return parsePdfaLabel(options.pdfa);
1697
+ if (options.pdfx !== undefined) return parsePdfxLabel(options.pdfx);
1698
+ return undefined;
1699
+ }
1700
+
1701
+ /**
1702
+ * `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
1703
+ * needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
1704
+ */
1705
+ export function resolveIccProfile(options: Pick<CliOptions, "iccProfile">, label: PdfLabel | undefined): IccProfile | undefined {
1706
+ if (options.iccProfile !== undefined) {
1707
+ const path = resolve(options.iccProfile);
1708
+ if (!existsSync(path)) throw new Error(`--icc-profile file does not exist: ${path}`);
1709
+ return { bytes: readFileSync(path), name: basename(path) };
1710
+ }
1711
+ if (label === undefined) return undefined;
1712
+ if (label.kind === "pdfx") {
1713
+ throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
1714
+ }
1715
+ return loadDefaultIccProfile();
1716
+ }
833
1717
 
834
- dbg("raw CLI options", options);
835
- dbg("extra args (after --)", extraArgs);
1718
+ /**
1719
+ * Document metadata for the PDF: the flags override values taken from the
1720
+ * input (HTML meta tags or a publication manifest); the language falls back
1721
+ * to "de" when no source provides one.
1722
+ */
1723
+ export function resolvePdfMetadata(
1724
+ options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language">,
1725
+ inputAbs: string,
1726
+ htmlMode: boolean
1727
+ ): DocumentMetadata & { language: string } {
1728
+ const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]) as DocumentMetadata;
1729
+ let derived: DocumentMetadata | undefined;
1730
+ if (htmlMode) {
1731
+ derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
1732
+ } else if (/\.json$/i.test(inputAbs)) {
1733
+ derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
1734
+ if (derived === undefined) log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
1735
+ }
1736
+ log.trace("metadata (derived)", derived);
1737
+ return resolveMetadata(cliFields, derived);
1738
+ }
1739
+
1740
+ export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
1741
+ log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
1742
+ log.trace("raw CLI options", options);
1743
+ log.trace("extra args (after --)", extraArgs);
836
1744
 
837
1745
  if (!options.input) throw new Error("Missing required option: --input");
838
1746
 
839
1747
  const inputAbs = resolve(options.input);
840
- dbg("resolved input", inputAbs);
1748
+ log.trace("resolved input", inputAbs);
841
1749
  if (!existsSync(inputAbs)) throw new Error(`Input file does not exist: ${inputAbs}`);
842
1750
 
843
- const cwd = options.cwd ? resolve(options.cwd) : dirname(inputAbs);
844
- if (!existsSync(cwd)) {
845
- throw new Error(`Working directory does not exist: ${cwd}`);
846
- }
847
- dbg("cwd", cwd);
848
-
849
1751
  const outputAbs = resolve(options.output);
850
- dbg("resolved output", outputAbs);
1752
+ log.trace("resolved output", outputAbs);
851
1753
 
852
1754
  if (!validFormats.includes(options.format as OutputFormat)) {
853
1755
  throw new Error(`Invalid format: "${options.format}". Allowed: ${validFormats.join(", ")}`);
@@ -858,215 +1760,326 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
858
1760
  throw new Error(`Invalid log level: "${options.logLevel}". Allowed: ${validLogLevels.join(", ")}`);
859
1761
  }
860
1762
  const logLevel: LogLevel = options.debug ? "debug" : (options.logLevel as LogLevel);
861
- dbg("logLevel", logLevel);
1763
+ log.trace("logLevel", logLevel);
862
1764
 
863
1765
  const mode = (options.preview ? "preview" : options.mode) as Mode;
864
1766
  if (!validModes.includes(mode)) {
865
1767
  throw new Error(`Invalid mode: "${mode}". Allowed: ${validModes.join(", ")}`);
866
1768
  }
867
- dbg("mode", mode);
1769
+ log.trace("mode", mode);
868
1770
 
869
1771
  const htmlMode = isHtmlInput(inputAbs);
870
- dbg("htmlMode (auto-detected)", htmlMode);
1772
+ log.trace("htmlMode (auto-detected)", htmlMode);
871
1773
 
872
1774
  if (!htmlMode) {
873
1775
  if (options.assetBase.length > 0) {
874
- console.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
1776
+ log.warn(`[warn] --asset-base has no effect for non-HTML input "${inputAbs}".`);
875
1777
  }
876
1778
  if (options.ignoreAsset.length > 0) {
877
- console.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
1779
+ log.warn(`[warn] --ignore-asset has no effect for non-HTML input "${inputAbs}".`);
878
1780
  }
879
1781
  }
880
1782
 
881
1783
  const assetBases = options.assetBase.map(parseAssetBaseMapping);
882
- dbg("parsed assetBases", assetBases);
1784
+ log.trace("parsed assetBases", assetBases);
883
1785
 
884
1786
  const ignoredAssets = new Set(options.ignoreAsset.map(normalizeIgnoreAssetPath));
885
- dbg("ignoredAssets", [...ignoredAssets]);
1787
+ log.trace("ignoredAssets", [...ignoredAssets]);
886
1788
 
887
1789
  // ── HTML-derived mappings ────────────────────────────────────────────────
888
1790
  const derivedMappings: string[] = [];
889
1791
 
890
1792
  if (htmlMode) {
891
1793
  const htmlDir = dirname(inputAbs);
892
- console.log(`[html] Analysing input as HTML: ${inputAbs}`);
1794
+ log.info(`[html] Analysing input as HTML: ${inputAbs}`);
893
1795
 
894
1796
  const includeScripts = mode === "preview" ? true : options.scripts;
895
1797
  const urls = extractUrlsFromHtml(inputAbs, includeScripts);
896
1798
 
897
1799
  if (urls.length === 0) {
898
- console.log("[html] No URLs found in input HTML");
1800
+ log.info("[html] No URLs found in input HTML");
899
1801
  } else {
900
- console.log(`[html] Found URLs (${urls.length}):`);
1802
+ log.info(`[html] Found URLs (${urls.length}):`);
901
1803
  }
902
1804
 
903
1805
  for (const url of urls) {
904
- const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets, dbg);
1806
+ const result = urlToStaticMapping(url, htmlDir, assetBases, ignoredAssets);
905
1807
  if (result.kind === "skipped") {
906
- console.log(` → Skipped (${result.reason}): ${url}`);
1808
+ log.info(` → Skipped (${result.reason}): ${url}`);
907
1809
  continue;
908
1810
  }
909
- console.log(` → Mapping: ${result.mapping}`);
1811
+ log.info(` → Mapping: ${result.mapping}`);
910
1812
  derivedMappings.push(result.mapping);
911
1813
  }
912
1814
 
913
- dbg("derived static mappings from HTML", derivedMappings);
1815
+ log.trace("derived static mappings from HTML", derivedMappings);
914
1816
  }
915
1817
 
916
1818
  // ── static map ────────────────────────────────────────────────────────────
917
1819
  const allStaticMappings = [...options.static, ...derivedMappings];
918
- dbg("all raw static mappings", allStaticMappings);
1820
+ log.trace("all raw static mappings", allStaticMappings);
919
1821
 
920
1822
  const staticMap = buildStaticMap(allStaticMappings);
921
- dbg("assembled staticMap", staticMap);
1823
+ log.trace("assembled staticMap", staticMap);
922
1824
 
923
- const hasStatic = Object.keys(staticMap).length > 0;
1825
+ // Mappings derived from the HTML have already been reported by
1826
+ // urlToStaticMapping; only explicit --static mounts are checked here.
1827
+ const derivedVirtualPaths = new Set(derivedMappings.map((mapping) => parseStaticMapping(mapping).virtual));
924
1828
 
925
1829
  for (const [virtualPath, localPath] of Object.entries(staticMap)) {
1830
+ if (derivedVirtualPaths.has(virtualPath)) continue;
926
1831
  if (!existsSync(localPath)) {
927
- console.warn(
1832
+ log.warn(
928
1833
  `[static] Warning: mapped local path does not exist\n` + ` virtual : ${virtualPath}\n` + ` local : ${localPath}`
929
1834
  );
930
1835
  }
931
1836
  }
932
1837
 
933
1838
  const extraConfig = parseExtraArgs(extraArgs);
934
- dbg("extraConfig (parsed from -- args)", extraConfig);
1839
+ log.trace("extraConfig (parsed from -- args)", extraConfig);
935
1840
 
936
- const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
1841
+ const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
1842
+ const pdfLabel = resolvePdfLabel(options);
1843
+ if (pdfLabel !== undefined) log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
1844
+ if (options.iccProfile !== undefined && pdfLabel === undefined) {
1845
+ log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
1846
+ }
1847
+ const iccProfile = resolveIccProfile(options, pdfLabel);
1848
+
1849
+ const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
1850
+ // The wait arms automatically on script-driven pages: without it, charts,
1851
+ // wasm and WebGL race pagination and the PDF ships half-painted content.
1852
+ const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
1853
+ const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
1854
+ if (autoArmed)
1855
+ log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
1856
+ const htmlOptions: HtmlRewriteOptions = {
1857
+ allowRemote: fetchMissing,
1858
+ fetchMissing,
1859
+ dumpDir: options.dumpHtml ?? null,
1860
+ settle,
1861
+ ...(typeof extraConfig.css === "string" ? { css: extraConfig.css } : {}),
1862
+ ...(typeof extraConfig.userStyle === "string" ? { userStyle: extraConfig.userStyle } : {})
1863
+ };
1864
+ log.trace("htmlRewriteOptions", htmlOptions);
937
1865
 
938
- console.log(`Starting Vivliostyle in mode: ${mode}`);
1866
+ if (options.timeout !== undefined) {
1867
+ const timeoutMs = Number.parseInt(options.timeout, 10);
1868
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error(`Invalid --timeout: "${options.timeout}"`);
1869
+ extraConfig.timeout = timeoutMs;
1870
+ log.info(`[render] timeout=${timeoutMs}ms`);
1871
+ }
939
1872
 
940
- // ── BUILD mode ─────────────────────────────────────────────────────────────
1873
+ if (options.pixelRatio !== undefined) {
1874
+ const ratio = Number.parseFloat(options.pixelRatio);
1875
+ if (!Number.isFinite(ratio) || ratio <= 0) throw new Error(`Invalid --pixel-ratio: "${options.pixelRatio}"`);
1876
+ const existing = typeof extraConfig.viewerParam === "string" ? extraConfig.viewerParam : "";
1877
+ extraConfig.viewerParam = existing === "" ? `pixelRatio=${ratio}` : `${existing}&pixelRatio=${ratio}`;
1878
+ log.info(`[render] pixelRatio=${ratio}`);
1879
+ }
1880
+ // Canvas/WebGL backing-store upscale follows --pixel-ratio: layout keeps its
1881
+ // CSS size while JS-painted pixels are redrawn at n× resolution so print
1882
+ // output past 96dpi stays sharp. Pages opt in via window.__vivResize(factor).
1883
+ const canvasScale =
1884
+ options.pixelRatio === undefined
1885
+ ? undefined
1886
+ : (() => {
1887
+ const ratio = Number.parseFloat(options.pixelRatio);
1888
+ return Number.isFinite(ratio) && ratio > 1 ? ratio : undefined;
1889
+ })();
1890
+
1891
+ log.info(`Starting Vivliostyle in mode: ${mode}`);
1892
+
1893
+ // ── BUILD mode ───────────────────────────────────────────────────────────────
941
1894
  if (mode === "build") {
942
- let vivliostyleInput = inputAbs;
943
- let htmlCleanup = (): void => undefined;
1895
+ if (format !== "pdf") throw new Error(`Unsupported format: ${format}. This renderer produces PDF only.`);
1896
+
1897
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
1898
+ const viewerLibDir = resolveViewerLibDir();
1899
+ log.trace("viewerLibDir", viewerLibDir);
1900
+ log.trace("sitePath", sitePath);
1901
+
1902
+ const entry: { localPath: string | null; sitePath: string } = { localPath: null, sitePath };
1903
+ const server = await startStaticServer({
1904
+ staticMap,
1905
+ assetBases,
1906
+ entry,
1907
+ fetchMissing: htmlOptions.fetchMissing === true,
1908
+ settle: htmlOptions.settle ?? null,
1909
+ viewerLibDir,
1910
+ viewerFilePath: join(viewerLibDir, "index.html"),
1911
+ log: (message) => log.info(message),
1912
+ onSettled: ({ reason, waitedMs, detail }) => {
1913
+ // Detail is logged in both branches: the deadline case is exactly
1914
+ // when canvas sizes and readiness matter most (e.g. slow WebGL).
1915
+ const line = `[wait] layout gate ${reason} after ${waitedMs}ms`;
1916
+ const withDetail = detail === undefined ? line : `${line} ${JSON.stringify(detail)}`;
1917
+ if (reason === "settled") log.info(withDetail);
1918
+ else log.warn(`${withDetail} — content may be incomplete`);
1919
+ }
1920
+ });
944
1921
 
945
- if (hasStatic || assetBases.length > 0) {
946
- const server = await startStaticServer(staticMap, assetBases, null, dbg);
1922
+ const htmlResource = { cleanup: (): void => undefined };
947
1923
 
948
- try {
949
- if (htmlMode) {
950
- ({ vivliostyleInput, cleanup: htmlCleanup } = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, dbg));
951
- }
952
-
953
- dbg("vivliostyleInput (final)", vivliostyleInput);
954
-
955
- const config: BuildConfig = {
956
- cwd,
957
- input: vivliostyleInput,
958
- output: [{ path: outputAbs, format }],
959
- ...metaFields,
960
- logLevel,
961
- ...(options.debug ? { debug: true } : {}),
962
- ...extraConfig
963
- };
964
- dbg("final BuildConfig", config);
965
- await build(config);
966
- console.log(`✓ Document created: ${outputAbs}`);
967
- } finally {
968
- htmlCleanup();
969
- server.close();
1924
+ try {
1925
+ // Remote references are only worth keeping if they still exist.
1926
+ const remoteReferences = collectRemoteReferences(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document).filter((url) =>
1927
+ referencesToProbe(url, assetBases)
1928
+ );
1929
+ const unavailableUrls = htmlOptions.fetchMissing === true ? await probeRemoteReferences(remoteReferences) : undefined;
1930
+ if (unavailableUrls !== undefined && unavailableUrls.size > 0) {
1931
+ log.warn(`[fetch] ${unavailableUrls.size} remote reference(s) are unavailable and will be dropped`);
970
1932
  }
971
- } else {
972
- dbg("vivliostyleInput (final)", vivliostyleInput);
973
-
974
- const config: BuildConfig = {
975
- cwd,
976
- input: vivliostyleInput,
977
- output: [{ path: outputAbs, format }],
978
- ...metaFields,
979
- logLevel,
980
- ...(options.debug ? { debug: true } : {}),
981
- ...extraConfig
982
- };
983
- dbg("final BuildConfig", config);
984
- await build(config);
985
- console.log(`✓ Document created: ${outputAbs}`);
1933
+
1934
+ const prepared = prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, server.baseUrl, {
1935
+ ...htmlOptions,
1936
+ unavailableUrls,
1937
+ shimOrigin: server.baseUrl,
1938
+ // The viewer is served next to the document, so scripts the page runs
1939
+ // resolve their relative URLs against the document's own directory.
1940
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
1941
+ });
1942
+ htmlResource.cleanup = prepared.cleanup;
1943
+ entry.localPath = prepared.vivliostyleInput;
1944
+
1945
+ const documentUrl = `${server.baseUrl}${sitePath}`;
1946
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
1947
+ log.info(`[html] Serving document at ${documentUrl}`);
1948
+
1949
+ await runRender({
1950
+ documentUrl,
1951
+ viewerPageUrl,
1952
+ outputAbs,
1953
+ metaFields,
1954
+ viewerParams: buildRenderViewerParams(extraConfig, htmlOptions),
1955
+ timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
1956
+ waitForSettle: htmlOptions.settle != null,
1957
+ chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1958
+ canvasScale,
1959
+ ...(pdfLabel === undefined ? {} : { pdfLabel }),
1960
+ ...(iccProfile === undefined ? {} : { iccProfile })
1961
+ });
1962
+ } finally {
1963
+ htmlResource.cleanup();
1964
+ await server.close();
986
1965
  }
1966
+ return;
1967
+ }
987
1968
 
988
- // ── PREVIEW mode ───────────────────────────────────────────────────────────
989
- } else {
990
- let previewInput = inputAbs;
991
- let htmlCleanup = (): void => undefined;
992
- const previewStaticMap: Record<string, string> = { ...staticMap };
993
-
994
- if (htmlMode) {
995
- const { htmlPath, extraStatic, cleanup } = buildPreviewHtml(inputAbs, assetBases, dbg);
996
- previewInput = htmlPath;
997
- htmlCleanup = cleanup;
998
-
999
- for (const [virtual, local] of Object.entries(extraStatic)) {
1000
- if (!Object.hasOwn(previewStaticMap, virtual)) {
1001
- previewStaticMap[virtual] = local;
1002
- console.log(`[preview] AssetBase static mount: ${virtual} → ${local}`);
1003
- } else {
1004
- dbg("preview: skipping assetBase mount shadowed by explicit --static", { virtual, local });
1005
- }
1006
- }
1969
+ // ── PREVIEW mode ─────────────────────────────────────────────────────────────
1970
+ {
1971
+ const preview = await startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraConfig);
1972
+ log.info(`[preview] ${preview.url}`);
1973
+ await openInBrowser(preview.url);
1974
+
1975
+ await new Promise<void>((resolvePromise) => {
1976
+ const stop = (): void => {
1977
+ process.off("SIGINT", stop);
1978
+ process.off("SIGTERM", stop);
1979
+ resolvePromise();
1980
+ };
1981
+ process.once("SIGINT", stop);
1982
+ process.once("SIGTERM", stop);
1983
+ });
1007
1984
 
1008
- if (htmlPath !== inputAbs) {
1009
- console.log(`[preview] Using rewritten HTML: ${htmlPath}`);
1010
- }
1011
- }
1985
+ await preview.close();
1986
+ }
1987
+ }
1012
1988
 
1013
- dbg("preview input (final)", previewInput);
1014
- dbg("previewStaticMap (final)", previewStaticMap);
1015
-
1016
- const hasPreviewStatic = Object.keys(previewStaticMap).length > 0;
1017
-
1018
- const previewCwd = dirname(previewInput);
1019
- dbg("previewCwd", previewCwd);
1020
-
1021
- const previewEntry = previewInput.slice(previewCwd.length + 1);
1022
- dbg("previewEntry (relative, for configData only)", previewEntry);
1023
-
1024
- const config: PreviewConfig = {
1025
- cwd: previewCwd,
1026
- input: previewInput,
1027
- logLevel,
1028
- enableStaticServe: true,
1029
- openViewer: true,
1030
- singleDoc: true,
1031
- ...(hasPreviewStatic
1032
- ? {
1033
- configData: [
1034
- {
1035
- entry: previewEntry,
1036
- ...metaFields,
1037
- static: previewStaticMap as StaticMap
1038
- }
1039
- ]
1040
- }
1041
- : {}),
1042
- ...(options.debug ? { debug: true } : {}),
1043
- ...extraConfig
1044
- };
1989
+ export type PreviewTarget = {
1990
+ /** URL of the viewer, showing the document. */
1991
+ url: string;
1992
+ /** URL the viewer loads the document from. */
1993
+ documentUrl: string;
1994
+ close: () => Promise<void>;
1995
+ };
1045
1996
 
1046
- dbg("final PreviewConfig", config);
1997
+ /**
1998
+ * Serves the rewritten document next to the viewer and returns the URL to open.
1999
+ *
2000
+ * The viewer page lives in the document's own directory, so the preview shows
2001
+ * exactly what the PDF render would lay out.
2002
+ */
2003
+ export async function startPreview(
2004
+ inputAbs: string,
2005
+ assetBases: AssetBaseMapping[],
2006
+ staticMap: StaticMap,
2007
+ htmlOptions: HtmlRewriteOptions,
2008
+ extraConfig: Record<string, unknown>
2009
+ ): Promise<PreviewTarget> {
2010
+ const sitePath = deriveSitePath(inputAbs, assetBases) ?? "/index.html";
2011
+ const viewerLibDir = resolveViewerLibDir();
2012
+ const entry: { localPath: string | null; sitePath: string } = { localPath: null, sitePath };
2013
+
2014
+ const server = await startStaticServer({
2015
+ staticMap,
2016
+ assetBases,
2017
+ entry,
2018
+ fetchMissing: htmlOptions.fetchMissing === true,
2019
+ viewerLibDir,
2020
+ viewerFilePath: join(viewerLibDir, "index.html"),
2021
+ log: (message) => log.info(message)
2022
+ });
1047
2023
 
1048
- const shutdown = (): void => {
1049
- htmlCleanup();
1050
- process.exit(0);
1051
- };
1052
- process.once("SIGINT", shutdown);
1053
- process.once("SIGTERM", shutdown);
2024
+ const prepared = buildPreviewHtml(inputAbs, assetBases, {
2025
+ ...htmlOptions,
2026
+ // The viewer is served next to the document, so custom-element URLs
2027
+ // resolve against the document's own directory (see siteDirectory below).
2028
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
2029
+ });
2030
+ entry.localPath = prepared.htmlPath;
2031
+
2032
+ const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
2033
+ const documentUrl = `${server.baseUrl}${sitePath}`;
2034
+ const url = buildViewerUrl(viewerPageUrl, {
2035
+ src: documentUrl,
2036
+ bookMode: false,
2037
+ renderAllPages: false,
2038
+ ...buildRenderViewerParams(extraConfig, htmlOptions)
2039
+ });
1054
2040
 
1055
- try {
1056
- await preview(config);
1057
- } catch (err) {
1058
- process.off("SIGINT", shutdown);
1059
- process.off("SIGTERM", shutdown);
1060
- htmlCleanup();
1061
- console.error("[preview] Full error:", err);
1062
- const message = err instanceof Error ? err.message : String(err);
1063
- throw new Error(`preview() failed:\n${message}`);
2041
+ return {
2042
+ url,
2043
+ documentUrl,
2044
+ close: async () => {
2045
+ prepared.cleanup();
2046
+ await server.close();
1064
2047
  }
2048
+ };
2049
+ }
2050
+
2051
+ /** Opens a URL in the user's browser; preview mode is a plain server. */
2052
+ async function openInBrowser(url: string): Promise<void> {
2053
+ const { spawn } = await import("node:child_process");
2054
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
2055
+ try {
2056
+ const child = spawn(command, [url], { stdio: "ignore", detached: true });
2057
+ child.unref();
2058
+ } catch (err) {
2059
+ log.warn(`[preview] Could not open a browser: ${String(err)}`);
2060
+ }
2061
+ }
1065
2062
 
1066
- process.off("SIGINT", shutdown);
1067
- process.off("SIGTERM", shutdown);
1068
- htmlCleanup();
2063
+ /**
2064
+ * Viewer parameters for the render: layout overrides from `--` plus the options
2065
+ * the wrapper owns (page size, output resolution, user stylesheet).
2066
+ */
2067
+ function buildRenderViewerParams(extraConfig: Record<string, unknown>, htmlOptions: HtmlRewriteOptions): ViewerParams {
2068
+ const params: ViewerParams = {};
2069
+
2070
+ if (typeof extraConfig.size === "string") params.size = extraConfig.size;
2071
+ if (typeof extraConfig.viewerParam === "string") {
2072
+ for (const pair of extraConfig.viewerParam.split("&")) {
2073
+ if (pair === "") continue;
2074
+ const eq = pair.indexOf("=");
2075
+ if (eq === -1) params[pair] = true;
2076
+ else params[pair.slice(0, eq)] = pair.slice(eq + 1);
2077
+ }
1069
2078
  }
2079
+ if (htmlOptions.css !== undefined) params.style = htmlOptions.css;
2080
+ if (htmlOptions.userStyle !== undefined) params.userStyle = htmlOptions.userStyle;
2081
+
2082
+ return params;
1070
2083
  }
1071
2084
 
1072
2085
  // ---------------------------------------------------------------------------
@@ -1097,7 +2110,7 @@ if (isDirectExecution()) {
1097
2110
  }
1098
2111
 
1099
2112
  execute(parsed.options, parsed.extraArgs).catch((err: unknown) => {
1100
- console.error(err instanceof Error ? err.message : String(err));
2113
+ log.error(err instanceof Error ? err.message : String(err));
1101
2114
  process.exit(1);
1102
2115
  });
1103
2116
  }