@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,16 @@ import log, { type LogLevelDesc } from "loglevel";
13
13
  import { VIEWER_PAGE_NAME, startStaticServer, type AssetBaseMapping, type SettleGate, type StaticMap } from "./server.js";
14
14
  import { buildViewerUrl, renderPdf, type ViewerParams } from "./render/pdf.js";
15
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";
16
26
 
17
27
  type OutputFormat = "pdf";
18
28
  type LogLevel = "silent" | "info" | "verbose" | "debug";
@@ -23,7 +33,17 @@ type CliOptions = {
23
33
  output: string;
24
34
  title?: string;
25
35
  author?: string;
36
+ subject?: string;
37
+ keywords?: string;
26
38
  language?: string;
39
+ created?: string;
40
+ modified?: string;
41
+ pdfa?: string;
42
+ pdfx?: string;
43
+ iccProfile?: string;
44
+ /** Commander's negatable form of --no-validate. */
45
+ validate?: boolean;
46
+ verapdf?: boolean;
27
47
  static: string[];
28
48
  scripts: boolean;
29
49
  format: string;
@@ -194,7 +214,38 @@ export function buildRuntimeScript(options: RuntimeScriptOptions): string {
194
214
  return `(function(){
195
215
  var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
196
216
  var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
197
- var pending=0,frames=0,last=0,mutations=0,done=false;
217
+ var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
218
+ // Force preserveDrawingBuffer on every WebGL context the page creates:
219
+ // print-to-PDF otherwise captures the cleared drawing buffer and WebGL
220
+ // content ships empty, even though the browser shows it composited.
221
+ try {
222
+ var origGetContext = HTMLCanvasElement.prototype.getContext;
223
+ HTMLCanvasElement.prototype.getContext = function (type, attrs) {
224
+ if (typeof type === "string" && /^webgl/.test(type)) {
225
+ attrs = Object.assign({}, attrs || {});
226
+ attrs.preserveDrawingBuffer = true;
227
+ return origGetContext.call(this, type, attrs);
228
+ }
229
+ return origGetContext.call(this, type, attrs);
230
+ };
231
+ } catch (e) {}
232
+ // Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
233
+ // waiting for it on the document (framework bootstraps, print scripts, asset
234
+ // bootstraps) never run. Re-dispatch the lifecycle events properly once
235
+ // loading finished.
236
+ try {
237
+ var redeliver = function () {
238
+ setTimeout(function () {
239
+ try {
240
+ document.dispatchEvent(new Event("DOMContentLoaded"));
241
+ window.dispatchEvent(new Event("DOMContentLoaded"));
242
+ window.dispatchEvent(new Event("load"));
243
+ } catch (e) {}
244
+ }, 0);
245
+ };
246
+ if (document.readyState === "complete") redeliver();
247
+ else window.addEventListener("load", redeliver, { once: true });
248
+ } catch (e) {}
198
249
  var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
199
250
 
200
251
  // Root-relative URLs resolve against the site root, document-relative ones
@@ -228,7 +279,7 @@ function signal(why){
228
279
  var at=Math.round(performance.now());
229
280
  state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
230
281
  var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
231
- "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
282
+ "&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
232
283
  "&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
233
284
  "&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
234
285
  try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
@@ -258,14 +309,39 @@ if(of){window.fetch=function(input,init){
258
309
  else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
259
310
  }catch(e){}
260
311
  pending++;last=performance.now();
261
- return of.call(this,input,init).then(function(v){pending--;last=performance.now();return v;},
262
- function(e){pending--;last=performance.now();throw e;});};}
312
+ var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
313
+ return of.call(this,input,init).then(function(v){pending--;last=performance.now();
314
+ try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
315
+ return v;},
316
+ function(e){pending--;last=performance.now();
317
+ try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
318
+ throw e;});};}
263
319
  var XHR=window.XMLHttpRequest;
264
320
  if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
265
- XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
321
+ XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
266
322
  XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
267
- this.addEventListener("loadend",function(){pending--;last=performance.now();});}
323
+ this.addEventListener("loadend",function(){pending--;last=performance.now();
324
+ try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
268
325
  return send.apply(this,arguments);};}
326
+ // WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
327
+ // alone would report idle mid-compile. Hold pending through it.
328
+ var WA=window.WebAssembly;
329
+ if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
330
+ var orig=WA[n];if(typeof orig!=="function")return;
331
+ WA[n]=function(){pending++;last=performance.now();
332
+ var result;
333
+ try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
334
+ if(result&&typeof result.then==="function"){
335
+ return result.then(function(v){pending--;last=performance.now();return v;},
336
+ function(e){pending--;last=performance.now();throw e;});
337
+ }
338
+ pending--;last=performance.now();return result;};});}
339
+ // Heavy main-thread work (script eval, wasm compile, shader/layout jank)
340
+ // emits no network or DOM signal; long tasks keep the quiet window open.
341
+ try{var PO=window.PerformanceObserver;
342
+ if(typeof PO==="function"){new PO(function(list){
343
+ var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
344
+ }).observe({entryTypes:["longtask"]});}}catch(e){}
269
345
  ["Image","Audio"].forEach(function(n){
270
346
  var Orig=window[n];if(!Orig)return;
271
347
  var Wrapped=function(u){return new Orig(fix(u));};
@@ -290,6 +366,8 @@ last=performance.now();
290
366
  ${expandDetailsTick}
291
367
  var now=performance.now();
292
368
  if(now>=DEADLINE){signal("deadline");return;}
369
+ // Webfonts loading late would leave canvas text painted with fallbacks.
370
+ try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
293
371
  // Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
294
372
  // painted instead of making the gate guess from network quietness. Shader
295
373
  // compile and tile decode finish after the last fetch, so readiness wins.
@@ -712,6 +790,70 @@ export function rewriteVirtualPathsToServerInDom(
712
790
  return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
713
791
  }
714
792
 
793
+ /**
794
+ * Resolves relative URLs on custom elements (`<a-asset-item>`,
795
+ * `<model-viewer>`, and any tag name containing a dash) to absolute server
796
+ * URLs.
797
+ *
798
+ * Vivliostyle resolves the subresource attributes it knows (`<img>`,
799
+ * `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
800
+ * understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
801
+ * `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
802
+ * the viewer those instead. Standard elements are left alone (the viewer and
803
+ * the runtime URL shim already handle them); only dash-tagged elements, whose
804
+ * attributes the viewer cannot be trusted with, are rewritten.
805
+ */
806
+ export function rewriteCustomElementUrlsInDom(document: Document, documentDirUrl: string): boolean {
807
+ let changed = false;
808
+
809
+ const resolveOne = (url: string): string => {
810
+ const current = url.trim();
811
+ if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//")) return current;
812
+ // Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
813
+ // are covered by the server-URL rewrite.
814
+ if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/")) return current;
815
+ try {
816
+ const resolved = new URL(current, documentDirUrl).href;
817
+ return resolved === current ? current : resolved;
818
+ } catch {
819
+ return current;
820
+ }
821
+ };
822
+
823
+ const apply = (el: Element, attr: "src" | "srcset"): void => {
824
+ const raw = el.getAttribute(attr);
825
+ if (raw === null) return;
826
+ if (attr === "src") {
827
+ const next = resolveOne(raw);
828
+ if (next === raw.trim() || next === raw) return;
829
+ el.setAttribute(attr, next);
830
+ changed = true;
831
+ return;
832
+ }
833
+ const kept = raw
834
+ .split(",")
835
+ .map((candidate) => candidate.trim())
836
+ .filter(Boolean)
837
+ .map((candidate) => {
838
+ const [url, ...descriptor] = candidate.split(/\s+/);
839
+ return [resolveOne(url), ...descriptor].join(" ");
840
+ });
841
+ const next = kept.join(", ");
842
+ if (next === raw) return;
843
+ el.setAttribute(attr, next);
844
+ changed = true;
845
+ };
846
+
847
+ for (const el of document.querySelectorAll("[src],[srcset]")) {
848
+ // Tag names are upper-cased in HTML documents; the dash test is case-free.
849
+ if (!el.tagName.includes("-")) continue;
850
+ apply(el, "src");
851
+ apply(el, "srcset");
852
+ }
853
+
854
+ return changed;
855
+ }
856
+
715
857
  /**
716
858
  * Returns a predicate that reports whether a root-relative path can be served
717
859
  * from one of the configured asset-base local roots.
@@ -846,10 +988,19 @@ export function buildPreviewHtml(
846
988
  const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
847
989
  if (changed) log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
848
990
 
991
+ // Same custom-element fix as the build path: the viewer mangles relative
992
+ // URLs on elements it does not understand. Only applied when the caller
993
+ // knows the document's directory on the server (see startPreview).
994
+ const customChanged =
995
+ options.documentBaseUrl === undefined || options.documentBaseUrl === null
996
+ ? false
997
+ : rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
998
+ if (customChanged) log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
999
+
849
1000
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
850
1001
  if (dropped.length > 0) reportDroppedRemoteRefs(dropped);
851
1002
 
852
- if (!changed && dropped.length === 0) {
1003
+ if (!changed && !customChanged && dropped.length === 0) {
853
1004
  log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
854
1005
  return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
855
1006
  }
@@ -908,6 +1059,10 @@ export function prepareInputHtmlForBuild(
908
1059
  const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
909
1060
  if (srvChanged) log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
910
1061
 
1062
+ const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
1063
+ const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
1064
+ if (customChanged) log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
1065
+
911
1066
  const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
912
1067
 
913
1068
  const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
@@ -928,7 +1083,15 @@ export function prepareInputHtmlForBuild(
928
1083
  log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
929
1084
  }
930
1085
 
931
- if (!absChanged && !srvChanged && dropped.length === 0 && gone.length === 0 && options.settle == null && !wantsRuntime) {
1086
+ if (
1087
+ !absChanged &&
1088
+ !srvChanged &&
1089
+ !customChanged &&
1090
+ dropped.length === 0 &&
1091
+ gone.length === 0 &&
1092
+ options.settle == null &&
1093
+ !wantsRuntime
1094
+ ) {
932
1095
  log.trace("prepareInputHtmlForBuild: no changes, using original file");
933
1096
  return { vivliostyleInput: inputAbs, cleanup: () => undefined };
934
1097
  }
@@ -1233,7 +1396,60 @@ function buildProgram(): Command {
1233
1396
  .option("-o, --output <file>", "Output file path", "output.pdf")
1234
1397
  .option("--title <title>", "Document title (overrides the one in the source)")
1235
1398
  .option("--author <author>", "Document author")
1236
- .option("--language <lang>", "Document language tag (e.g. en, de, ja)", "de")
1399
+ .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
1400
+ .option("--keywords <keywords>", "Document keywords, comma separated")
1401
+ .option(
1402
+ "--language <lang>",
1403
+ "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'"
1404
+ )
1405
+ .option(
1406
+ "--created <date>",
1407
+ "Document creation date (ISO 8601, e.g. 2024-11-18T00:00:00+01:00). Taken from the document's dcterms.created meta tag when omitted"
1408
+ )
1409
+ .option("--modified <date>", "Document modification date (ISO 8601). Taken from the document's dcterms.modified meta tag when omitted")
1410
+ .option(
1411
+ "--pdfa <level>",
1412
+ [
1413
+ "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
1414
+ "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
1415
+ "--icc-profile is given) and a file identifier are written.",
1416
+ "Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
1417
+ "This is a label only: the content is neither converted nor checked,",
1418
+ "so conformance of the content is the author's responsibility."
1419
+ ].join("\n ")
1420
+ )
1421
+ .option(
1422
+ "--pdfx <version>",
1423
+ [
1424
+ "Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
1425
+ "identification metadata as XMP, X-1a:2003 into the information",
1426
+ "dictionary. Both embed the --icc-profile as the OutputIntent.",
1427
+ "Same label-only semantics as --pdfa."
1428
+ ].join("\n ")
1429
+ )
1430
+ .option(
1431
+ "--no-validate",
1432
+ [
1433
+ "Skip the built-in compliance checks run for --pdfa/--pdfx output:",
1434
+ "PDF version of the labeled part, XMP identification, OutputIntent,",
1435
+ "file identifier, embedded fonts and the absence of JavaScript."
1436
+ ].join("\n ")
1437
+ )
1438
+ .option(
1439
+ "--verapdf",
1440
+ [
1441
+ "Additionally run the verapdf binary (must be on the PATH) against the",
1442
+ "output and fail the build on full ISO rule-set violations."
1443
+ ].join("\n ")
1444
+ )
1445
+ .option(
1446
+ "--icc-profile <path>",
1447
+ [
1448
+ "ICC profile embedded as the PDF output intent, e.g. a print",
1449
+ "provider's profile. Required for --pdfx; --pdfa defaults to the",
1450
+ "bundled sRGB profile."
1451
+ ].join("\n ")
1452
+ )
1237
1453
  .option(
1238
1454
  "--static <mapping>",
1239
1455
  [
@@ -1298,8 +1514,10 @@ function buildProgram(): Command {
1298
1514
  "--wait-for-content [ms]",
1299
1515
  [
1300
1516
  "Delay pagination until the page's own async work finished: no request in",
1301
- "flight and the document height stable for --quiet-ms (default 400).",
1302
- "Without [ms] the hard limit of 25000ms applies; larger values are capped."
1517
+ "flight, no wasm compiling, no long task running and the document height",
1518
+ "stable for --quiet-ms (default 400). Pages with <script> wait",
1519
+ "automatically (deadline 10000ms); 0 disables, larger values capped at",
1520
+ "25000ms."
1303
1521
  ].join("\n ")
1304
1522
  )
1305
1523
  .option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
@@ -1345,7 +1563,12 @@ function buildProgram(): Command {
1345
1563
  " • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
1346
1564
  " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1347
1565
  " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
1348
- " • --asset-base localBase is also a fallback root for CSS-referenced assets."
1566
+ " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
1567
+ " • PDF metadata (--title/--author/--subject/--keywords/--language/--created/--modified)",
1568
+ " • values read from the document or the publication manifest; language falls",
1569
+ " • back to 'de'. --pdfa/--pdfx label the output; the built-in validation",
1570
+ " • checks the practical subset (--no-validate skips it) and --verapdf runs",
1571
+ " • the full ISO rule set through the verapdf binary."
1349
1572
  ].join("\n")
1350
1573
  );
1351
1574
  }
@@ -1379,16 +1602,28 @@ export function parseArgs(argv: string[]): {
1379
1602
  // Build runner helper
1380
1603
  // ---------------------------------------------------------------------------
1381
1604
 
1605
+ /** Metadata fields the CLI layer resolves before handing them to the renderer. */
1606
+ type MetadataFieldName = "title" | "author" | "subject" | "keywords" | "language" | "created" | "modified";
1607
+
1608
+ /** ICC profile bytes with the name they get in the PDF's OutputIntent. */
1609
+ type IccProfile = { bytes: Uint8Array; name: string };
1610
+
1382
1611
  type RenderParams = {
1383
1612
  documentUrl: string;
1384
1613
  viewerPageUrl: string;
1385
1614
  outputAbs: string;
1386
- metaFields: Partial<Record<"title" | "author" | "language", string>>;
1615
+ metaFields: Partial<Record<MetadataFieldName, string>>;
1387
1616
  viewerParams: ViewerParams;
1388
1617
  timeoutMs?: number;
1389
1618
  waitForSettle: boolean;
1390
1619
  chromeExecutable?: string;
1391
1620
  canvasScale?: number;
1621
+ pdfLabel?: PdfLabel;
1622
+ iccProfile?: IccProfile;
1623
+ /** Run the built-in compliance checks for the label (default: on). */
1624
+ validate: boolean;
1625
+ /** Additionally run the verapdf binary against the output. */
1626
+ verapdf?: boolean;
1392
1627
  };
1393
1628
 
1394
1629
  async function runRender(params: RenderParams): Promise<void> {
@@ -1403,7 +1638,15 @@ async function runRender(params: RenderParams): Promise<void> {
1403
1638
  ...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
1404
1639
  ...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
1405
1640
  ...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
1406
- ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language })
1641
+ ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
1642
+ ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
1643
+ ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
1644
+ ...(params.metaFields.created === undefined ? {} : { created: params.metaFields.created }),
1645
+ ...(params.metaFields.modified === undefined ? {} : { modified: params.metaFields.modified }),
1646
+ ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
1647
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name }),
1648
+ validate: params.validate,
1649
+ ...(params.verapdf === undefined ? {} : { verapdf: params.verapdf })
1407
1650
  };
1408
1651
 
1409
1652
  log.trace("renderPdf request", request);
@@ -1433,9 +1676,15 @@ function resolveInternalLogLevel(options: CliOptions): LogLevel {
1433
1676
  */
1434
1677
  const MAX_SETTLE_DEADLINE_MS = 25_000;
1435
1678
 
1679
+ /** Deadline for the automatic wait on script-driven pages (see below). */
1680
+ const AUTO_SETTLE_DEADLINE_MS = 10_000;
1681
+
1436
1682
  export function resolveSettleGate(options: CliOptions): SettleGate | null {
1437
1683
  const raw = options.waitForContent;
1438
1684
  if (raw === undefined || raw === false) return null;
1685
+ // Explicit 0 disables the wait — including the automatic one for pages
1686
+ // with scripts (see resolveEffectiveSettle).
1687
+ if (raw === "0") return null;
1439
1688
 
1440
1689
  const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
1441
1690
  if (!Number.isFinite(requested) || requested <= 0) throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
@@ -1449,6 +1698,88 @@ export function resolveSettleGate(options: CliOptions): SettleGate | null {
1449
1698
  };
1450
1699
  }
1451
1700
 
1701
+ /**
1702
+ * Settle gate that actually applies: an explicit `--wait-for-content` wins;
1703
+ * otherwise pages that run scripts wait automatically (charts, wasm, WebGL
1704
+ * would otherwise race pagination), static pages don't wait at all.
1705
+ */
1706
+ export function resolveEffectiveSettle(options: CliOptions, hasScripts: boolean): { gate: SettleGate | null; autoArmed: boolean } {
1707
+ const explicit = resolveSettleGate(options);
1708
+ if (explicit !== null || options.waitForContent !== undefined) return { gate: explicit, autoArmed: false };
1709
+ if (!hasScripts) return { gate: null, autoArmed: false };
1710
+
1711
+ const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
1712
+ if (!Number.isFinite(quietRaw) || quietRaw <= 0) throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
1713
+ return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
1714
+ }
1715
+
1716
+ // ---------------------------------------------------------------------------
1717
+ // PDF metadata + standards labeling resolution
1718
+ // ---------------------------------------------------------------------------
1719
+
1720
+ function describePdfLabel(label: PdfLabel): string {
1721
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
1722
+ }
1723
+
1724
+ /**
1725
+ * `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
1726
+ */
1727
+ export function resolvePdfLabel(options: Pick<CliOptions, "pdfa" | "pdfx">): PdfLabel | undefined {
1728
+ if (options.pdfa !== undefined && options.pdfx !== undefined) {
1729
+ throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
1730
+ }
1731
+ if (options.pdfa !== undefined) return parsePdfaLabel(options.pdfa);
1732
+ if (options.pdfx !== undefined) return parsePdfxLabel(options.pdfx);
1733
+ return undefined;
1734
+ }
1735
+
1736
+ /**
1737
+ * `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
1738
+ * needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
1739
+ */
1740
+ export function resolveIccProfile(options: Pick<CliOptions, "iccProfile">, label: PdfLabel | undefined): IccProfile | undefined {
1741
+ if (options.iccProfile !== undefined) {
1742
+ const path = resolve(options.iccProfile);
1743
+ if (!existsSync(path)) throw new Error(`--icc-profile file does not exist: ${path}`);
1744
+ return { bytes: readFileSync(path), name: basename(path) };
1745
+ }
1746
+ if (label === undefined) return undefined;
1747
+ if (label.kind === "pdfx") {
1748
+ throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
1749
+ }
1750
+ return loadDefaultIccProfile();
1751
+ }
1752
+
1753
+ /**
1754
+ * Document metadata for the PDF: the flags override values taken from the
1755
+ * input (HTML meta tags or a publication manifest); the language falls back
1756
+ * to "de" when no source provides one.
1757
+ */
1758
+ export function resolvePdfMetadata(
1759
+ options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language" | "created" | "modified">,
1760
+ inputAbs: string,
1761
+ htmlMode: boolean
1762
+ ): DocumentMetadata & { language: string } {
1763
+ const cliFields = pickDefinedStrings(options, [
1764
+ "title",
1765
+ "author",
1766
+ "subject",
1767
+ "keywords",
1768
+ "language",
1769
+ "created",
1770
+ "modified"
1771
+ ]) as DocumentMetadata;
1772
+ let derived: DocumentMetadata | undefined;
1773
+ if (htmlMode) {
1774
+ derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
1775
+ } else if (/\.json$/i.test(inputAbs)) {
1776
+ derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
1777
+ if (derived === undefined) log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
1778
+ }
1779
+ log.trace("metadata (derived)", derived);
1780
+ return resolveMetadata(cliFields, derived);
1781
+ }
1782
+
1452
1783
  export async function execute(options: CliOptions, extraArgs: string[] = []): Promise<void> {
1453
1784
  log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
1454
1785
  log.trace("raw CLI options", options);
@@ -1550,10 +1881,21 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
1550
1881
  const extraConfig = parseExtraArgs(extraArgs);
1551
1882
  log.trace("extraConfig (parsed from -- args)", extraConfig);
1552
1883
 
1553
- const metaFields = pickDefinedStrings(options, ["title", "author", "language"]);
1884
+ const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
1885
+ const pdfLabel = resolvePdfLabel(options);
1886
+ if (pdfLabel !== undefined) log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
1887
+ if (options.iccProfile !== undefined && pdfLabel === undefined) {
1888
+ log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
1889
+ }
1890
+ const iccProfile = resolveIccProfile(options, pdfLabel);
1554
1891
 
1555
1892
  const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
1556
- const settle = resolveSettleGate(options);
1893
+ // The wait arms automatically on script-driven pages: without it, charts,
1894
+ // wasm and WebGL race pagination and the PDF ships half-painted content.
1895
+ const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
1896
+ const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
1897
+ if (autoArmed)
1898
+ log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
1557
1899
  const htmlOptions: HtmlRewriteOptions = {
1558
1900
  allowRemote: fetchMissing,
1559
1901
  fetchMissing,
@@ -1656,7 +1998,11 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
1656
1998
  timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
1657
1999
  waitForSettle: htmlOptions.settle != null,
1658
2000
  chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1659
- canvasScale
2001
+ canvasScale,
2002
+ ...(pdfLabel === undefined ? {} : { pdfLabel }),
2003
+ ...(iccProfile === undefined ? {} : { iccProfile }),
2004
+ validate: options.validate !== false,
2005
+ ...(options.verapdf === true ? { verapdf: true } : {})
1660
2006
  });
1661
2007
  } finally {
1662
2008
  htmlResource.cleanup();
@@ -1720,7 +2066,12 @@ export async function startPreview(
1720
2066
  log: (message) => log.info(message)
1721
2067
  });
1722
2068
 
1723
- const prepared = buildPreviewHtml(inputAbs, assetBases, htmlOptions);
2069
+ const prepared = buildPreviewHtml(inputAbs, assetBases, {
2070
+ ...htmlOptions,
2071
+ // The viewer is served next to the document, so custom-element URLs
2072
+ // resolve against the document's own directory (see siteDirectory below).
2073
+ documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
2074
+ });
1724
2075
  entry.localPath = prepared.htmlPath;
1725
2076
 
1726
2077
  const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;