@projektemacher/vivliostyle-batch-cli 0.2.0 → 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.
- package/README.md +47 -26
- package/dist/index.d.ts +99 -1
- package/dist/vivliostyle-batch-cli.js +990 -46
- package/package.json +23 -19
- package/scripts/convert-docs-pdf.mjs +520 -0
- package/src/metadata.ts +154 -0
- package/src/render/pdf-postprocess.ts +293 -0
- package/src/render/pdf.ts +221 -23
- package/src/render/srgb.icc +0 -0
- package/src/render/xmp.ts +183 -0
- package/src/server.ts +18 -1
- package/src/vivliostyle-cli.ts +324 -18
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import { resolve, join, dirname, posix, relative, isAbsolute, sep
|
|
2
|
+
import { resolve, join, dirname, posix, basename, relative, isAbsolute, sep } from 'node:path';
|
|
3
3
|
import { readFileSync, statSync, existsSync, readdirSync, mkdirSync, writeFileSync, realpathSync, mkdtempSync, rmSync } from 'node:fs';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import { platform, homedir, tmpdir } from 'node:os';
|
|
@@ -9,6 +9,8 @@ import { createServer } from 'node:http';
|
|
|
9
9
|
import { lookup } from 'mime-types';
|
|
10
10
|
import puppeteer from 'puppeteer-core';
|
|
11
11
|
import { PDFDocument } from 'pdf-lib';
|
|
12
|
+
import { randomUUID, randomBytes } from 'node:crypto';
|
|
13
|
+
import * as mupdf from 'mupdf';
|
|
12
14
|
import { createRequire } from 'node:module';
|
|
13
15
|
|
|
14
16
|
// src/server.ts
|
|
@@ -141,7 +143,19 @@ async function startStaticServer(options = {}, port = 0) {
|
|
|
141
143
|
return false;
|
|
142
144
|
if (urlPath === SETTLE_READY_PATH) {
|
|
143
145
|
const detail = {};
|
|
144
|
-
for (const key of [
|
|
146
|
+
for (const key of [
|
|
147
|
+
"reason",
|
|
148
|
+
"ms",
|
|
149
|
+
"pending",
|
|
150
|
+
"frames",
|
|
151
|
+
"canvases",
|
|
152
|
+
"containers",
|
|
153
|
+
"mutations",
|
|
154
|
+
"dpr",
|
|
155
|
+
"painted",
|
|
156
|
+
"ready",
|
|
157
|
+
"longtasks"
|
|
158
|
+
]) {
|
|
145
159
|
const value = query.get(key);
|
|
146
160
|
if (value === null)
|
|
147
161
|
continue;
|
|
@@ -172,6 +186,11 @@ async function startStaticServer(options = {}, port = 0) {
|
|
|
172
186
|
const handler = (req, res) => {
|
|
173
187
|
const urlPath = decodeRequestPath(req);
|
|
174
188
|
const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
|
|
189
|
+
// Every request the page makes transits here: log it (path + status) so
|
|
190
|
+
// render problems become traceable from the per-page logs.
|
|
191
|
+
res.on("finish", () => {
|
|
192
|
+
log(`${urlPath} ${res.statusCode}`);
|
|
193
|
+
});
|
|
175
194
|
if (handleSettle(urlPath, query, res))
|
|
176
195
|
return;
|
|
177
196
|
// The viewer page lives next to the document so that scripts the page runs
|
|
@@ -317,6 +336,357 @@ function chromeArgs(extra = []) {
|
|
|
317
336
|
];
|
|
318
337
|
}
|
|
319
338
|
|
|
339
|
+
// src/render/xmp.ts
|
|
340
|
+
const NS = {
|
|
341
|
+
rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
|
|
342
|
+
dc: "http://purl.org/dc/elements/1.1/",
|
|
343
|
+
pdf: "http://ns.adobe.com/pdf/1.3/",
|
|
344
|
+
xmp: "http://ns.adobe.com/xap/1.0/",
|
|
345
|
+
xmpMM: "http://ns.adobe.com/xap/1.0/mm/",
|
|
346
|
+
pdfaid: "http://www.aiim.org/pdfa/ns/id/",
|
|
347
|
+
pdfxid: "http://www.npes.org/pdfx/ns/id/"
|
|
348
|
+
};
|
|
349
|
+
/** XMP Specification Part 1 (April 2012), 8.2.1.2 date form. */
|
|
350
|
+
function toXmpDate(date) {
|
|
351
|
+
const pad = (value, length = 2) => String(value).padStart(length, "0");
|
|
352
|
+
return (`${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
|
|
353
|
+
`T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}Z`);
|
|
354
|
+
}
|
|
355
|
+
// ISO 32000-1:2008, 7.9.4 writes a date as D:YYYYMMDDHHmmSSOHH'mm, the form
|
|
356
|
+
// Skia in Chromium writes. The offset is kept, not normalized to UTC, so the
|
|
357
|
+
// XMP packet shows the same instant the information dictionary shows.
|
|
358
|
+
const PDF_DATE = /^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:Z|([+\-])(\d{2})'(\d{2})'?)$/;
|
|
359
|
+
/** Reformats a PDF date string as an XMP date; `undefined` when not one. */
|
|
360
|
+
function pdfDateToXmpDate(value) {
|
|
361
|
+
const match = PDF_DATE.exec(value);
|
|
362
|
+
if (match === null)
|
|
363
|
+
return undefined;
|
|
364
|
+
const [, year, month, day, hour, minute, second, sign, offsetHour, offsetMinute] = match;
|
|
365
|
+
const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
|
|
366
|
+
return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
|
|
367
|
+
}
|
|
368
|
+
function xmlEscape(text) {
|
|
369
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
370
|
+
}
|
|
371
|
+
/** dc:title/dc:description: a language alternative with the x-default entry. */
|
|
372
|
+
function languageAlternative(text) {
|
|
373
|
+
return ["<rdf:Alt>", ` <rdf:li xml:lang="x-default">${xmlEscape(text)}</rdf:li>`, "</rdf:Alt>"].join("\n ");
|
|
374
|
+
}
|
|
375
|
+
/** dc:creator: an ordered sequence; ";" separates individual authors. */
|
|
376
|
+
function creatorSequence(author) {
|
|
377
|
+
const names = author
|
|
378
|
+
.split(";")
|
|
379
|
+
.map((name) => name.trim())
|
|
380
|
+
.filter((name) => name !== "");
|
|
381
|
+
const items = (names.length === 0 ? [author] : names).map((name) => ` <rdf:li>${xmlEscape(name)}</rdf:li>`);
|
|
382
|
+
return ["<rdf:Seq>", ...items, "</rdf:Seq>"].join("\n ");
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Builds the XMP packet for the document. Only defined fields are written;
|
|
386
|
+
* the packet wrapper uses the fixed header id packet scanners look for
|
|
387
|
+
* (XMP Part 1, 7.3.2 makes the wrapper optional, Acrobat rejects its absence).
|
|
388
|
+
*/
|
|
389
|
+
function buildXmpPacket(fields, label) {
|
|
390
|
+
const properties = [];
|
|
391
|
+
if (label !== undefined && label.kind === "pdfx" && label.version === "X-4") {
|
|
392
|
+
properties.push(`<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>`);
|
|
393
|
+
}
|
|
394
|
+
if (fields.title !== undefined) {
|
|
395
|
+
properties.push(`<dc:title>\n ${languageAlternative(fields.title)}\n </dc:title>`);
|
|
396
|
+
}
|
|
397
|
+
if (fields.author !== undefined) {
|
|
398
|
+
properties.push(`<dc:creator>\n ${creatorSequence(fields.author)}\n </dc:creator>`);
|
|
399
|
+
}
|
|
400
|
+
if (fields.subject !== undefined) {
|
|
401
|
+
properties.push(`<dc:description>\n ${languageAlternative(fields.subject)}\n </dc:description>`);
|
|
402
|
+
}
|
|
403
|
+
if (fields.keywords !== undefined) {
|
|
404
|
+
properties.push(`<pdf:Keywords>${xmlEscape(fields.keywords)}</pdf:Keywords>`);
|
|
405
|
+
}
|
|
406
|
+
if (fields.producer !== undefined) {
|
|
407
|
+
properties.push(`<pdf:Producer>${xmlEscape(fields.producer)}</pdf:Producer>`);
|
|
408
|
+
}
|
|
409
|
+
if (fields.trapped !== undefined) {
|
|
410
|
+
properties.push(`<pdf:Trapped>${fields.trapped}</pdf:Trapped>`);
|
|
411
|
+
}
|
|
412
|
+
if (fields.creatorTool !== undefined) {
|
|
413
|
+
properties.push(`<xmp:CreatorTool>${xmlEscape(fields.creatorTool)}</xmp:CreatorTool>`);
|
|
414
|
+
}
|
|
415
|
+
if (fields.createDate !== undefined) {
|
|
416
|
+
properties.push(`<xmp:CreateDate>${fields.createDate}</xmp:CreateDate>`);
|
|
417
|
+
}
|
|
418
|
+
if (fields.modifyDate !== undefined) {
|
|
419
|
+
properties.push(`<xmp:ModifyDate>${fields.modifyDate}</xmp:ModifyDate>`);
|
|
420
|
+
}
|
|
421
|
+
if (fields.metadataDate !== undefined) {
|
|
422
|
+
properties.push(`<xmp:MetadataDate>${fields.metadataDate}</xmp:MetadataDate>`);
|
|
423
|
+
}
|
|
424
|
+
if (fields.documentId !== undefined) {
|
|
425
|
+
properties.push(`<xmpMM:DocumentID>${xmlEscape(fields.documentId)}</xmpMM:DocumentID>`, `<xmpMM:VersionID>1</xmpMM:VersionID>`, `<xmpMM:RenditionClass>default</xmpMM:RenditionClass>`);
|
|
426
|
+
}
|
|
427
|
+
if (label !== undefined && label.kind === "pdfa") {
|
|
428
|
+
properties.push(`<pdfaid:part>${label.part}</pdfaid:part>`);
|
|
429
|
+
// PDF/A-4 (ISO 19005-4) identifies through the part value alone; the
|
|
430
|
+
// conformance levels a/b/u exist for parts 1 to 3 only.
|
|
431
|
+
if (label.part !== "4" && label.conformance !== undefined) {
|
|
432
|
+
properties.push(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
const body = [
|
|
436
|
+
`<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>`,
|
|
437
|
+
`<x:xmpmeta xmlns:x="adobe:ns:meta/">`,
|
|
438
|
+
` <rdf:RDF xmlns:rdf="${NS.rdf}">`,
|
|
439
|
+
` <rdf:Description rdf:about="" xmlns:dc="${NS.dc}" xmlns:pdf="${NS.pdf}" xmlns:xmp="${NS.xmp}" xmlns:xmpMM="${NS.xmpMM}" xmlns:pdfaid="${NS.pdfaid}" xmlns:pdfxid="${NS.pdfxid}">`,
|
|
440
|
+
...properties.map((property) => ` ${property}`),
|
|
441
|
+
` </rdf:Description>`,
|
|
442
|
+
` </rdf:RDF>`,
|
|
443
|
+
`</x:xmpmeta>`,
|
|
444
|
+
`<?xpacket end="w"?>`
|
|
445
|
+
].join("\n");
|
|
446
|
+
// XML 1.0 (Fifth Edition), 2.11: a processor turns a literal CR into LF
|
|
447
|
+
// before parsing, so a CR in a value survives only as a character reference.
|
|
448
|
+
return `${body.replaceAll("\r", "
")}\n`;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/render/pdf-postprocess.ts
|
|
452
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
453
|
+
// Licensed under the MIT License.
|
|
454
|
+
/**
|
|
455
|
+
* PDF post-processing: document metadata, XMP and standards labeling.
|
|
456
|
+
*
|
|
457
|
+
* Runs on the PDF bytes Chrome printed (Skia output) and applies:
|
|
458
|
+
* - document information entries (title, author, subject, keywords, producer, creator)
|
|
459
|
+
* - the catalog /Lang entry for the document language
|
|
460
|
+
* - an XMP metadata stream kept consistent with the information dictionary
|
|
461
|
+
* - PDF/A or PDF/X identification: XMP identification properties, an
|
|
462
|
+
* OutputIntent with an embedded ICC profile and a stable file identifier
|
|
463
|
+
*
|
|
464
|
+
* This is a "label, don't convert" step — the same semantics vivliostyle-cli
|
|
465
|
+
* gives its PDF/X option: the content is neither converted nor checked, so
|
|
466
|
+
* conformance of the content is the author's responsibility. Verify with
|
|
467
|
+
* veraPDF (or a print provider's preflight) when it matters.
|
|
468
|
+
*
|
|
469
|
+
* The editing follows vivliostyle-cli's mupdf-based post-processing
|
|
470
|
+
* (src/output/pdfx.ts, pdf-document.ts, pdf-version.ts at v11.4).
|
|
471
|
+
*/
|
|
472
|
+
/**
|
|
473
|
+
* Tracks MuPDF's native objects and destroys them in reverse order. Every
|
|
474
|
+
* PDFObject/Buffer/ColorSpace keeps native memory behind the wasm binding,
|
|
475
|
+
* which is only reclaimed on an explicit destroy.
|
|
476
|
+
*/
|
|
477
|
+
function createScope() {
|
|
478
|
+
const tracked = [];
|
|
479
|
+
return {
|
|
480
|
+
track(value) {
|
|
481
|
+
tracked.push(value);
|
|
482
|
+
return value;
|
|
483
|
+
},
|
|
484
|
+
dispose() {
|
|
485
|
+
while (tracked.length > 0) {
|
|
486
|
+
try {
|
|
487
|
+
tracked.pop()?.destroy();
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
// Cleanup is best-effort; a failed destroy must not mask the result.
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
// The catalog /Version is written for every required version; MuPDF's wasm
|
|
497
|
+
// binding provides no API for the header version and a full save derives the
|
|
498
|
+
// header from the catalog entry (same approach as vivliostyle-cli).
|
|
499
|
+
function setMinimumPdfVersion(document, minimumVersion, scope) {
|
|
500
|
+
if (document.getVersion() >= minimumVersion)
|
|
501
|
+
return;
|
|
502
|
+
const trailer = scope.track(document.getTrailer());
|
|
503
|
+
const catalog = scope.track(trailer.get("Root"));
|
|
504
|
+
const version = scope.track(document.newName(`${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`));
|
|
505
|
+
catalog.put("Version", version);
|
|
506
|
+
}
|
|
507
|
+
function readInfoString(info, key, scope) {
|
|
508
|
+
const value = scope.track(info.get(key));
|
|
509
|
+
return value.isString() ? value.asString() : undefined;
|
|
510
|
+
}
|
|
511
|
+
function readTrapped(info, scope) {
|
|
512
|
+
const trapped = scope.track(info.get("Trapped"));
|
|
513
|
+
return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
|
|
514
|
+
}
|
|
515
|
+
function openPdfDocument(pdf, scope) {
|
|
516
|
+
// openDocument returns the Document base type; a PDF input yields a PDFDocument.
|
|
517
|
+
const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
|
|
518
|
+
return scope.track(document);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Runs `fn` with freshly fetched catalog handles. MuPDF replaces the trailer
|
|
522
|
+
* dict whenever an information entry is written through `setMetaData`, and a
|
|
523
|
+
* PDFObject handle held across such a write ends up detached from the
|
|
524
|
+
* document — edits into it silently disappear on save. Every mutation
|
|
525
|
+
* therefore re-fetches its handles right before it runs.
|
|
526
|
+
*/
|
|
527
|
+
function withCatalog(document, scope, fn) {
|
|
528
|
+
const trailer = scope.track(document.getTrailer());
|
|
529
|
+
const catalog = scope.track(trailer.get("Root"));
|
|
530
|
+
return fn(catalog);
|
|
531
|
+
}
|
|
532
|
+
/** Runs `fn` with a freshly fetched information dictionary handle. */
|
|
533
|
+
function withInfo(document, scope, fn) {
|
|
534
|
+
const trailer = scope.track(document.getTrailer());
|
|
535
|
+
const info = scope.track(trailer.get("Info"));
|
|
536
|
+
return fn(info);
|
|
537
|
+
}
|
|
538
|
+
/** Runs `fn` with a freshly fetched trailer handle. */
|
|
539
|
+
function withTrailer(document, scope, fn) {
|
|
540
|
+
return fn(scope.track(document.getTrailer()));
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Applies metadata and standards labeling to a printed PDF.
|
|
544
|
+
*
|
|
545
|
+
* Producer/Creator are always stamped (the wrapper owns them), so a build
|
|
546
|
+
* without explicit metadata still gets a consistent information dictionary
|
|
547
|
+
* and XMP packet. Dates come from what Skia wrote: CreationDate is kept,
|
|
548
|
+
* ModifyDate falls back to it, exactly like vivliostyle-cli handles output
|
|
549
|
+
* from print backends that skip the modification date.
|
|
550
|
+
*/
|
|
551
|
+
async function postProcessPdf(pdf, options) {
|
|
552
|
+
const scope = createScope();
|
|
553
|
+
try {
|
|
554
|
+
const { metadata, label } = options;
|
|
555
|
+
const document = openPdfDocument(pdf, scope);
|
|
556
|
+
// ── What the print backend already wrote ────────────────────────────────
|
|
557
|
+
const { creationDate, modifyDate, trapped } = withInfo(document, scope, (info) => ({
|
|
558
|
+
creationDate: readInfoString(info, "CreationDate", scope),
|
|
559
|
+
modifyDate: readInfoString(info, "ModDate", scope),
|
|
560
|
+
trapped: readTrapped(info, scope)
|
|
561
|
+
}));
|
|
562
|
+
const createDateXmp = (creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined) ?? toXmpDate(new Date());
|
|
563
|
+
// Acrobat's preflight requires xmp:ModifyDate/MetadataDate; backends like
|
|
564
|
+
// Firefox's cairo skip them, so they take the creation date then.
|
|
565
|
+
const modifyDateXmp = (modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined) ?? createDateXmp;
|
|
566
|
+
// ── Document information entries ────────────────────────────────────────
|
|
567
|
+
document.setMetaData("info:Producer", metadata.producer);
|
|
568
|
+
document.setMetaData("info:Creator", metadata.creator);
|
|
569
|
+
if (metadata.title !== undefined)
|
|
570
|
+
document.setMetaData("info:Title", metadata.title);
|
|
571
|
+
if (metadata.author !== undefined)
|
|
572
|
+
document.setMetaData("info:Author", metadata.author);
|
|
573
|
+
if (metadata.subject !== undefined)
|
|
574
|
+
document.setMetaData("info:Subject", metadata.subject);
|
|
575
|
+
if (metadata.keywords !== undefined)
|
|
576
|
+
document.setMetaData("info:Keywords", metadata.keywords);
|
|
577
|
+
// ── Catalog language ────────────────────────────────────────────────────
|
|
578
|
+
const language = metadata.language;
|
|
579
|
+
if (language !== undefined && language !== "") {
|
|
580
|
+
withCatalog(document, scope, (catalog) => {
|
|
581
|
+
catalog.put("Lang", scope.track(document.newString(language)));
|
|
582
|
+
});
|
|
583
|
+
setMinimumPdfVersion(document, 14, scope);
|
|
584
|
+
}
|
|
585
|
+
// ── XMP metadata stream ─────────────────────────────────────────────────
|
|
586
|
+
const xmp = buildXmpPacket({
|
|
587
|
+
title: metadata.title,
|
|
588
|
+
author: metadata.author,
|
|
589
|
+
subject: metadata.subject,
|
|
590
|
+
keywords: metadata.keywords,
|
|
591
|
+
producer: metadata.producer,
|
|
592
|
+
creatorTool: metadata.creator,
|
|
593
|
+
createDate: createDateXmp,
|
|
594
|
+
modifyDate: modifyDateXmp,
|
|
595
|
+
metadataDate: toXmpDate(new Date()),
|
|
596
|
+
documentId: `uuid:${randomUUID()}`,
|
|
597
|
+
...(label !== undefined && label.kind === "pdfx" && label.version === "X-4" ? { trapped } : {})
|
|
598
|
+
}, label);
|
|
599
|
+
withCatalog(document, scope, (catalog) => {
|
|
600
|
+
const xmpBuffer = scope.track(new mupdf.Buffer(xmp));
|
|
601
|
+
const metadataStream = scope.track(document.addStream(xmpBuffer, { Type: "Metadata", Subtype: "XML" }));
|
|
602
|
+
catalog.put("Metadata", metadataStream);
|
|
603
|
+
});
|
|
604
|
+
// ── OutputIntent with the embedded ICC profile ──────────────────────────
|
|
605
|
+
if (label !== undefined) {
|
|
606
|
+
const profile = options.iccProfile;
|
|
607
|
+
if (profile === undefined) {
|
|
608
|
+
throw new Error(label.kind === "pdfx"
|
|
609
|
+
? "PDF/X labeling requires an ICC profile for the OutputIntent (--icc-profile)."
|
|
610
|
+
: "PDF/A labeling requires an ICC profile for the OutputIntent.");
|
|
611
|
+
}
|
|
612
|
+
const profileName = options.iccProfileName ?? "output-intent.icc";
|
|
613
|
+
withCatalog(document, scope, (catalog) => {
|
|
614
|
+
const profileBuffer = scope.track(new mupdf.Buffer(profile));
|
|
615
|
+
const colorSpace = scope.track(new mupdf.ColorSpace(profileBuffer, profileName));
|
|
616
|
+
const profileStream = scope.track(document.addStream(profileBuffer, { N: colorSpace.getNumberOfComponents() }));
|
|
617
|
+
const identifier = scope.track(document.newString("Custom"));
|
|
618
|
+
const profileInfo = scope.track(document.newString(profileName));
|
|
619
|
+
// ISO 32000-1:2008, 7.7.2/14.11.5: OutputConditionIdentifier may be
|
|
620
|
+
// "Custom"; Info and DestOutputProfile are required for nonstandard
|
|
621
|
+
// production conditions.
|
|
622
|
+
const intent = scope.track(document.addObject({
|
|
623
|
+
Type: "OutputIntent",
|
|
624
|
+
S: label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX",
|
|
625
|
+
OutputConditionIdentifier: identifier,
|
|
626
|
+
Info: profileInfo,
|
|
627
|
+
DestOutputProfile: profileStream
|
|
628
|
+
}));
|
|
629
|
+
catalog.put("OutputIntents", [intent]);
|
|
630
|
+
});
|
|
631
|
+
setMinimumPdfVersion(document, 14, scope);
|
|
632
|
+
}
|
|
633
|
+
// ── Standards identification outside the XMP packet ─────────────────────
|
|
634
|
+
if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
|
|
635
|
+
// PDF/X-1a:2003 identification lives in the information dictionary, not
|
|
636
|
+
// in XMP (XMP identification is the PDF/X-4 form).
|
|
637
|
+
document.setMetaData("info:GTS_PDFXVersion", "PDF/X-1a:2003");
|
|
638
|
+
withInfo(document, scope, (info) => {
|
|
639
|
+
info.put("Trapped", scope.track(document.newName(trapped)));
|
|
640
|
+
// Acrobat's PDF/X-1a:2003 preflight requires ModDate, which some print
|
|
641
|
+
// backends never write; it takes the creation date then.
|
|
642
|
+
if (modifyDate === undefined && creationDate !== undefined) {
|
|
643
|
+
info.put("ModDate", scope.track(document.newString(creationDate)));
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
// A stable file identifier is required for PDF/A and PDF/X. Written last,
|
|
648
|
+
// against a trailer handle fetched after every information entry write.
|
|
649
|
+
if (label !== undefined) {
|
|
650
|
+
withTrailer(document, scope, (trailer) => {
|
|
651
|
+
const existingId = scope.track(trailer.get("ID"));
|
|
652
|
+
if (!existingId.isArray()) {
|
|
653
|
+
const bytes = randomBytes(16);
|
|
654
|
+
trailer.put("ID", [document.newByteString(bytes), document.newByteString(bytes)]);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
if (!document.hasUnsavedChanges())
|
|
659
|
+
return pdf;
|
|
660
|
+
const output = scope.track(document.saveToBuffer("compress"));
|
|
661
|
+
// Copy so the data stays valid after the buffer is destroyed.
|
|
662
|
+
return new Uint8Array(output.asUint8Array());
|
|
663
|
+
}
|
|
664
|
+
finally {
|
|
665
|
+
scope.dispose();
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
|
|
670
|
+
* The profile ships unchanged from the ICC ("sRGB_v4_ICC_preference.icc"); its
|
|
671
|
+
* license permits redistribution provided the file, including its embedded
|
|
672
|
+
* copyright notice tag, is not modified (https://www.color.org/srgbprofiles.xalter).
|
|
673
|
+
*/
|
|
674
|
+
function loadDefaultIccProfile() {
|
|
675
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
676
|
+
const candidates = [
|
|
677
|
+
// Source layout (vitest, direct TS execution).
|
|
678
|
+
join(moduleDir, "srgb.icc"),
|
|
679
|
+
// Bundled layout: dist/vivliostyle-batch-cli.js ships next to src/.
|
|
680
|
+
resolve(moduleDir, "../src/render/srgb.icc")
|
|
681
|
+
];
|
|
682
|
+
for (const candidate of candidates) {
|
|
683
|
+
if (existsSync(candidate)) {
|
|
684
|
+
return { bytes: readFileSync(candidate), name: "sRGB_v4_ICC_preference.icc" };
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
|
|
688
|
+
}
|
|
689
|
+
|
|
320
690
|
// src/render/pdf.ts
|
|
321
691
|
// Copyright (c) 2026 Christian Mahnke
|
|
322
692
|
// Licensed under the MIT License.
|
|
@@ -326,6 +696,10 @@ function chromeArgs(extra = []) {
|
|
|
326
696
|
* The viewer page is served by our own static server (see src/server.ts), so
|
|
327
697
|
* the document's origin — and therefore the base URI of the scripts the page
|
|
328
698
|
* runs — is the site we serve, not an internal viewer base.
|
|
699
|
+
*
|
|
700
|
+
* Printed pages run through the post-processing step (see
|
|
701
|
+
* src/render/pdf-postprocess.ts), which stamps the document metadata and
|
|
702
|
+
* applies the requested PDF/A or PDF/X labeling.
|
|
329
703
|
*/
|
|
330
704
|
/** URL of the viewer page, with the publication and layout parameters. */
|
|
331
705
|
function buildViewerUrl(viewerPageUrl, params) {
|
|
@@ -339,25 +713,18 @@ function buildViewerUrl(viewerPageUrl, params) {
|
|
|
339
713
|
return query === "" ? viewerPageUrl : `${viewerPageUrl}#${query}`;
|
|
340
714
|
}
|
|
341
715
|
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
342
|
-
/**
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
if (meta.keywords !== undefined)
|
|
355
|
-
document.setKeywords([meta.keywords]);
|
|
356
|
-
if (meta.language !== undefined)
|
|
357
|
-
document.setLanguage(meta.language);
|
|
358
|
-
document.setProducer("vivliostyle-batch-cli");
|
|
359
|
-
document.setCreator("vivliostyle-batch-cli");
|
|
360
|
-
return document.save();
|
|
716
|
+
/** The wrapper owns the producer/creator entries of every PDF it prints. */
|
|
717
|
+
const TOOL_IDENTITY = "vivliostyle-batch-cli";
|
|
718
|
+
function pdfMetadata(request) {
|
|
719
|
+
return {
|
|
720
|
+
...(request.title === undefined ? {} : { title: request.title }),
|
|
721
|
+
...(request.author === undefined ? {} : { author: request.author }),
|
|
722
|
+
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
723
|
+
...(request.keywords === undefined ? {} : { keywords: request.keywords }),
|
|
724
|
+
...(request.language === undefined ? {} : { language: request.language }),
|
|
725
|
+
creator: TOOL_IDENTITY,
|
|
726
|
+
producer: TOOL_IDENTITY
|
|
727
|
+
};
|
|
361
728
|
}
|
|
362
729
|
/**
|
|
363
730
|
* Runs inside one frame (viewer window or a document/iframe within it):
|
|
@@ -386,8 +753,179 @@ function buildFrameProbeScript(factor) {
|
|
|
386
753
|
try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
|
|
387
754
|
}
|
|
388
755
|
try { window.dispatchEvent(new Event("resize")); } catch(e){}
|
|
756
|
+
// Bridge the viewer's broken page lifecycle. A-Frame scenes can end up
|
|
757
|
+
// loaded-but-never-playing in the paginated tree (render loop, default
|
|
758
|
+
// lights and asset loads all missed their window) while the same page
|
|
759
|
+
// renders fine in a real browser. Start the scene's own loop and give
|
|
760
|
+
// collapsed scenes a box (their display:block stylesheet does not reach
|
|
761
|
+
// the re-parented tree, so unsized unknown elements stay inline).
|
|
762
|
+
try {
|
|
763
|
+
var bridgeScenes = document.querySelectorAll("a-scene");
|
|
764
|
+
for (var bi = 0; bi < bridgeScenes.length; bi++) {
|
|
765
|
+
var bridgeScene = bridgeScenes[bi];
|
|
766
|
+
if (!bridgeScene.isPlaying && typeof bridgeScene.play === "function") {
|
|
767
|
+
try { bridgeScene.play(); } catch (e) {}
|
|
768
|
+
}
|
|
769
|
+
if (bridgeScene.clientWidth === 0 || bridgeScene.clientHeight === 0) {
|
|
770
|
+
var sized = bridgeScene.parentElement;
|
|
771
|
+
while (sized && (sized.clientWidth === 0 || sized.clientHeight === 0)) sized = sized.parentElement;
|
|
772
|
+
if (sized) {
|
|
773
|
+
bridgeScene.style.display = "block";
|
|
774
|
+
bridgeScene.style.width = sized.clientWidth + "px";
|
|
775
|
+
bridgeScene.style.height = sized.clientHeight + "px";
|
|
776
|
+
if (typeof bridgeScene.resize === "function") bridgeScene.resize();
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
await nextFrame();
|
|
781
|
+
} catch(e){}
|
|
782
|
+
// Give each scene what it needs to render like the browser does, then
|
|
783
|
+
// materialize its WebGL canvas into a 2D overlay (2D canvases always
|
|
784
|
+
// survive print-to-PDF): re-kick unloaded assets, swap unlit materials for
|
|
785
|
+
// flat ones when no lights exist, render, and blit synchronously.
|
|
786
|
+
var materialized = 0;
|
|
787
|
+
var sceneDiag = "";
|
|
788
|
+
try {
|
|
789
|
+
var scenes = document.querySelectorAll("a-scene");
|
|
790
|
+
for (var si = 0; si < scenes.length; si++) {
|
|
791
|
+
var sceneEl = scenes[si];
|
|
792
|
+
// The viewer clones scenes into its page boxes; only the VISIBLE one
|
|
793
|
+
// (with a box) is what the PDF will show. The hidden original's render
|
|
794
|
+
// would materialize nothing.
|
|
795
|
+
if (!(sceneEl.clientWidth > 0 && sceneEl.clientHeight > 0)) continue;
|
|
796
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
797
|
+
try {
|
|
798
|
+
var gltfEl = sceneEl.querySelector("[gltf-model]");
|
|
799
|
+
if (gltfEl) {
|
|
800
|
+
var gmObj = gltfEl.object3D;
|
|
801
|
+
sceneDiag += " gmKids=" + gmObj.children.length + "/" + (gltfEl.components["gltf-model"] ? String(gltfEl.components["gltf-model"].model !== null) : "nocomp");
|
|
802
|
+
}
|
|
803
|
+
sceneDiag += " tree=" + sceneEl.object3D.children.map(function (c) { return c.type + (c.children ? ":" + c.children.length : ""); }).join("|").slice(0, 110);
|
|
804
|
+
} catch (e) {
|
|
805
|
+
sceneDiag += " diagErr " + String(e).slice(0, 50);
|
|
806
|
+
}
|
|
807
|
+
try {
|
|
808
|
+
var assetItems = sceneEl.querySelectorAll("a-asset-item");
|
|
809
|
+
var assetWaits = [];
|
|
810
|
+
for (var ai = 0; ai < assetItems.length; ai++) {
|
|
811
|
+
var assetEl = assetItems[ai];
|
|
812
|
+
if (assetEl.hasLoaded) continue;
|
|
813
|
+
assetWaits.push(
|
|
814
|
+
new Promise(function (resolve) {
|
|
815
|
+
var settled = false;
|
|
816
|
+
var finish = function () {
|
|
817
|
+
if (settled) return;
|
|
818
|
+
settled = true;
|
|
819
|
+
resolve();
|
|
820
|
+
};
|
|
821
|
+
assetEl.addEventListener("loaded", finish, { once: true });
|
|
822
|
+
assetEl.addEventListener("error", finish, { once: true });
|
|
823
|
+
setTimeout(finish, 8000);
|
|
824
|
+
var src = assetEl.getAttribute("src");
|
|
825
|
+
if (src) assetEl.setAttribute("src", src);
|
|
826
|
+
})
|
|
827
|
+
);
|
|
828
|
+
}
|
|
829
|
+
if (assetWaits.length > 0) {
|
|
830
|
+
await Promise.race([Promise.all(assetWaits), new Promise(function (r) { setTimeout(r, 9000); })]);
|
|
831
|
+
}
|
|
832
|
+
} catch (e) {}
|
|
833
|
+
try {
|
|
834
|
+
var lightsFound = 0;
|
|
835
|
+
sceneEl.object3D.traverse(function (n) { if (n.isLight) lightsFound++; });
|
|
836
|
+
if (lightsFound === 0) {
|
|
837
|
+
var basicCtor = null;
|
|
838
|
+
sceneEl.object3D.traverse(function (n) {
|
|
839
|
+
if (n.isMesh && n.material && n.material.isMeshBasicMaterial && basicCtor === null) basicCtor = n.material.constructor;
|
|
840
|
+
});
|
|
841
|
+
if (basicCtor) {
|
|
842
|
+
sceneEl.object3D.traverse(function (n) {
|
|
843
|
+
if (!n.isMesh || !n.material || n.material.isMeshBasicMaterial) return;
|
|
844
|
+
try {
|
|
845
|
+
var m = n.material;
|
|
846
|
+
var flat = new basicCtor({ color: m.color ? m.color.clone() : undefined });
|
|
847
|
+
flat.side = m.side;
|
|
848
|
+
flat.transparent = m.transparent;
|
|
849
|
+
flat.opacity = m.opacity;
|
|
850
|
+
if (m.map) flat.map = m.map;
|
|
851
|
+
n.material = flat;
|
|
852
|
+
} catch (e) {}
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
} catch(e){}
|
|
857
|
+
try {
|
|
858
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
859
|
+
var glCanvas = sceneEl.canvas;
|
|
860
|
+
if (!glCanvas || glCanvas.width === 0 || glCanvas.height === 0) continue;
|
|
861
|
+
var overlay = document.createElement("canvas");
|
|
862
|
+
overlay.setAttribute("data-viv-gl-overlay", "");
|
|
863
|
+
overlay.width = glCanvas.width;
|
|
864
|
+
overlay.height = glCanvas.height;
|
|
865
|
+
overlay.style.position = "absolute";
|
|
866
|
+
overlay.style.pointerEvents = "none";
|
|
867
|
+
overlay.style.width = glCanvas.clientWidth + "px";
|
|
868
|
+
overlay.style.height = glCanvas.clientHeight + "px";
|
|
869
|
+
var cr = glCanvas.getBoundingClientRect();
|
|
870
|
+
var pr = (glCanvas.offsetParent || document.body).getBoundingClientRect();
|
|
871
|
+
overlay.style.left = cr.left - pr.left + "px";
|
|
872
|
+
overlay.style.top = cr.top - pr.top + "px";
|
|
873
|
+
overlay.style.zIndex = "1";
|
|
874
|
+
(glCanvas.parentNode || document.body).appendChild(overlay);
|
|
875
|
+
overlay.getContext("2d").drawImage(glCanvas, 0, 0);
|
|
876
|
+
// Empty capture = the scene never initialized in this tree (its
|
|
877
|
+
// framework lifecycle was lost to the viewer's re-parenting). Replace
|
|
878
|
+
// it with a fresh copy: the custom-element upgrade re-runs the full
|
|
879
|
+
// framework lifecycle (assets, lights, render loop) in the now-sized
|
|
880
|
+
// tree.
|
|
881
|
+
var empty = true;
|
|
882
|
+
try {
|
|
883
|
+
var dd = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
884
|
+
for (var di = 3; di < dd.length; di += 256) {
|
|
885
|
+
if (dd[di] > 0) {
|
|
886
|
+
empty = false;
|
|
887
|
+
break;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
} catch (e) {
|
|
891
|
+
empty = false;
|
|
892
|
+
}
|
|
893
|
+
if (empty) {
|
|
894
|
+
var fresh = sceneEl.cloneNode(true);
|
|
895
|
+
sceneEl.parentNode.replaceChild(fresh, sceneEl);
|
|
896
|
+
sceneEl = fresh;
|
|
897
|
+
// Enough time for the fresh scene's asset fetches (a real GLB over
|
|
898
|
+
// the network) + first renders.
|
|
899
|
+
await new Promise(function (r) {
|
|
900
|
+
setTimeout(r, 8000);
|
|
901
|
+
});
|
|
902
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
903
|
+
}
|
|
904
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
905
|
+
var gl2 = sceneEl.canvas;
|
|
906
|
+
if (!gl2 || gl2.width === 0 || gl2.height === 0) continue;
|
|
907
|
+
overlay.width = gl2.width;
|
|
908
|
+
overlay.height = gl2.height;
|
|
909
|
+
overlay.getContext("2d").drawImage(gl2, 0, 0);
|
|
910
|
+
materialized++;
|
|
911
|
+
try {
|
|
912
|
+
var od = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
913
|
+
var alphaN = 0;
|
|
914
|
+
var orangeN = 0;
|
|
915
|
+
for (var oi = 3; oi < od.length; oi += 16) {
|
|
916
|
+
if (od[oi] > 0) alphaN++;
|
|
917
|
+
if (od[oi - 3] > 150 && od[oi - 2] > 60 && od[oi - 2] < 200 && od[oi - 1] < 110 && od[oi - 3] > od[oi - 2] + 40) orangeN++;
|
|
918
|
+
}
|
|
919
|
+
glSample = [alphaN, orangeN];
|
|
920
|
+
} catch (e) {}
|
|
921
|
+
} catch (e) {}
|
|
922
|
+
}
|
|
923
|
+
} catch(e){}
|
|
389
924
|
// Hooks like echarts re-init dispose the canvas synchronously; let layout
|
|
390
925
|
// settle a frame before measuring so sizes reflect the repainted state.
|
|
926
|
+
// This also lets render loops refill their drawing buffers after the
|
|
927
|
+
// resize above — drawImage on a just-resized WebGL canvas would read the
|
|
928
|
+
// cleared buffer.
|
|
391
929
|
try { await nextFrame(); } catch(e){}
|
|
392
930
|
if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
|
|
393
931
|
var webgl = false, webgl2 = false;
|
|
@@ -406,7 +944,9 @@ function buildFrameProbeScript(factor) {
|
|
|
406
944
|
canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
|
|
407
945
|
iframeCount: document.querySelectorAll("iframe").length,
|
|
408
946
|
dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
|
|
409
|
-
resized: resized
|
|
947
|
+
resized: resized,
|
|
948
|
+
materialized: materialized,
|
|
949
|
+
sceneDiag: sceneDiag
|
|
410
950
|
};
|
|
411
951
|
})(${JSON.stringify(factor)})`;
|
|
412
952
|
}
|
|
@@ -420,8 +960,9 @@ async function prepareForPrint(page, options = {}) {
|
|
|
420
960
|
try {
|
|
421
961
|
out.push((await frame.evaluate(script)));
|
|
422
962
|
}
|
|
423
|
-
catch {
|
|
963
|
+
catch (err) {
|
|
424
964
|
// Cross-origin embeds that refuse evaluation still print as pixels.
|
|
965
|
+
log.trace("frame probe failed", frame.url?.() ?? "(frame)", err instanceof Error ? err.message : String(err));
|
|
425
966
|
continue;
|
|
426
967
|
}
|
|
427
968
|
}
|
|
@@ -433,10 +974,11 @@ async function prepareForPrint(page, options = {}) {
|
|
|
433
974
|
/** One-line summary for logs: capabilities per frame that owns content. */
|
|
434
975
|
function summarizeCapabilities(caps) {
|
|
435
976
|
return caps
|
|
436
|
-
.filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
|
|
977
|
+
.filter((c) => c.canvasCount > 0 || (c.iframeCount ?? 0) > 0 || c.fixture !== null)
|
|
437
978
|
.map((c) => `${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
|
|
438
979
|
`webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
|
|
439
|
-
(c.resized !== null ? ` resized=[${c.resized}]` : "")
|
|
980
|
+
(c.resized !== null ? ` resized=[${c.resized}]` : "") +
|
|
981
|
+
(c.materialized ? ` materialized=${c.materialized} ${c.sceneDiag ?? ""}` : ""))
|
|
440
982
|
.join(" | ");
|
|
441
983
|
}
|
|
442
984
|
async function renderPdf(request) {
|
|
@@ -466,12 +1008,15 @@ async function renderPdf(request) {
|
|
|
466
1008
|
page.setDefaultNavigationTimeout(timeoutMs);
|
|
467
1009
|
page.on("pageerror", (err) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
|
|
468
1010
|
// Viewer and page errors are the usual reason a render produces nothing.
|
|
1011
|
+
// Debug/info console messages (fetch traces from the runtime script) are
|
|
1012
|
+
// shown at debug level, so -d traces every page-side request.
|
|
1013
|
+
const debugConsole = log.getLevel() <= log.levels.DEBUG;
|
|
469
1014
|
page.on("console", (message) => {
|
|
470
1015
|
const type = message.type();
|
|
471
|
-
if (type !== "error" && type !== "warn")
|
|
1016
|
+
if (type !== "error" && type !== "warn" && !(debugConsole && (type === "debug" || type === "info")))
|
|
472
1017
|
return;
|
|
473
1018
|
const where = message.location();
|
|
474
|
-
log
|
|
1019
|
+
log[debugConsole && type !== "error" && type !== "warn" ? "trace" : "warn"](`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`);
|
|
475
1020
|
});
|
|
476
1021
|
page.on("requestfailed", (request) => {
|
|
477
1022
|
log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
|
|
@@ -524,7 +1069,11 @@ async function renderPdf(request) {
|
|
|
524
1069
|
preferCSSPageSize: true,
|
|
525
1070
|
tagged: true
|
|
526
1071
|
});
|
|
527
|
-
const stamped = await
|
|
1072
|
+
const stamped = await postProcessPdf(pdf, {
|
|
1073
|
+
metadata: pdfMetadata(request),
|
|
1074
|
+
...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
|
|
1075
|
+
...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
|
|
1076
|
+
});
|
|
528
1077
|
mkdirSync(dirname(request.output), { recursive: true });
|
|
529
1078
|
writeFileSync(request.output, stamped);
|
|
530
1079
|
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
@@ -567,6 +1116,132 @@ function fileURLOfSelf() {
|
|
|
567
1116
|
return new URL(import.meta.url).pathname;
|
|
568
1117
|
}
|
|
569
1118
|
|
|
1119
|
+
// src/metadata.ts
|
|
1120
|
+
/** Language tag assumed when no source provides one (project contract). */
|
|
1121
|
+
const DEFAULT_LANGUAGE = "de";
|
|
1122
|
+
/**
|
|
1123
|
+
* Extracts metadata from the input document: <title>, the usual
|
|
1124
|
+
* author/description/keywords meta tags and the document language.
|
|
1125
|
+
*/
|
|
1126
|
+
function extractMetadataFromDocument(document) {
|
|
1127
|
+
const title = document.querySelector("title")?.textContent?.trim();
|
|
1128
|
+
const metaContent = (names) => {
|
|
1129
|
+
for (const name of names) {
|
|
1130
|
+
const element = document.querySelector(`meta[name="${name}" i]`) ?? document.querySelector(`meta[http-equiv="${name}" i]`);
|
|
1131
|
+
const content = element?.getAttribute("content")?.trim();
|
|
1132
|
+
if (content !== undefined && content !== "")
|
|
1133
|
+
return content;
|
|
1134
|
+
}
|
|
1135
|
+
return undefined;
|
|
1136
|
+
};
|
|
1137
|
+
return {
|
|
1138
|
+
...(title === undefined || title === "" ? {} : { title }),
|
|
1139
|
+
...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
|
|
1140
|
+
...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
|
|
1141
|
+
...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
|
|
1142
|
+
...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
|
|
1143
|
+
language: value
|
|
1144
|
+
}))
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Extracts metadata from a publication manifest (W3C Web Publication
|
|
1149
|
+
* Manifest shape): title, author, description, keywords and language.
|
|
1150
|
+
* Returns undefined when the text is not a JSON object.
|
|
1151
|
+
*/
|
|
1152
|
+
function extractMetadataFromManifest(text) {
|
|
1153
|
+
let manifest;
|
|
1154
|
+
try {
|
|
1155
|
+
manifest = JSON.parse(text);
|
|
1156
|
+
}
|
|
1157
|
+
catch {
|
|
1158
|
+
return undefined;
|
|
1159
|
+
}
|
|
1160
|
+
if (manifest === null || typeof manifest !== "object")
|
|
1161
|
+
return undefined;
|
|
1162
|
+
const record = manifest;
|
|
1163
|
+
return {
|
|
1164
|
+
...optional(asString(record.title), (value) => ({ title: value })),
|
|
1165
|
+
...optional(asAuthorList(record.author), (value) => ({ author: value })),
|
|
1166
|
+
...optional(asString(record.description), (value) => ({ subject: value })),
|
|
1167
|
+
...optional(asStringList(record.keywords, ", "), (value) => ({ keywords: value })),
|
|
1168
|
+
...optional(asStringList(record.language ?? record.inLanguage, " "), (value) => ({ language: value }))
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Merges the sources: the CLI fields win over the extracted ones, and the
|
|
1173
|
+
* language falls back to the project default.
|
|
1174
|
+
*/
|
|
1175
|
+
function resolveMetadata(cli, derived) {
|
|
1176
|
+
const merged = { ...derived, ...definedEntries(cli) };
|
|
1177
|
+
if (merged.language === undefined || merged.language === "") {
|
|
1178
|
+
merged.language = DEFAULT_LANGUAGE;
|
|
1179
|
+
}
|
|
1180
|
+
return merged;
|
|
1181
|
+
}
|
|
1182
|
+
/** Parses a `--pdfa` level like `2b`; part 4 takes no conformance level. */
|
|
1183
|
+
function parsePdfaLabel(value) {
|
|
1184
|
+
const match = /^([1-4])([abu])?$/i.exec(value.trim());
|
|
1185
|
+
if (match === null) {
|
|
1186
|
+
throw new Error(`Invalid --pdfa level: "${value}". Allowed: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4`);
|
|
1187
|
+
}
|
|
1188
|
+
const part = match[1];
|
|
1189
|
+
const conformance = match[2]?.toLowerCase();
|
|
1190
|
+
if (part === "4" && conformance !== undefined) {
|
|
1191
|
+
throw new Error(`PDF/A-4 does not take a conformance level: "${value}". Use --pdfa 4`);
|
|
1192
|
+
}
|
|
1193
|
+
if (part !== "4" && conformance === undefined) {
|
|
1194
|
+
throw new Error(`Missing PDF/A conformance level: "${value}". Use e.g. --pdfa 2b`);
|
|
1195
|
+
}
|
|
1196
|
+
return { kind: "pdfa", part, ...(conformance === undefined ? {} : { conformance }) };
|
|
1197
|
+
}
|
|
1198
|
+
/** Parses a `--pdfx` version; `X-1a` is accepted as shorthand for 2003. */
|
|
1199
|
+
function parsePdfxLabel(value) {
|
|
1200
|
+
const normalized = value.trim();
|
|
1201
|
+
if (normalized === "X-4")
|
|
1202
|
+
return { kind: "pdfx", version: "X-4" };
|
|
1203
|
+
if (normalized === "X-1a" || normalized === "X-1a:2003")
|
|
1204
|
+
return { kind: "pdfx", version: "X-1a:2003" };
|
|
1205
|
+
throw new Error(`Invalid --pdfx version: "${value}". Allowed: X-4, X-1a:2003`);
|
|
1206
|
+
}
|
|
1207
|
+
// ---------------------------------------------------------------------------
|
|
1208
|
+
// Helpers
|
|
1209
|
+
// ---------------------------------------------------------------------------
|
|
1210
|
+
function definedEntries(source) {
|
|
1211
|
+
const entries = {};
|
|
1212
|
+
for (const [key, value] of Object.entries(source)) {
|
|
1213
|
+
if (value !== undefined && value !== "")
|
|
1214
|
+
entries[key] = value;
|
|
1215
|
+
}
|
|
1216
|
+
return entries;
|
|
1217
|
+
}
|
|
1218
|
+
function optional(value, wrap) {
|
|
1219
|
+
return value === undefined || value === null || value === "" ? {} : wrap(value);
|
|
1220
|
+
}
|
|
1221
|
+
function asString(value) {
|
|
1222
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
|
|
1223
|
+
}
|
|
1224
|
+
/** Flattens string | {name} | ({name} | string)[] into "a; b" form. */
|
|
1225
|
+
function asAuthorList(value) {
|
|
1226
|
+
const names = Array.isArray(value) ? value : [value];
|
|
1227
|
+
const flattened = names
|
|
1228
|
+
.map((entry) => {
|
|
1229
|
+
if (typeof entry === "string")
|
|
1230
|
+
return entry.trim();
|
|
1231
|
+
if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
|
|
1232
|
+
return entry.name.trim();
|
|
1233
|
+
}
|
|
1234
|
+
return "";
|
|
1235
|
+
})
|
|
1236
|
+
.filter((name) => name !== "");
|
|
1237
|
+
return flattened.length === 0 ? undefined : flattened.join("; ");
|
|
1238
|
+
}
|
|
1239
|
+
function asStringList(value, separator) {
|
|
1240
|
+
const entries = Array.isArray(value) ? value : [value];
|
|
1241
|
+
const flattened = entries.map((entry) => (typeof entry === "string" ? entry.trim() : "")).filter((entry) => entry !== "");
|
|
1242
|
+
return flattened.length === 0 ? undefined : flattened.join(separator);
|
|
1243
|
+
}
|
|
1244
|
+
|
|
570
1245
|
// src/vivliostyle-cli.ts
|
|
571
1246
|
// Copyright (c) 2026 Christian Mahnke
|
|
572
1247
|
// Licensed under the MIT License.
|
|
@@ -670,7 +1345,38 @@ function buildRuntimeScript(options) {
|
|
|
670
1345
|
return `(function(){
|
|
671
1346
|
var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
|
|
672
1347
|
var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
|
|
673
|
-
var pending=0,frames=0,last=0,mutations=0,done=false;
|
|
1348
|
+
var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
|
|
1349
|
+
// Force preserveDrawingBuffer on every WebGL context the page creates:
|
|
1350
|
+
// print-to-PDF otherwise captures the cleared drawing buffer and WebGL
|
|
1351
|
+
// content ships empty, even though the browser shows it composited.
|
|
1352
|
+
try {
|
|
1353
|
+
var origGetContext = HTMLCanvasElement.prototype.getContext;
|
|
1354
|
+
HTMLCanvasElement.prototype.getContext = function (type, attrs) {
|
|
1355
|
+
if (typeof type === "string" && /^webgl/.test(type)) {
|
|
1356
|
+
attrs = Object.assign({}, attrs || {});
|
|
1357
|
+
attrs.preserveDrawingBuffer = true;
|
|
1358
|
+
return origGetContext.call(this, type, attrs);
|
|
1359
|
+
}
|
|
1360
|
+
return origGetContext.call(this, type, attrs);
|
|
1361
|
+
};
|
|
1362
|
+
} catch (e) {}
|
|
1363
|
+
// Vivliostyle re-dispatches DOMContentLoaded on the window only, so scripts
|
|
1364
|
+
// waiting for it on the document (framework bootstraps, print scripts, asset
|
|
1365
|
+
// bootstraps) never run. Re-dispatch the lifecycle events properly once
|
|
1366
|
+
// loading finished.
|
|
1367
|
+
try {
|
|
1368
|
+
var redeliver = function () {
|
|
1369
|
+
setTimeout(function () {
|
|
1370
|
+
try {
|
|
1371
|
+
document.dispatchEvent(new Event("DOMContentLoaded"));
|
|
1372
|
+
window.dispatchEvent(new Event("DOMContentLoaded"));
|
|
1373
|
+
window.dispatchEvent(new Event("load"));
|
|
1374
|
+
} catch (e) {}
|
|
1375
|
+
}, 0);
|
|
1376
|
+
};
|
|
1377
|
+
if (document.readyState === "complete") redeliver();
|
|
1378
|
+
else window.addEventListener("load", redeliver, { once: true });
|
|
1379
|
+
} catch (e) {}
|
|
674
1380
|
var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mutations:0,dpr:window.devicePixelRatio};
|
|
675
1381
|
|
|
676
1382
|
// Root-relative URLs resolve against the site root, document-relative ones
|
|
@@ -704,7 +1410,7 @@ function signal(why){
|
|
|
704
1410
|
var at=Math.round(performance.now());
|
|
705
1411
|
state.done=true;state.reason=why;state.at=at;state.pending=pending;state.frames=frames;state.mutations=mutations;
|
|
706
1412
|
var url=ORIGIN+"/__viv-settle-ready?reason="+encodeURIComponent(why)+"&ms="+at+
|
|
707
|
-
"&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&dpr="+window.devicePixelRatio+
|
|
1413
|
+
"&pending="+pending+"&frames="+frames+"&mutations="+mutations+"&longtasks="+longtasks+"&dpr="+window.devicePixelRatio+
|
|
708
1414
|
"&painted="+paintedCanvases()+"&ready="+(window.__vivReady===true?1:0)+
|
|
709
1415
|
"&canvases="+encodeURIComponent(canvases())+"&containers="+encodeURIComponent(containers());
|
|
710
1416
|
try{navigator.sendBeacon?navigator.sendBeacon(url):fetch(url,{keepalive:true});}catch(e){}
|
|
@@ -734,14 +1440,39 @@ if(of){window.fetch=function(input,init){
|
|
|
734
1440
|
else if(input&&typeof input.url==="string")input=new Request(fix(input.url),input);
|
|
735
1441
|
}catch(e){}
|
|
736
1442
|
pending++;last=performance.now();
|
|
737
|
-
|
|
738
|
-
|
|
1443
|
+
var furl=(typeof input==="string"?input:input&&input.url?input.url:"?");
|
|
1444
|
+
return of.call(this,input,init).then(function(v){pending--;last=performance.now();
|
|
1445
|
+
try{console.debug("[viv-fetch]",furl,"->",v.status);}catch(e){}
|
|
1446
|
+
return v;},
|
|
1447
|
+
function(e){pending--;last=performance.now();
|
|
1448
|
+
try{console.debug("[viv-fetch]",furl,"-> FAILED",String(e).slice(0,80));}catch(e2){}
|
|
1449
|
+
throw e;});};}
|
|
739
1450
|
var XHR=window.XMLHttpRequest;
|
|
740
1451
|
if(XHR){var open=XHR.prototype.open,send=XHR.prototype.send;
|
|
741
|
-
XHR.prototype.open=function(m,u){this.__vscounted=true;return open.apply(this,arguments);};
|
|
1452
|
+
XHR.prototype.open=function(m,u){this.__vscounted=true;this.__vsurl=fix(u);return open.apply(this,arguments);};
|
|
742
1453
|
XHR.prototype.send=function(){if(this.__vscounted&&!this.__vsdone){this.__vsdone=true;pending++;last=performance.now();
|
|
743
|
-
this.addEventListener("loadend",function(){pending--;last=performance.now();
|
|
1454
|
+
this.addEventListener("loadend",function(){pending--;last=performance.now();
|
|
1455
|
+
try{console.debug("[viv-xhr]",this.__vsurl,"->",this.status);}catch(e){}});}
|
|
744
1456
|
return send.apply(this,arguments);};}
|
|
1457
|
+
// WebAssembly compilation runs after its fetch resolves, so the fetch wrapper
|
|
1458
|
+
// alone would report idle mid-compile. Hold pending through it.
|
|
1459
|
+
var WA=window.WebAssembly;
|
|
1460
|
+
if(WA){["instantiate","instantiateStreaming","compile","compileStreaming"].forEach(function(n){
|
|
1461
|
+
var orig=WA[n];if(typeof orig!=="function")return;
|
|
1462
|
+
WA[n]=function(){pending++;last=performance.now();
|
|
1463
|
+
var result;
|
|
1464
|
+
try{result=orig.apply(this,arguments);}catch(e){pending--;last=performance.now();throw e;}
|
|
1465
|
+
if(result&&typeof result.then==="function"){
|
|
1466
|
+
return result.then(function(v){pending--;last=performance.now();return v;},
|
|
1467
|
+
function(e){pending--;last=performance.now();throw e;});
|
|
1468
|
+
}
|
|
1469
|
+
pending--;last=performance.now();return result;};});}
|
|
1470
|
+
// Heavy main-thread work (script eval, wasm compile, shader/layout jank)
|
|
1471
|
+
// emits no network or DOM signal; long tasks keep the quiet window open.
|
|
1472
|
+
try{var PO=window.PerformanceObserver;
|
|
1473
|
+
if(typeof PO==="function"){new PO(function(list){
|
|
1474
|
+
var entries=list.getEntries();for(var i=0;i<entries.length;i++){longtasks++;last=performance.now();}
|
|
1475
|
+
}).observe({entryTypes:["longtask"]});}}catch(e){}
|
|
745
1476
|
["Image","Audio"].forEach(function(n){
|
|
746
1477
|
var Orig=window[n];if(!Orig)return;
|
|
747
1478
|
var Wrapped=function(u){return new Orig(fix(u));};
|
|
@@ -766,6 +1497,8 @@ last=performance.now();
|
|
|
766
1497
|
${expandDetailsTick}
|
|
767
1498
|
var now=performance.now();
|
|
768
1499
|
if(now>=DEADLINE){signal("deadline");return;}
|
|
1500
|
+
// Webfonts loading late would leave canvas text painted with fallbacks.
|
|
1501
|
+
try{if(document.fonts&&document.fonts.status==="loading"){setTimeout(check,50);return;}}catch(e){}
|
|
769
1502
|
// Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
|
|
770
1503
|
// painted instead of making the gate guess from network quietness. Shader
|
|
771
1504
|
// compile and tile decode finish after the last fetch, so readiness wins.
|
|
@@ -1133,6 +1866,72 @@ function rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl
|
|
|
1133
1866
|
};
|
|
1134
1867
|
return rewriteUrlAttributes(document, (url) => (shouldRewrite(url) ? `${serverBaseUrl}${url}` : url));
|
|
1135
1868
|
}
|
|
1869
|
+
/**
|
|
1870
|
+
* Resolves relative URLs on custom elements (`<a-asset-item>`,
|
|
1871
|
+
* `<model-viewer>`, and any tag name containing a dash) to absolute server
|
|
1872
|
+
* URLs.
|
|
1873
|
+
*
|
|
1874
|
+
* Vivliostyle resolves the subresource attributes it knows (`<img>`,
|
|
1875
|
+
* `<iframe>`, …) correctly, but mangles relative URLs on elements it does not
|
|
1876
|
+
* understand — `../tiles/model.glb` on an `<a-asset-item>` came back as
|
|
1877
|
+
* `http://tiles/model.glb`. Absolute server URLs always resolve, so pages hand
|
|
1878
|
+
* the viewer those instead. Standard elements are left alone (the viewer and
|
|
1879
|
+
* the runtime URL shim already handle them); only dash-tagged elements, whose
|
|
1880
|
+
* attributes the viewer cannot be trusted with, are rewritten.
|
|
1881
|
+
*/
|
|
1882
|
+
function rewriteCustomElementUrlsInDom(document, documentDirUrl) {
|
|
1883
|
+
let changed = false;
|
|
1884
|
+
const resolveOne = (url) => {
|
|
1885
|
+
const current = url.trim();
|
|
1886
|
+
if (current === "" || current.startsWith("#") || current.startsWith("?") || current.startsWith("//"))
|
|
1887
|
+
return current;
|
|
1888
|
+
// Absolute URLs (http:, data:, blob:, …) resolve as-is; root-relative ones
|
|
1889
|
+
// are covered by the server-URL rewrite.
|
|
1890
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(current) || current.startsWith("/"))
|
|
1891
|
+
return current;
|
|
1892
|
+
try {
|
|
1893
|
+
const resolved = new URL(current, documentDirUrl).href;
|
|
1894
|
+
return resolved === current ? current : resolved;
|
|
1895
|
+
}
|
|
1896
|
+
catch {
|
|
1897
|
+
return current;
|
|
1898
|
+
}
|
|
1899
|
+
};
|
|
1900
|
+
const apply = (el, attr) => {
|
|
1901
|
+
const raw = el.getAttribute(attr);
|
|
1902
|
+
if (raw === null)
|
|
1903
|
+
return;
|
|
1904
|
+
if (attr === "src") {
|
|
1905
|
+
const next = resolveOne(raw);
|
|
1906
|
+
if (next === raw.trim() || next === raw)
|
|
1907
|
+
return;
|
|
1908
|
+
el.setAttribute(attr, next);
|
|
1909
|
+
changed = true;
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
const kept = raw
|
|
1913
|
+
.split(",")
|
|
1914
|
+
.map((candidate) => candidate.trim())
|
|
1915
|
+
.filter(Boolean)
|
|
1916
|
+
.map((candidate) => {
|
|
1917
|
+
const [url, ...descriptor] = candidate.split(/\s+/);
|
|
1918
|
+
return [resolveOne(url), ...descriptor].join(" ");
|
|
1919
|
+
});
|
|
1920
|
+
const next = kept.join(", ");
|
|
1921
|
+
if (next === raw)
|
|
1922
|
+
return;
|
|
1923
|
+
el.setAttribute(attr, next);
|
|
1924
|
+
changed = true;
|
|
1925
|
+
};
|
|
1926
|
+
for (const el of document.querySelectorAll("[src],[srcset]")) {
|
|
1927
|
+
// Tag names are upper-cased in HTML documents; the dash test is case-free.
|
|
1928
|
+
if (!el.tagName.includes("-"))
|
|
1929
|
+
continue;
|
|
1930
|
+
apply(el, "src");
|
|
1931
|
+
apply(el, "srcset");
|
|
1932
|
+
}
|
|
1933
|
+
return changed;
|
|
1934
|
+
}
|
|
1136
1935
|
/**
|
|
1137
1936
|
* Returns a predicate that reports whether a root-relative path can be served
|
|
1138
1937
|
* from one of the configured asset-base local roots.
|
|
@@ -1252,10 +2051,18 @@ function buildPreviewHtml(inputAbs, assetBases, options = {}) {
|
|
|
1252
2051
|
const changed = rewriteAbsoluteUrlsInDom(document, assetBases);
|
|
1253
2052
|
if (changed)
|
|
1254
2053
|
log.trace("buildPreviewHtml: rewrote absolute URLs → virtual paths");
|
|
2054
|
+
// Same custom-element fix as the build path: the viewer mangles relative
|
|
2055
|
+
// URLs on elements it does not understand. Only applied when the caller
|
|
2056
|
+
// knows the document's directory on the server (see startPreview).
|
|
2057
|
+
const customChanged = options.documentBaseUrl === undefined || options.documentBaseUrl === null
|
|
2058
|
+
? false
|
|
2059
|
+
: rewriteCustomElementUrlsInDom(document, options.documentBaseUrl);
|
|
2060
|
+
if (customChanged)
|
|
2061
|
+
log.trace("buildPreviewHtml: resolved custom-element URLs → server URLs");
|
|
1255
2062
|
const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document);
|
|
1256
2063
|
if (dropped.length > 0)
|
|
1257
2064
|
reportDroppedRemoteRefs(dropped);
|
|
1258
|
-
if (!changed && dropped.length === 0) {
|
|
2065
|
+
if (!changed && !customChanged && dropped.length === 0) {
|
|
1259
2066
|
log.trace("buildPreviewHtml: no URL rewrites needed, using original file");
|
|
1260
2067
|
return { htmlPath: inputAbs, extraStatic, cleanup: () => undefined };
|
|
1261
2068
|
}
|
|
@@ -1302,6 +2109,10 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
|
|
|
1302
2109
|
const srvChanged = rewriteVirtualPathsToServerInDom(document, staticMapKeys, serverBaseUrl, probe);
|
|
1303
2110
|
if (srvChanged)
|
|
1304
2111
|
log.trace("prepareInputHtmlForBuild: rewrote virtual paths → server URLs");
|
|
2112
|
+
const customBase = options.documentBaseUrl ?? `${serverBaseUrl}/`;
|
|
2113
|
+
const customChanged = rewriteCustomElementUrlsInDom(document, customBase);
|
|
2114
|
+
if (customChanged)
|
|
2115
|
+
log.trace("prepareInputHtmlForBuild: resolved custom-element URLs → server URLs", { customBase });
|
|
1305
2116
|
const gone = options.unavailableUrls === undefined ? [] : dropUnavailableReferencesInDom(document, options.unavailableUrls);
|
|
1306
2117
|
const dropped = options.allowRemote ? [] : dropRemoteReferencesInDom(document, isStaticServerUrl(serverBaseUrl));
|
|
1307
2118
|
if (dropped.length > 0)
|
|
@@ -1320,7 +2131,13 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
|
|
|
1320
2131
|
injectRuntimeScriptInDom(document, { origin, documentBaseUrl, gate: options.settle ?? null, expandDetails: true });
|
|
1321
2132
|
log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
|
|
1322
2133
|
}
|
|
1323
|
-
if (!absChanged &&
|
|
2134
|
+
if (!absChanged &&
|
|
2135
|
+
!srvChanged &&
|
|
2136
|
+
!customChanged &&
|
|
2137
|
+
dropped.length === 0 &&
|
|
2138
|
+
gone.length === 0 &&
|
|
2139
|
+
options.settle == null &&
|
|
2140
|
+
!wantsRuntime) {
|
|
1324
2141
|
log.trace("prepareInputHtmlForBuild: no changes, using original file");
|
|
1325
2142
|
return { vivliostyleInput: inputAbs, cleanup: () => undefined };
|
|
1326
2143
|
}
|
|
@@ -1577,7 +2394,28 @@ function buildProgram() {
|
|
|
1577
2394
|
.option("-o, --output <file>", "Output file path", "output.pdf")
|
|
1578
2395
|
.option("--title <title>", "Document title (overrides the one in the source)")
|
|
1579
2396
|
.option("--author <author>", "Document author")
|
|
1580
|
-
.option("--
|
|
2397
|
+
.option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
|
|
2398
|
+
.option("--keywords <keywords>", "Document keywords, comma separated")
|
|
2399
|
+
.option("--language <lang>", "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'")
|
|
2400
|
+
.option("--pdfa <level>", [
|
|
2401
|
+
"Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
|
|
2402
|
+
"an OutputIntent with an embedded ICC profile (bundled sRGB unless",
|
|
2403
|
+
"--icc-profile is given) and a file identifier are written.",
|
|
2404
|
+
"Levels: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4.",
|
|
2405
|
+
"This is a label only: the content is neither converted nor checked,",
|
|
2406
|
+
"so conformance of the content is the author's responsibility."
|
|
2407
|
+
].join("\n "))
|
|
2408
|
+
.option("--pdfx <version>", [
|
|
2409
|
+
"Label the output PDF as PDF/X (ISO 15930): X-4 writes the",
|
|
2410
|
+
"identification metadata as XMP, X-1a:2003 into the information",
|
|
2411
|
+
"dictionary. Both embed the --icc-profile as the OutputIntent.",
|
|
2412
|
+
"Same label-only semantics as --pdfa."
|
|
2413
|
+
].join("\n "))
|
|
2414
|
+
.option("--icc-profile <path>", [
|
|
2415
|
+
"ICC profile embedded as the PDF output intent, e.g. a print",
|
|
2416
|
+
"provider's profile. Required for --pdfx; --pdfa defaults to the",
|
|
2417
|
+
"bundled sRGB profile."
|
|
2418
|
+
].join("\n "))
|
|
1581
2419
|
.option("--static <mapping>", [
|
|
1582
2420
|
"Map a virtual path to a local directory or file.",
|
|
1583
2421
|
"Format: /virtual/path:/absolute/local/path",
|
|
@@ -1616,8 +2454,10 @@ function buildProgram() {
|
|
|
1616
2454
|
].join("\n "))
|
|
1617
2455
|
.option("--wait-for-content [ms]", [
|
|
1618
2456
|
"Delay pagination until the page's own async work finished: no request in",
|
|
1619
|
-
"flight
|
|
1620
|
-
"
|
|
2457
|
+
"flight, no wasm compiling, no long task running and the document height",
|
|
2458
|
+
"stable for --quiet-ms (default 400). Pages with <script> wait",
|
|
2459
|
+
"automatically (deadline 10000ms); 0 disables, larger values capped at",
|
|
2460
|
+
"25000ms."
|
|
1621
2461
|
].join("\n "))
|
|
1622
2462
|
.option("--quiet-ms <ms>", "Quiet period before the layout gate opens (default 400)")
|
|
1623
2463
|
.option("--timeout <ms>", ["Give up on a page after <ms> (Vivliostyle default: 300000).", "Lower it for pages with embeds that never finish loading."].join("\n "))
|
|
@@ -1649,7 +2489,10 @@ function buildProgram() {
|
|
|
1649
2489
|
" • A local HTTP server serves the document, its assets and the Vivliostyle viewer;",
|
|
1650
2490
|
" • the browser prints that page to PDF, so canvases and iframes stay real content.",
|
|
1651
2491
|
" • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
|
|
1652
|
-
" • --asset-base localBase is also a fallback root for CSS-referenced assets."
|
|
2492
|
+
" • --asset-base localBase is also a fallback root for CSS-referenced assets.",
|
|
2493
|
+
" • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
|
|
2494
|
+
" • values read from the document or the publication manifest; language falls",
|
|
2495
|
+
" • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
|
|
1653
2496
|
].join("\n"));
|
|
1654
2497
|
}
|
|
1655
2498
|
function printHelp() {
|
|
@@ -1684,7 +2527,11 @@ async function runRender(params) {
|
|
|
1684
2527
|
...(params.canvasScale === undefined ? {} : { canvasScale: params.canvasScale }),
|
|
1685
2528
|
...(params.metaFields.title === undefined ? {} : { title: params.metaFields.title }),
|
|
1686
2529
|
...(params.metaFields.author === undefined ? {} : { author: params.metaFields.author }),
|
|
1687
|
-
...(params.metaFields.
|
|
2530
|
+
...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
|
|
2531
|
+
...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
|
|
2532
|
+
...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
|
|
2533
|
+
...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
|
|
2534
|
+
...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
|
|
1688
2535
|
};
|
|
1689
2536
|
log.trace("renderPdf request", request);
|
|
1690
2537
|
const result = await renderPdf(request);
|
|
@@ -1710,10 +2557,16 @@ function resolveInternalLogLevel(options) {
|
|
|
1710
2557
|
* hard limit is capped below that.
|
|
1711
2558
|
*/
|
|
1712
2559
|
const MAX_SETTLE_DEADLINE_MS = 25_000;
|
|
2560
|
+
/** Deadline for the automatic wait on script-driven pages (see below). */
|
|
2561
|
+
const AUTO_SETTLE_DEADLINE_MS = 10_000;
|
|
1713
2562
|
function resolveSettleGate(options) {
|
|
1714
2563
|
const raw = options.waitForContent;
|
|
1715
2564
|
if (raw === undefined || raw === false)
|
|
1716
2565
|
return null;
|
|
2566
|
+
// Explicit 0 disables the wait — including the automatic one for pages
|
|
2567
|
+
// with scripts (see resolveEffectiveSettle).
|
|
2568
|
+
if (raw === "0")
|
|
2569
|
+
return null;
|
|
1717
2570
|
const requested = typeof raw === "string" && raw !== "" ? Number.parseInt(raw, 10) : MAX_SETTLE_DEADLINE_MS;
|
|
1718
2571
|
if (!Number.isFinite(requested) || requested <= 0)
|
|
1719
2572
|
throw new Error(`Invalid --wait-for-content: "${String(raw)}"`);
|
|
@@ -1725,6 +2578,78 @@ function resolveSettleGate(options) {
|
|
|
1725
2578
|
deadlineMs: Math.min(requested, MAX_SETTLE_DEADLINE_MS)
|
|
1726
2579
|
};
|
|
1727
2580
|
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Settle gate that actually applies: an explicit `--wait-for-content` wins;
|
|
2583
|
+
* otherwise pages that run scripts wait automatically (charts, wasm, WebGL
|
|
2584
|
+
* would otherwise race pagination), static pages don't wait at all.
|
|
2585
|
+
*/
|
|
2586
|
+
function resolveEffectiveSettle(options, hasScripts) {
|
|
2587
|
+
const explicit = resolveSettleGate(options);
|
|
2588
|
+
if (explicit !== null || options.waitForContent !== undefined)
|
|
2589
|
+
return { gate: explicit, autoArmed: false };
|
|
2590
|
+
if (!hasScripts)
|
|
2591
|
+
return { gate: null, autoArmed: false };
|
|
2592
|
+
const quietRaw = options.quietMs === undefined ? 400 : Number.parseInt(options.quietMs, 10);
|
|
2593
|
+
if (!Number.isFinite(quietRaw) || quietRaw <= 0)
|
|
2594
|
+
throw new Error(`Invalid --quiet-ms: "${String(options.quietMs)}"`);
|
|
2595
|
+
return { gate: { quietMs: quietRaw, deadlineMs: AUTO_SETTLE_DEADLINE_MS }, autoArmed: true };
|
|
2596
|
+
}
|
|
2597
|
+
// ---------------------------------------------------------------------------
|
|
2598
|
+
// PDF metadata + standards labeling resolution
|
|
2599
|
+
// ---------------------------------------------------------------------------
|
|
2600
|
+
function describePdfLabel(label) {
|
|
2601
|
+
return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* `--pdfa` / `--pdfx`: mutually exclusive standards labels for the output PDF.
|
|
2605
|
+
*/
|
|
2606
|
+
function resolvePdfLabel(options) {
|
|
2607
|
+
if (options.pdfa !== undefined && options.pdfx !== undefined) {
|
|
2608
|
+
throw new Error("--pdfa and --pdfx are mutually exclusive — choose one standard label");
|
|
2609
|
+
}
|
|
2610
|
+
if (options.pdfa !== undefined)
|
|
2611
|
+
return parsePdfaLabel(options.pdfa);
|
|
2612
|
+
if (options.pdfx !== undefined)
|
|
2613
|
+
return parsePdfxLabel(options.pdfx);
|
|
2614
|
+
return undefined;
|
|
2615
|
+
}
|
|
2616
|
+
/**
|
|
2617
|
+
* `--icc-profile <path>`: the profile the OutputIntent embeds. PDF/X always
|
|
2618
|
+
* needs one; a PDF/A build without the flag embeds the bundled sRGB profile.
|
|
2619
|
+
*/
|
|
2620
|
+
function resolveIccProfile(options, label) {
|
|
2621
|
+
if (options.iccProfile !== undefined) {
|
|
2622
|
+
const path = resolve(options.iccProfile);
|
|
2623
|
+
if (!existsSync(path))
|
|
2624
|
+
throw new Error(`--icc-profile file does not exist: ${path}`);
|
|
2625
|
+
return { bytes: readFileSync(path), name: basename(path) };
|
|
2626
|
+
}
|
|
2627
|
+
if (label === undefined)
|
|
2628
|
+
return undefined;
|
|
2629
|
+
if (label.kind === "pdfx") {
|
|
2630
|
+
throw new Error(`--pdfx ${label.version} requires --icc-profile <path>: PDF/X output intents carry an ICC profile`);
|
|
2631
|
+
}
|
|
2632
|
+
return loadDefaultIccProfile();
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Document metadata for the PDF: the flags override values taken from the
|
|
2636
|
+
* input (HTML meta tags or a publication manifest); the language falls back
|
|
2637
|
+
* to "de" when no source provides one.
|
|
2638
|
+
*/
|
|
2639
|
+
function resolvePdfMetadata(options, inputAbs, htmlMode) {
|
|
2640
|
+
const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]);
|
|
2641
|
+
let derived;
|
|
2642
|
+
if (htmlMode) {
|
|
2643
|
+
derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
|
|
2644
|
+
}
|
|
2645
|
+
else if (/\.json$/i.test(inputAbs)) {
|
|
2646
|
+
derived = extractMetadataFromManifest(readFileSync(inputAbs, "utf-8"));
|
|
2647
|
+
if (derived === undefined)
|
|
2648
|
+
log.warn(`[metadata] ${inputAbs} is not a JSON publication manifest — no manifest metadata`);
|
|
2649
|
+
}
|
|
2650
|
+
log.trace("metadata (derived)", derived);
|
|
2651
|
+
return resolveMetadata(cliFields, derived);
|
|
2652
|
+
}
|
|
1728
2653
|
async function execute(options, extraArgs = []) {
|
|
1729
2654
|
log.setLevel(LOG_LEVELS[resolveInternalLogLevel(options)]);
|
|
1730
2655
|
log.trace("raw CLI options", options);
|
|
@@ -1806,9 +2731,21 @@ async function execute(options, extraArgs = []) {
|
|
|
1806
2731
|
}
|
|
1807
2732
|
const extraConfig = parseExtraArgs(extraArgs);
|
|
1808
2733
|
log.trace("extraConfig (parsed from -- args)", extraConfig);
|
|
1809
|
-
const metaFields =
|
|
2734
|
+
const metaFields = resolvePdfMetadata(options, inputAbs, htmlMode);
|
|
2735
|
+
const pdfLabel = resolvePdfLabel(options);
|
|
2736
|
+
if (pdfLabel !== undefined)
|
|
2737
|
+
log.info(`[pdf] labeling the output as ${describePdfLabel(pdfLabel)}`);
|
|
2738
|
+
if (options.iccProfile !== undefined && pdfLabel === undefined) {
|
|
2739
|
+
log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
|
|
2740
|
+
}
|
|
2741
|
+
const iccProfile = resolveIccProfile(options, pdfLabel);
|
|
1810
2742
|
const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
|
|
1811
|
-
|
|
2743
|
+
// The wait arms automatically on script-driven pages: without it, charts,
|
|
2744
|
+
// wasm and WebGL race pagination and the PDF ships half-painted content.
|
|
2745
|
+
const hasScripts = htmlMode && new JSDOM(readFileSync(inputAbs, "utf-8")).window.document.querySelector("script") !== null;
|
|
2746
|
+
const { gate: settle, autoArmed } = resolveEffectiveSettle(options, hasScripts);
|
|
2747
|
+
if (autoArmed)
|
|
2748
|
+
log.info(`[wait] auto-armed for script-driven page (deadline ${AUTO_SETTLE_DEADLINE_MS}ms, disable with --wait-for-content 0)`);
|
|
1812
2749
|
const htmlOptions = {
|
|
1813
2750
|
allowRemote: fetchMissing,
|
|
1814
2751
|
fetchMissing,
|
|
@@ -1902,7 +2839,9 @@ async function execute(options, extraArgs = []) {
|
|
|
1902
2839
|
timeoutMs: typeof extraConfig.timeout === "number" ? extraConfig.timeout : undefined,
|
|
1903
2840
|
waitForSettle: htmlOptions.settle != null,
|
|
1904
2841
|
chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
|
|
1905
|
-
canvasScale
|
|
2842
|
+
canvasScale,
|
|
2843
|
+
...(pdfLabel === undefined ? {} : { pdfLabel }),
|
|
2844
|
+
...(iccProfile === undefined ? {} : { iccProfile })
|
|
1906
2845
|
});
|
|
1907
2846
|
}
|
|
1908
2847
|
finally {
|
|
@@ -1947,7 +2886,12 @@ async function startPreview(inputAbs, assetBases, staticMap, htmlOptions, extraC
|
|
|
1947
2886
|
viewerFilePath: join(viewerLibDir, "index.html"),
|
|
1948
2887
|
log: (message) => log.info(message)
|
|
1949
2888
|
});
|
|
1950
|
-
const prepared = buildPreviewHtml(inputAbs, assetBases,
|
|
2889
|
+
const prepared = buildPreviewHtml(inputAbs, assetBases, {
|
|
2890
|
+
...htmlOptions,
|
|
2891
|
+
// The viewer is served next to the document, so custom-element URLs
|
|
2892
|
+
// resolve against the document's own directory (see siteDirectory below).
|
|
2893
|
+
documentBaseUrl: `${server.baseUrl}${siteDirectory(sitePath)}/`
|
|
2894
|
+
});
|
|
1951
2895
|
entry.localPath = prepared.htmlPath;
|
|
1952
2896
|
const viewerPageUrl = `${server.baseUrl}${siteDirectory(sitePath)}/${VIEWER_PAGE_NAME}`;
|
|
1953
2897
|
const documentUrl = `${server.baseUrl}${sitePath}`;
|
|
@@ -2033,4 +2977,4 @@ if (isDirectExecution()) {
|
|
|
2033
2977
|
});
|
|
2034
2978
|
}
|
|
2035
2979
|
|
|
2036
|
-
export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };
|
|
2980
|
+
export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveEffectiveSettle, resolveIccProfile, resolvePdfLabel, resolvePdfMetadata, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteCustomElementUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };
|