@projektemacher/vivliostyle-batch-cli 0.3.0 → 0.3.2
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 +5 -0
- package/dist/index.d.ts +19 -1
- package/dist/vivliostyle-batch-cli.js +413 -20
- package/package.json +4 -4
- package/src/metadata.ts +9 -1
- package/src/render/pdf-postprocess.ts +83 -10
- package/src/render/pdf-validate.ts +185 -0
- package/src/render/pdf.ts +56 -2
- package/src/render/srgb.icc +0 -0
- package/src/render/verapdf.ts +56 -0
- package/src/render/xmp.ts +12 -0
- package/src/vivliostyle-cli.ts +88 -10
|
@@ -11,6 +11,7 @@ import puppeteer from 'puppeteer-core';
|
|
|
11
11
|
import { PDFDocument } from 'pdf-lib';
|
|
12
12
|
import { randomUUID, randomBytes } from 'node:crypto';
|
|
13
13
|
import * as mupdf from 'mupdf';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
14
15
|
import { createRequire } from 'node:module';
|
|
15
16
|
|
|
16
17
|
// src/server.ts
|
|
@@ -365,6 +366,17 @@ function pdfDateToXmpDate(value) {
|
|
|
365
366
|
const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
|
|
366
367
|
return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
|
|
367
368
|
}
|
|
369
|
+
// The inverse of the PDF date form above: XMP Part 1, 8.2.1.2 date.
|
|
370
|
+
const XMP_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+\-]\d{2}:\d{2})$/;
|
|
371
|
+
/** Reformats an XMP date string as a PDF date; `undefined` when not one. */
|
|
372
|
+
function xmpDateToPdfDate(value) {
|
|
373
|
+
const match = XMP_DATE.exec(value);
|
|
374
|
+
if (match === null)
|
|
375
|
+
return undefined;
|
|
376
|
+
const [, year, month, day, hour, minute, second, zone] = match;
|
|
377
|
+
const offset = zone === "Z" ? "Z" : `${zone.slice(0, 3)}'${zone.slice(4, 6)}`;
|
|
378
|
+
return `D:${year}${month}${day}${hour}${minute}${second}${offset}`;
|
|
379
|
+
}
|
|
368
380
|
function xmlEscape(text) {
|
|
369
381
|
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
370
382
|
}
|
|
@@ -493,6 +505,21 @@ function createScope() {
|
|
|
493
505
|
}
|
|
494
506
|
};
|
|
495
507
|
}
|
|
508
|
+
/**
|
|
509
|
+
* The PDF version each standards label is defined against: PDF/A-1 and
|
|
510
|
+
* PDF/X-1a:2003 on PDF 1.4, PDF/X-4 on PDF 1.6, PDF/A-2 and PDF/A-3 on
|
|
511
|
+
* PDF 1.7 (ISO 32000-1) and PDF/A-4 on PDF 2.0 (ISO 32000-2).
|
|
512
|
+
*/
|
|
513
|
+
function minimumVersionForLabel(label) {
|
|
514
|
+
if (label.kind === "pdfa") {
|
|
515
|
+
if (label.part === "1")
|
|
516
|
+
return 14;
|
|
517
|
+
if (label.part === "4")
|
|
518
|
+
return 20;
|
|
519
|
+
return 17;
|
|
520
|
+
}
|
|
521
|
+
return label.version === "X-4" ? 16 : 14;
|
|
522
|
+
}
|
|
496
523
|
// The catalog /Version is written for every required version; MuPDF's wasm
|
|
497
524
|
// binding provides no API for the header version and a full save derives the
|
|
498
525
|
// header from the catalog entry (same approach as vivliostyle-cli).
|
|
@@ -508,6 +535,32 @@ function readInfoString(info, key, scope) {
|
|
|
508
535
|
const value = scope.track(info.get(key));
|
|
509
536
|
return value.isString() ? value.asString() : undefined;
|
|
510
537
|
}
|
|
538
|
+
/**
|
|
539
|
+
* Parses an explicitly given date (ISO 8601, optionally date-only, or the PDF
|
|
540
|
+
* "D:…" form) into both formats the document needs: the information
|
|
541
|
+
* dictionary date (ISO 32000-1:2008, 7.9.4) and the XMP date (XMP Part 1,
|
|
542
|
+
* 8.2.1.2). A date without offset counts as UTC.
|
|
543
|
+
*/
|
|
544
|
+
function parseExplicitDate(value, field) {
|
|
545
|
+
const trimmed = value.trim();
|
|
546
|
+
const pdfFromXmp = xmpDateToPdfDate(trimmed);
|
|
547
|
+
if (pdfFromXmp !== undefined)
|
|
548
|
+
return { pdfDate: pdfFromXmp, xmpDate: trimmed };
|
|
549
|
+
const xmpFromPdf = pdfDateToXmpDate(trimmed);
|
|
550
|
+
if (xmpFromPdf !== undefined)
|
|
551
|
+
return { pdfDate: trimmed, xmpDate: xmpFromPdf };
|
|
552
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2}))?)?(?:[Zz]|([+\-])(\d{2}):?(\d{2}))?$/.exec(trimmed);
|
|
553
|
+
if (match === null) {
|
|
554
|
+
throw new Error(`Invalid ${field} date: "${value}". Use ISO 8601, e.g. 2024-11-18T00:00:00+01:00`);
|
|
555
|
+
}
|
|
556
|
+
const [, year, month, day, hour = "00", minute = "00", second = "00", sign, offsetHour, offsetMinute] = match;
|
|
557
|
+
const offset = sign === undefined ? "Z" : `${sign}${offsetHour}'${offsetMinute}`;
|
|
558
|
+
const xmpOffset = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
|
|
559
|
+
return {
|
|
560
|
+
pdfDate: `D:${year}${month}${day}${hour}${minute}${second}${offset}`,
|
|
561
|
+
xmpDate: `${year}-${month}-${day}T${hour}:${minute}:${second}${xmpOffset}`
|
|
562
|
+
};
|
|
563
|
+
}
|
|
511
564
|
function readTrapped(info, scope) {
|
|
512
565
|
const trapped = scope.track(info.get("Trapped"));
|
|
513
566
|
return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
|
|
@@ -559,10 +612,25 @@ async function postProcessPdf(pdf, options) {
|
|
|
559
612
|
modifyDate: readInfoString(info, "ModDate", scope),
|
|
560
613
|
trapped: readTrapped(info, scope)
|
|
561
614
|
}));
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
615
|
+
let infoCreationDate = creationDate;
|
|
616
|
+
let infoModifyDate = modifyDate;
|
|
617
|
+
let createDateXmp = creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined;
|
|
618
|
+
let modifyDateXmp = modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined;
|
|
619
|
+
if (metadata.created !== undefined) {
|
|
620
|
+
const parsed = parseExplicitDate(metadata.created, "--created");
|
|
621
|
+
infoCreationDate = parsed.pdfDate;
|
|
622
|
+
createDateXmp = parsed.xmpDate;
|
|
623
|
+
}
|
|
624
|
+
if (metadata.modified !== undefined) {
|
|
625
|
+
const parsed = parseExplicitDate(metadata.modified, "--modified");
|
|
626
|
+
infoModifyDate = parsed.pdfDate;
|
|
627
|
+
modifyDateXmp = parsed.xmpDate;
|
|
628
|
+
}
|
|
629
|
+
// Acrobat's preflight requires xmp:CreateDate/MetadataDate and, with
|
|
630
|
+
// ModifyDate absent (as with backends like Firefox's cairo), falls back to
|
|
631
|
+
// the creation date — so both dates are always present in the XMP packet.
|
|
632
|
+
createDateXmp ??= toXmpDate(new Date());
|
|
633
|
+
modifyDateXmp ??= createDateXmp;
|
|
566
634
|
// ── Document information entries ────────────────────────────────────────
|
|
567
635
|
document.setMetaData("info:Producer", metadata.producer);
|
|
568
636
|
document.setMetaData("info:Creator", metadata.creator);
|
|
@@ -574,6 +642,15 @@ async function postProcessPdf(pdf, options) {
|
|
|
574
642
|
document.setMetaData("info:Subject", metadata.subject);
|
|
575
643
|
if (metadata.keywords !== undefined)
|
|
576
644
|
document.setMetaData("info:Keywords", metadata.keywords);
|
|
645
|
+
// Explicit dates override the ones the print backend wrote (setMetaData
|
|
646
|
+
// replaces the information dictionary, so these run after the entries
|
|
647
|
+
// above and every later access re-fetches its handles).
|
|
648
|
+
if (infoCreationDate !== undefined && infoCreationDate !== creationDate) {
|
|
649
|
+
document.setMetaData("info:CreationDate", infoCreationDate);
|
|
650
|
+
}
|
|
651
|
+
if (infoModifyDate !== undefined && infoModifyDate !== modifyDate) {
|
|
652
|
+
document.setMetaData("info:ModDate", infoModifyDate);
|
|
653
|
+
}
|
|
577
654
|
// ── Catalog language ────────────────────────────────────────────────────
|
|
578
655
|
const language = metadata.language;
|
|
579
656
|
if (language !== undefined && language !== "") {
|
|
@@ -628,7 +705,7 @@ async function postProcessPdf(pdf, options) {
|
|
|
628
705
|
}));
|
|
629
706
|
catalog.put("OutputIntents", [intent]);
|
|
630
707
|
});
|
|
631
|
-
setMinimumPdfVersion(document,
|
|
708
|
+
setMinimumPdfVersion(document, minimumVersionForLabel(label), scope);
|
|
632
709
|
}
|
|
633
710
|
// ── Standards identification outside the XMP packet ─────────────────────
|
|
634
711
|
if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
|
|
@@ -667,9 +744,15 @@ async function postProcessPdf(pdf, options) {
|
|
|
667
744
|
}
|
|
668
745
|
/**
|
|
669
746
|
* Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
*
|
|
747
|
+
*
|
|
748
|
+
* The profile ships unchanged from Debian's icc-profiles-free package
|
|
749
|
+
* (sources.debian.org, sRGB.icc from the "sRGB IEC61966-2.1" distribution by
|
|
750
|
+
* Hewlett-Packard): a monitor-class ("mntr") RGB profile with the embedded
|
|
751
|
+
* copyright tag, as PDF/A requires (ISO 19005-2, 6.2.3: an OutputIntent
|
|
752
|
+
* profile must be of the output or monitor device class and older than
|
|
753
|
+
* ICC v5). The ICC/HP license permits redistribution provided the file,
|
|
754
|
+
* including its embedded copyright notice tag, is not modified
|
|
755
|
+
* (https://registry.color.org/profile-library/#license).
|
|
673
756
|
*/
|
|
674
757
|
function loadDefaultIccProfile() {
|
|
675
758
|
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -681,12 +764,225 @@ function loadDefaultIccProfile() {
|
|
|
681
764
|
];
|
|
682
765
|
for (const candidate of candidates) {
|
|
683
766
|
if (existsSync(candidate)) {
|
|
684
|
-
return { bytes: readFileSync(candidate), name: "
|
|
767
|
+
return { bytes: readFileSync(candidate), name: "sRGB IEC61966-2.1" };
|
|
685
768
|
}
|
|
686
769
|
}
|
|
687
770
|
throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
|
|
688
771
|
}
|
|
689
772
|
|
|
773
|
+
// src/render/pdf-validate.ts
|
|
774
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
775
|
+
// Licensed under the MIT License.
|
|
776
|
+
/**
|
|
777
|
+
* Built-in compliance checks for standards-labeled output (PDF/A, PDF/X).
|
|
778
|
+
*
|
|
779
|
+
* veraPDF implements the full ISO rule sets; this module covers the practical
|
|
780
|
+
* subset a print backend can violate and that the post-processing step is
|
|
781
|
+
* responsible for: the PDF version of the labeled part, the XMP
|
|
782
|
+
* identification, the OutputIntent with an embedded ICC profile, the file
|
|
783
|
+
* identifier, embedded fonts and the absence of JavaScript actions.
|
|
784
|
+
* Run the verapdf binary (see verapdf.ts) when the full rule set matters.
|
|
785
|
+
*/
|
|
786
|
+
/** Human-readable label, e.g. "PDF/A-2b" or "PDF/X-4". */
|
|
787
|
+
function describeLabel(label) {
|
|
788
|
+
return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
|
|
789
|
+
}
|
|
790
|
+
const decoder = new TextDecoder("utf-8");
|
|
791
|
+
function decodeStream(stream) {
|
|
792
|
+
return decoder.decode(stream.readStream().asUint8Array());
|
|
793
|
+
}
|
|
794
|
+
/** True when the font dictionary carries one of the embedded font file keys. */
|
|
795
|
+
function hasEmbeddedFontFile(fontDescriptor) {
|
|
796
|
+
for (const key of ["FontFile", "FontFile2", "FontFile3"]) {
|
|
797
|
+
if (fontDescriptor.get(key).isStream())
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
/** Checks a single font dictionary; returns a violation detail or null. */
|
|
803
|
+
function checkFont(font) {
|
|
804
|
+
const subtype = font.get("Subtype").asName();
|
|
805
|
+
if (subtype === "Type3") {
|
|
806
|
+
// PDF/A (parts 1-3) requires the character procedures of a Type3 font to
|
|
807
|
+
// be embedded streams; PDF/A-4 additionally allows them in the page.
|
|
808
|
+
return font.get("CharProcs").isDictionary() || font.get("CharProcs").isStream() ? null : "Type3 font without CharProcs";
|
|
809
|
+
}
|
|
810
|
+
let descriptor = font.get("FontDescriptor");
|
|
811
|
+
if (subtype === "Type0") {
|
|
812
|
+
const descendants = font.get("DescendantFonts");
|
|
813
|
+
if (!descendants.isArray())
|
|
814
|
+
return "Type0 font without DescendantFonts";
|
|
815
|
+
descriptor = descendants.get(0).resolve().get("FontDescriptor");
|
|
816
|
+
}
|
|
817
|
+
else if (subtype === "CIDFontType0" || subtype === "CIDFontType2") {
|
|
818
|
+
descriptor = font.get("FontDescriptor");
|
|
819
|
+
}
|
|
820
|
+
if (!descriptor.isDictionary())
|
|
821
|
+
return `${subtype} font without FontDescriptor`;
|
|
822
|
+
if (!hasEmbeddedFontFile(descriptor))
|
|
823
|
+
return `${subtype} font without embedded FontFile`;
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
function validateLabeledPdf(pdf, label) {
|
|
827
|
+
const violations = [];
|
|
828
|
+
const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
|
|
829
|
+
try {
|
|
830
|
+
const trailer = document.getTrailer();
|
|
831
|
+
const catalog = trailer.get("Root");
|
|
832
|
+
// ── PDF version of the labeled part ───────────────────────────────────
|
|
833
|
+
const minimumVersion = minimumVersionForLabel(label);
|
|
834
|
+
if (document.getVersion() < minimumVersion) {
|
|
835
|
+
violations.push({
|
|
836
|
+
check: "pdf-version",
|
|
837
|
+
detail: `document is PDF ${Math.trunc(document.getVersion() / 10)}.${document.getVersion() % 10}, ${describeLabel(label)} requires at least ${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
// ── XMP metadata stream with the standards identification ─────────────
|
|
841
|
+
// get() follows indirect references already; resolve() would hide the
|
|
842
|
+
// stream-ness of the handle (see the post-processing test comment).
|
|
843
|
+
const metadataStream = catalog.get("Metadata");
|
|
844
|
+
let xmp = "";
|
|
845
|
+
if (!metadataStream.isStream()) {
|
|
846
|
+
violations.push({ check: "xmp-metadata", detail: "catalog has no Metadata stream" });
|
|
847
|
+
}
|
|
848
|
+
else {
|
|
849
|
+
xmp = decodeStream(metadataStream);
|
|
850
|
+
if (label.kind === "pdfa") {
|
|
851
|
+
if (!xmp.includes(`<pdfaid:part>${label.part}</pdfaid:part>`)) {
|
|
852
|
+
violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:part>${label.part}` });
|
|
853
|
+
}
|
|
854
|
+
if (label.conformance !== undefined &&
|
|
855
|
+
!xmp.includes(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`)) {
|
|
856
|
+
violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:conformance>${label.conformance.toUpperCase()}` });
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
else if (label.version === "X-4" && !xmp.includes("<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>")) {
|
|
860
|
+
violations.push({ check: "xmp-identification", detail: "XMP is missing the PDF/X-4 GTS_PDFXVersion" });
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
// ── OutputIntent with an embedded ICC profile ──────────────────────────
|
|
864
|
+
if (label.kind === "pdfa" || label.version === "X-4") {
|
|
865
|
+
const intents = catalog.get("OutputIntents");
|
|
866
|
+
if (!intents.isArray() || intents.length < 1) {
|
|
867
|
+
violations.push({ check: "output-intent", detail: "catalog has no OutputIntents array" });
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
const intent = intents.get(0);
|
|
871
|
+
const expectedS = label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX";
|
|
872
|
+
if (!intent.get("S").asName()?.startsWith(expectedS)) {
|
|
873
|
+
violations.push({ check: "output-intent", detail: `OutputIntent /S is not ${expectedS}` });
|
|
874
|
+
}
|
|
875
|
+
// MuPDF's PDFObject.resolve() does not surface stream-ness for
|
|
876
|
+
// indirect refs, so the embedded profile is checked through its
|
|
877
|
+
// stream data (same approach as the post-processing tests).
|
|
878
|
+
let profileReadable = false;
|
|
879
|
+
try {
|
|
880
|
+
profileReadable = intent.get("DestOutputProfile").readStream().asUint8Array().length > 0;
|
|
881
|
+
}
|
|
882
|
+
catch {
|
|
883
|
+
profileReadable = false;
|
|
884
|
+
}
|
|
885
|
+
if (!profileReadable) {
|
|
886
|
+
violations.push({ check: "output-intent", detail: "OutputIntent has no embedded DestOutputProfile" });
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
// ── File identifier (required for PDF/A and PDF/X) ──────────────────────
|
|
891
|
+
const fileId = trailer.get("ID");
|
|
892
|
+
if (!fileId.isArray() || fileId.length < 2) {
|
|
893
|
+
violations.push({ check: "file-identifier", detail: "trailer /ID pair missing" });
|
|
894
|
+
}
|
|
895
|
+
// ── Fonts embedded ──────────────────────────────────────────────────────
|
|
896
|
+
const pageCount = document.countPages();
|
|
897
|
+
for (let index = 0; index < pageCount; index++) {
|
|
898
|
+
const page = document.loadPage(index);
|
|
899
|
+
try {
|
|
900
|
+
const fonts = page.getObject().get("Resources").resolve().get("Font");
|
|
901
|
+
if (!fonts.isDictionary())
|
|
902
|
+
continue;
|
|
903
|
+
fonts.forEach((fontRef) => {
|
|
904
|
+
const font = fontRef.resolve();
|
|
905
|
+
if (!font.isDictionary())
|
|
906
|
+
return;
|
|
907
|
+
const failure = checkFont(font);
|
|
908
|
+
if (failure !== null)
|
|
909
|
+
violations.push({ check: "font-embedded", detail: `page ${index + 1}: ${failure}` });
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
finally {
|
|
913
|
+
page.destroy();
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
// ── No JavaScript actions ────────────────────────────────────────────────
|
|
917
|
+
const names = catalog.get("Names");
|
|
918
|
+
if (names.isDictionary() && names.get("JavaScript").isDictionary()) {
|
|
919
|
+
violations.push({ check: "no-javascript", detail: "document name tree contains JavaScript actions" });
|
|
920
|
+
}
|
|
921
|
+
const openAction = catalog.get("OpenAction");
|
|
922
|
+
if (openAction.isDictionary() && openAction.get("S").asName() === "JavaScript") {
|
|
923
|
+
violations.push({ check: "no-javascript", detail: "OpenAction is a JavaScript action" });
|
|
924
|
+
}
|
|
925
|
+
// ── Information dictionary / XMP consistency ────────────────────────────
|
|
926
|
+
const info = trailer.get("Info");
|
|
927
|
+
if (info.isDictionary()) {
|
|
928
|
+
if (info.get("Title").isString() && xmp !== "" && !xmp.includes("<dc:title>")) {
|
|
929
|
+
violations.push({ check: "metadata-consistency", detail: "information dictionary has a Title but the XMP packet lacks dc:title" });
|
|
930
|
+
}
|
|
931
|
+
if (info.get("Author").isString() && xmp !== "" && !xmp.includes("<dc:creator>")) {
|
|
932
|
+
violations.push({
|
|
933
|
+
check: "metadata-consistency",
|
|
934
|
+
detail: "information dictionary has an Author but the XMP packet lacks dc:creator"
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return violations;
|
|
939
|
+
}
|
|
940
|
+
finally {
|
|
941
|
+
document.destroy();
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// src/render/verapdf.ts
|
|
946
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
947
|
+
// Licensed under the MIT License.
|
|
948
|
+
/**
|
|
949
|
+
* Optional pass-through to the verapdf binary (https://verapdf.org/), which
|
|
950
|
+
* implements the full ISO conformance rule sets for PDF/A and PDF/X. The
|
|
951
|
+
* binary must be on the PATH; it is never bundled because it needs a Java
|
|
952
|
+
* runtime. Only invoked on explicit request (--verapdf).
|
|
953
|
+
*/
|
|
954
|
+
/** Maps a standards label onto a veraPDF --flavour value. */
|
|
955
|
+
function veraPdfFlavour(label) {
|
|
956
|
+
if (label.kind === "pdfa") {
|
|
957
|
+
return label.part === "4" ? "4" : `${label.part}${label.conformance ?? ""}`;
|
|
958
|
+
}
|
|
959
|
+
return label.version === "X-4" ? "X-4" : "X-1a";
|
|
960
|
+
}
|
|
961
|
+
function runVeraPdf(pdfPath, label) {
|
|
962
|
+
const flavour = veraPdfFlavour(label);
|
|
963
|
+
let result;
|
|
964
|
+
try {
|
|
965
|
+
result = spawnSync("verapdf", ["--flavour", flavour, "--format", "text", pdfPath], {
|
|
966
|
+
encoding: "utf-8",
|
|
967
|
+
timeout: 120_000
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
catch (error) {
|
|
971
|
+
return { ran: false, reason: error instanceof Error ? error.message : String(error) };
|
|
972
|
+
}
|
|
973
|
+
if (result.error !== undefined) {
|
|
974
|
+
const code = result.error.code;
|
|
975
|
+
return {
|
|
976
|
+
ran: false,
|
|
977
|
+
reason: code === "ENOENT" ? "verapdf binary not found on PATH" : String(result.error)
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
981
|
+
const stderr = typeof result.stderr === "string" ? result.stderr : "";
|
|
982
|
+
const output = `${stdout}${stderr}`.slice(0, 4000);
|
|
983
|
+
return { ran: true, passed: /\bPASS\b/.test(stdout), exitCode: result.status, output };
|
|
984
|
+
}
|
|
985
|
+
|
|
690
986
|
// src/render/pdf.ts
|
|
691
987
|
// Copyright (c) 2026 Christian Mahnke
|
|
692
988
|
// Licensed under the MIT License.
|
|
@@ -722,6 +1018,8 @@ function pdfMetadata(request) {
|
|
|
722
1018
|
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
723
1019
|
...(request.keywords === undefined ? {} : { keywords: request.keywords }),
|
|
724
1020
|
...(request.language === undefined ? {} : { language: request.language }),
|
|
1021
|
+
...(request.created === undefined ? {} : { created: request.created }),
|
|
1022
|
+
...(request.modified === undefined ? {} : { modified: request.modified }),
|
|
725
1023
|
creator: TOOL_IDENTITY,
|
|
726
1024
|
producer: TOOL_IDENTITY
|
|
727
1025
|
};
|
|
@@ -1032,14 +1330,33 @@ async function renderPdf(request) {
|
|
|
1032
1330
|
polling: 500
|
|
1033
1331
|
});
|
|
1034
1332
|
if (request.waitForSettle === true) {
|
|
1333
|
+
// The gate image keeps the viewer's document processing pending until
|
|
1334
|
+
// the settle fires; only then does vivliostyle drain the deferred and
|
|
1335
|
+
// module scripts it queued (end-of-document execution) and dispatch
|
|
1336
|
+
// DOMContentLoaded. Pages that depend on those late globals flip
|
|
1337
|
+
// __vivReady after the gate settled, so hold print briefly for them.
|
|
1338
|
+
const POST_SETTLE_READY_GRACE_MS = 2000;
|
|
1339
|
+
let settledAt = -1;
|
|
1035
1340
|
const handle = await page.waitForFunction(() => {
|
|
1036
1341
|
const settleState = window.__vivSettle;
|
|
1037
1342
|
// Pages with mocked/measured async work set __vivReady when painted;
|
|
1038
1343
|
// Vivliostyle re-runs document scripts in the viewer context, so both
|
|
1039
1344
|
// live on the same window the renderer polls here.
|
|
1040
|
-
const
|
|
1041
|
-
if (
|
|
1345
|
+
const readyState = window.__vivReady;
|
|
1346
|
+
if (readyState === true)
|
|
1042
1347
|
return { reason: "ready", at: 0 };
|
|
1348
|
+
// An explicit not-ready beats a settled gate: quietness alone must
|
|
1349
|
+
// not print the pre-paint DOM (async tails emit no network signal).
|
|
1350
|
+
if (readyState === false) {
|
|
1351
|
+
if (settleState?.done === true) {
|
|
1352
|
+
if (settledAt < 0)
|
|
1353
|
+
settledAt = Date.now();
|
|
1354
|
+
if (Date.now() - settledAt >= POST_SETTLE_READY_GRACE_MS) {
|
|
1355
|
+
return { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 };
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
return false;
|
|
1359
|
+
}
|
|
1043
1360
|
return settleState?.done === true ? { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 } : false;
|
|
1044
1361
|
}, { polling: 200, timeout: timeoutMs });
|
|
1045
1362
|
const state = (await handle.jsonValue());
|
|
@@ -1074,8 +1391,29 @@ async function renderPdf(request) {
|
|
|
1074
1391
|
...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
|
|
1075
1392
|
...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
|
|
1076
1393
|
});
|
|
1394
|
+
if (request.pdfLabel !== undefined && request.validate !== false) {
|
|
1395
|
+
const violations = validateLabeledPdf(stamped, request.pdfLabel);
|
|
1396
|
+
if (violations.length > 0) {
|
|
1397
|
+
throw new Error(`${describeLabel(request.pdfLabel)} label failed validation, refusing to write a non-conforming output:\n` +
|
|
1398
|
+
violations.map((violation) => ` - ${violation.check}: ${violation.detail}`).join("\n"));
|
|
1399
|
+
}
|
|
1400
|
+
log.info(`[pdf] built-in ${describeLabel(request.pdfLabel)} validation passed`);
|
|
1401
|
+
}
|
|
1077
1402
|
mkdirSync(dirname(request.output), { recursive: true });
|
|
1078
1403
|
writeFileSync(request.output, stamped);
|
|
1404
|
+
if (request.verapdf === true && request.pdfLabel !== undefined) {
|
|
1405
|
+
const vera = runVeraPdf(request.output, request.pdfLabel);
|
|
1406
|
+
if (!vera.ran) {
|
|
1407
|
+
throw new Error(`--verapdf was requested, but veraPDF could not be run: ${vera.reason}. ` +
|
|
1408
|
+
"Install veraPDF (https://verapdf.org/, requires Java) or drop --verapdf.");
|
|
1409
|
+
}
|
|
1410
|
+
else if (vera.passed !== true) {
|
|
1411
|
+
throw new Error(`verapdf reports ${describeLabel(request.pdfLabel)} violations (exit ${vera.exitCode ?? "n/a"}):\n${vera.output}`);
|
|
1412
|
+
}
|
|
1413
|
+
else {
|
|
1414
|
+
log.info(`[pdf] verapdf reports ${describeLabel(request.pdfLabel)} conformance: PASS`);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1079
1417
|
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
1080
1418
|
return { output: request.output, bytes: stamped.length, pageCount, settle };
|
|
1081
1419
|
}
|
|
@@ -1121,7 +1459,9 @@ function fileURLOfSelf() {
|
|
|
1121
1459
|
const DEFAULT_LANGUAGE = "de";
|
|
1122
1460
|
/**
|
|
1123
1461
|
* Extracts metadata from the input document: <title>, the usual
|
|
1124
|
-
* author/description/keywords meta tags
|
|
1462
|
+
* author/description/keywords meta tags, the creation/modification dates
|
|
1463
|
+
* (dcterms, falling back to the plain date meta tag) and the document
|
|
1464
|
+
* language.
|
|
1125
1465
|
*/
|
|
1126
1466
|
function extractMetadataFromDocument(document) {
|
|
1127
1467
|
const title = document.querySelector("title")?.textContent?.trim();
|
|
@@ -1139,6 +1479,8 @@ function extractMetadataFromDocument(document) {
|
|
|
1139
1479
|
...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
|
|
1140
1480
|
...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
|
|
1141
1481
|
...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
|
|
1482
|
+
...optional(metaContent(["dcterms.created", "dc.date", "date"]), (value) => ({ created: value })),
|
|
1483
|
+
...optional(metaContent(["dcterms.modified", "dc.date.modified", "modified"]), (value) => ({ modified: value })),
|
|
1142
1484
|
...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
|
|
1143
1485
|
language: value
|
|
1144
1486
|
}))
|
|
@@ -1339,11 +1681,12 @@ function buildSettleGateImage(origin) {
|
|
|
1339
1681
|
function buildRuntimeScript(options) {
|
|
1340
1682
|
const { origin, documentBaseUrl, gate } = options;
|
|
1341
1683
|
const expandDetails = options.expandDetails === true ? EXPAND_DETAILS_SNIPPET : "";
|
|
1684
|
+
const mappedOrigins = JSON.stringify(options.mappedOrigins ?? []);
|
|
1342
1685
|
// Vivliostyle paginates incrementally, so collapsed content has to be opened
|
|
1343
1686
|
// again while it lays the document out, not just once up front.
|
|
1344
1687
|
const expandDetailsTick = options.expandDetails === true ? "expandDetails(document);" : "";
|
|
1345
1688
|
return `(function(){
|
|
1346
|
-
var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)};
|
|
1689
|
+
var ORIGIN=${JSON.stringify(origin)},BASE=${JSON.stringify(documentBaseUrl)},MAPPED_ORIGINS=${mappedOrigins};
|
|
1347
1690
|
var QUIET=${gate?.quietMs ?? 400},DEADLINE=${gate?.deadlineMs ?? 10000},FRAME_GRACE=3000;
|
|
1348
1691
|
var pending=0,frames=0,last=0,mutations=0,done=false,longtasks=0;
|
|
1349
1692
|
// Force preserveDrawingBuffer on every WebGL context the page creates:
|
|
@@ -1384,7 +1727,13 @@ var state=window.__vivSettle={done:false,reason:null,at:0,pending:0,frames:0,mut
|
|
|
1384
1727
|
function fix(u){
|
|
1385
1728
|
if(typeof u!=="string"||u==="")return u;
|
|
1386
1729
|
if(u.slice(0,2)==="//"||u.charAt(0)==="#"||u.charAt(0)==="?")return u;
|
|
1387
|
-
if(/^[a-z][a-z0-9+.-]*:/i.test(u))
|
|
1730
|
+
if(/^[a-z][a-z0-9+.-]*:/i.test(u)){
|
|
1731
|
+
try{
|
|
1732
|
+
var mu=new URL(u);
|
|
1733
|
+
if(MAPPED_ORIGINS.indexOf(mu.origin)>=0)return ORIGIN+mu.pathname+mu.search+mu.hash;
|
|
1734
|
+
}catch(e){}
|
|
1735
|
+
return u;
|
|
1736
|
+
}
|
|
1388
1737
|
return u.charAt(0)==="/"?ORIGIN+u:BASE+u;
|
|
1389
1738
|
}
|
|
1390
1739
|
|
|
@@ -1502,6 +1851,10 @@ last=performance.now();
|
|
|
1502
1851
|
// Deterministic pages (charts, WebGL, OSD fixtures) set __vivReady when
|
|
1503
1852
|
// painted instead of making the gate guess from network quietness. Shader
|
|
1504
1853
|
// compile and tile decode finish after the last fetch, so readiness wins.
|
|
1854
|
+
// An explicit __vivReady=false holds the quiet path too: async tails (module
|
|
1855
|
+
// imports, wasm, deferred timers) emit no network signal, so quietness alone
|
|
1856
|
+
// would settle on the pre-paint DOM. The deadline above still bounds it.
|
|
1857
|
+
if(window.__vivReady===false){setTimeout(check,50);return;}
|
|
1505
1858
|
if(window.__vivReady===true&&pending===0&&frames===0){signal("ready");return;}
|
|
1506
1859
|
if(pending===0&&frames===0&&now-last>=QUIET){signal("quiet");return;}
|
|
1507
1860
|
setTimeout(check,50);
|
|
@@ -2128,7 +2481,13 @@ function prepareInputHtmlForBuild(inputAbs, assetBases, staticMap, serverBaseUrl
|
|
|
2128
2481
|
const origin = options.shimOrigin ?? serverBaseUrl;
|
|
2129
2482
|
const documentBaseUrl = options.documentBaseUrl ?? `${origin}/`;
|
|
2130
2483
|
// Only the PDF run expands `<details>`; the preview stays interactive.
|
|
2131
|
-
injectRuntimeScriptInDom(document, {
|
|
2484
|
+
injectRuntimeScriptInDom(document, {
|
|
2485
|
+
origin,
|
|
2486
|
+
documentBaseUrl,
|
|
2487
|
+
gate: options.settle ?? null,
|
|
2488
|
+
mappedOrigins: options.mappedOrigins ?? [],
|
|
2489
|
+
expandDetails: true
|
|
2490
|
+
});
|
|
2132
2491
|
log.trace("prepareInputHtmlForBuild: injected runtime script", { origin, documentBaseUrl, gate: options.settle });
|
|
2133
2492
|
}
|
|
2134
2493
|
if (!absChanged &&
|
|
@@ -2397,6 +2756,8 @@ function buildProgram() {
|
|
|
2397
2756
|
.option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
|
|
2398
2757
|
.option("--keywords <keywords>", "Document keywords, comma separated")
|
|
2399
2758
|
.option("--language <lang>", "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'")
|
|
2759
|
+
.option("--created <date>", "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")
|
|
2760
|
+
.option("--modified <date>", "Document modification date (ISO 8601). Taken from the document's dcterms.modified meta tag when omitted")
|
|
2400
2761
|
.option("--pdfa <level>", [
|
|
2401
2762
|
"Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
|
|
2402
2763
|
"an OutputIntent with an embedded ICC profile (bundled sRGB unless",
|
|
@@ -2410,6 +2771,15 @@ function buildProgram() {
|
|
|
2410
2771
|
"identification metadata as XMP, X-1a:2003 into the information",
|
|
2411
2772
|
"dictionary. Both embed the --icc-profile as the OutputIntent.",
|
|
2412
2773
|
"Same label-only semantics as --pdfa."
|
|
2774
|
+
].join("\n "))
|
|
2775
|
+
.option("--no-validate", [
|
|
2776
|
+
"Skip the built-in compliance checks run for --pdfa/--pdfx output:",
|
|
2777
|
+
"PDF version of the labeled part, XMP identification, OutputIntent,",
|
|
2778
|
+
"file identifier, embedded fonts and the absence of JavaScript."
|
|
2779
|
+
].join("\n "))
|
|
2780
|
+
.option("--verapdf", [
|
|
2781
|
+
"Additionally run the verapdf binary (must be on the PATH) against the",
|
|
2782
|
+
"output and fail the build on full ISO rule-set violations."
|
|
2413
2783
|
].join("\n "))
|
|
2414
2784
|
.option("--icc-profile <path>", [
|
|
2415
2785
|
"ICC profile embedded as the PDF output intent, e.g. a print",
|
|
@@ -2490,9 +2860,11 @@ function buildProgram() {
|
|
|
2490
2860
|
" • the browser prints that page to PDF, so canvases and iframes stay real content.",
|
|
2491
2861
|
" • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
|
|
2492
2862
|
" • --asset-base localBase is also a fallback root for CSS-referenced assets.",
|
|
2493
|
-
" • PDF metadata (--title/--author/--subject/--keywords/--language)
|
|
2863
|
+
" • PDF metadata (--title/--author/--subject/--keywords/--language/--created/--modified)",
|
|
2494
2864
|
" • values read from the document or the publication manifest; language falls",
|
|
2495
|
-
" • back to 'de'. --pdfa/--pdfx label the output
|
|
2865
|
+
" • back to 'de'. --pdfa/--pdfx label the output; the built-in validation",
|
|
2866
|
+
" • checks the practical subset (--no-validate skips it) and --verapdf runs",
|
|
2867
|
+
" • the full ISO rule set through the verapdf binary."
|
|
2496
2868
|
].join("\n"));
|
|
2497
2869
|
}
|
|
2498
2870
|
function printHelp() {
|
|
@@ -2530,8 +2902,12 @@ async function runRender(params) {
|
|
|
2530
2902
|
...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
|
|
2531
2903
|
...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
|
|
2532
2904
|
...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
|
|
2905
|
+
...(params.metaFields.created === undefined ? {} : { created: params.metaFields.created }),
|
|
2906
|
+
...(params.metaFields.modified === undefined ? {} : { modified: params.metaFields.modified }),
|
|
2533
2907
|
...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
|
|
2534
|
-
...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
|
|
2908
|
+
...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name }),
|
|
2909
|
+
validate: params.validate,
|
|
2910
|
+
...(params.verapdf === undefined ? {} : { verapdf: params.verapdf })
|
|
2535
2911
|
};
|
|
2536
2912
|
log.trace("renderPdf request", request);
|
|
2537
2913
|
const result = await renderPdf(request);
|
|
@@ -2637,7 +3013,15 @@ function resolveIccProfile(options, label) {
|
|
|
2637
3013
|
* to "de" when no source provides one.
|
|
2638
3014
|
*/
|
|
2639
3015
|
function resolvePdfMetadata(options, inputAbs, htmlMode) {
|
|
2640
|
-
const cliFields = pickDefinedStrings(options, [
|
|
3016
|
+
const cliFields = pickDefinedStrings(options, [
|
|
3017
|
+
"title",
|
|
3018
|
+
"author",
|
|
3019
|
+
"subject",
|
|
3020
|
+
"keywords",
|
|
3021
|
+
"language",
|
|
3022
|
+
"created",
|
|
3023
|
+
"modified"
|
|
3024
|
+
]);
|
|
2641
3025
|
let derived;
|
|
2642
3026
|
if (htmlMode) {
|
|
2643
3027
|
derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
|
|
@@ -2738,6 +3122,9 @@ async function execute(options, extraArgs = []) {
|
|
|
2738
3122
|
if (options.iccProfile !== undefined && pdfLabel === undefined) {
|
|
2739
3123
|
log.warn("[pdf] --icc-profile has no effect without --pdfa or --pdfx");
|
|
2740
3124
|
}
|
|
3125
|
+
if (options.verapdf === true && pdfLabel === undefined) {
|
|
3126
|
+
log.warn("[pdf] --verapdf has no effect without --pdfa or --pdfx");
|
|
3127
|
+
}
|
|
2741
3128
|
const iccProfile = resolveIccProfile(options, pdfLabel);
|
|
2742
3129
|
const fetchMissing = options.fetchMissing === true || options.allowRemote === true;
|
|
2743
3130
|
// The wait arms automatically on script-driven pages: without it, charts,
|
|
@@ -2751,6 +3138,10 @@ async function execute(options, extraArgs = []) {
|
|
|
2751
3138
|
fetchMissing,
|
|
2752
3139
|
dumpDir: options.dumpHtml ?? null,
|
|
2753
3140
|
settle,
|
|
3141
|
+
// Page scripts fetch their data from the mapped origins (the blog's
|
|
3142
|
+
// sparql/graph components); route those to the static server so builds
|
|
3143
|
+
// stay deterministic instead of hitting the live site.
|
|
3144
|
+
mappedOrigins: [...new Set(assetBases.map((base) => new URL(base.urlBase).origin))],
|
|
2754
3145
|
...(typeof extraConfig.css === "string" ? { css: extraConfig.css } : {}),
|
|
2755
3146
|
...(typeof extraConfig.userStyle === "string" ? { userStyle: extraConfig.userStyle } : {})
|
|
2756
3147
|
};
|
|
@@ -2841,7 +3232,9 @@ async function execute(options, extraArgs = []) {
|
|
|
2841
3232
|
chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
|
|
2842
3233
|
canvasScale,
|
|
2843
3234
|
...(pdfLabel === undefined ? {} : { pdfLabel }),
|
|
2844
|
-
...(iccProfile === undefined ? {} : { iccProfile })
|
|
3235
|
+
...(iccProfile === undefined ? {} : { iccProfile }),
|
|
3236
|
+
validate: options.validate !== false,
|
|
3237
|
+
...(options.verapdf === true ? { verapdf: true } : {})
|
|
2845
3238
|
});
|
|
2846
3239
|
}
|
|
2847
3240
|
finally {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@projektemacher/vivliostyle-batch-cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A vivliostyle-cli with more options for batch processing",
|
|
6
6
|
"bin": {
|
|
@@ -46,16 +46,16 @@
|
|
|
46
46
|
"echarts": "^6.1.0",
|
|
47
47
|
"eslint": "^10.15.0",
|
|
48
48
|
"globals": "^17.14.0",
|
|
49
|
-
"marked": "^18.2.
|
|
49
|
+
"marked": "^18.2.1",
|
|
50
50
|
"openseadragon": "^6.1.1",
|
|
51
51
|
"prettier": "^3.10.1",
|
|
52
52
|
"rimraf": "^6.1.4",
|
|
53
|
-
"rollup": "^4.68.
|
|
53
|
+
"rollup": "^4.68.4",
|
|
54
54
|
"rollup-plugin-dts": "^6.5.1",
|
|
55
55
|
"three": "^0.187.0",
|
|
56
56
|
"tslib": "^2.9.1",
|
|
57
57
|
"typescript": "^6.0.3",
|
|
58
|
-
"typescript-eslint": "^8.
|
|
58
|
+
"typescript-eslint": "^8.73.0",
|
|
59
59
|
"vite": "^8.3.8",
|
|
60
60
|
"vitest": "^5.1.0"
|
|
61
61
|
},
|