@projektemacher/vivliostyle-batch-cli 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ // src/metadata.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
6
+ /**
7
+ * Document metadata for the PDF information dictionary and XMP packet:
8
+ * extraction from the input (HTML document or publication manifest) and
9
+ * resolution against the CLI flags.
10
+ *
11
+ * Precedence: CLI flags > publication manifest > document > defaults.
12
+ * The only default is the language tag, which falls back to "de" when
13
+ * neither the flags nor the input provide one.
14
+ */
15
+
16
+ import type { PdfAConformance, PdfAIdentification, PdfAPart, PdfXIdentification } from "./render/xmp.js";
17
+
18
+ /** Metadata fields shared by every source (document, manifest, CLI flags). */
19
+ export type DocumentMetadata = {
20
+ title?: string;
21
+ author?: string;
22
+ subject?: string;
23
+ keywords?: string;
24
+ language?: string;
25
+ };
26
+
27
+ /** Language tag assumed when no source provides one (project contract). */
28
+ export const DEFAULT_LANGUAGE = "de";
29
+
30
+ /**
31
+ * Extracts metadata from the input document: <title>, the usual
32
+ * author/description/keywords meta tags and the document language.
33
+ */
34
+ export function extractMetadataFromDocument(document: Document): DocumentMetadata {
35
+ const title = document.querySelector("title")?.textContent?.trim();
36
+ const metaContent = (names: readonly string[]): string | undefined => {
37
+ for (const name of names) {
38
+ const element = document.querySelector(`meta[name="${name}" i]`) ?? document.querySelector(`meta[http-equiv="${name}" i]`);
39
+ const content = element?.getAttribute("content")?.trim();
40
+ if (content !== undefined && content !== "") return content;
41
+ }
42
+ return undefined;
43
+ };
44
+ return {
45
+ ...(title === undefined || title === "" ? {} : { title }),
46
+ ...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
47
+ ...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
48
+ ...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
49
+ ...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
50
+ language: value
51
+ }))
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Extracts metadata from a publication manifest (W3C Web Publication
57
+ * Manifest shape): title, author, description, keywords and language.
58
+ * Returns undefined when the text is not a JSON object.
59
+ */
60
+ export function extractMetadataFromManifest(text: string): DocumentMetadata | undefined {
61
+ let manifest: unknown;
62
+ try {
63
+ manifest = JSON.parse(text);
64
+ } catch {
65
+ return undefined;
66
+ }
67
+ if (manifest === null || typeof manifest !== "object") return undefined;
68
+ const record = manifest as Record<string, unknown>;
69
+ return {
70
+ ...optional(asString(record.title), (value) => ({ title: value })),
71
+ ...optional(asAuthorList(record.author), (value) => ({ author: value })),
72
+ ...optional(asString(record.description), (value) => ({ subject: value })),
73
+ ...optional(asStringList(record.keywords, ", "), (value) => ({ keywords: value })),
74
+ ...optional(asStringList(record.language ?? record.inLanguage, " "), (value) => ({ language: value }))
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Merges the sources: the CLI fields win over the extracted ones, and the
80
+ * language falls back to the project default.
81
+ */
82
+ export function resolveMetadata(cli: DocumentMetadata, derived?: DocumentMetadata): DocumentMetadata & { language: string } {
83
+ const merged: DocumentMetadata = { ...derived, ...definedEntries(cli) };
84
+ if (merged.language === undefined || merged.language === "") {
85
+ merged.language = DEFAULT_LANGUAGE;
86
+ }
87
+ return merged as DocumentMetadata & { language: string };
88
+ }
89
+
90
+ /** Parses a `--pdfa` level like `2b`; part 4 takes no conformance level. */
91
+ export function parsePdfaLabel(value: string): PdfAIdentification {
92
+ const match = /^([1-4])([abu])?$/i.exec(value.trim());
93
+ if (match === null) {
94
+ throw new Error(`Invalid --pdfa level: "${value}". Allowed: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4`);
95
+ }
96
+ const part = match[1] as PdfAPart;
97
+ const conformance = match[2]?.toLowerCase() as PdfAConformance | undefined;
98
+ if (part === "4" && conformance !== undefined) {
99
+ throw new Error(`PDF/A-4 does not take a conformance level: "${value}". Use --pdfa 4`);
100
+ }
101
+ if (part !== "4" && conformance === undefined) {
102
+ throw new Error(`Missing PDF/A conformance level: "${value}". Use e.g. --pdfa 2b`);
103
+ }
104
+ return { kind: "pdfa", part, ...(conformance === undefined ? {} : { conformance }) };
105
+ }
106
+
107
+ /** Parses a `--pdfx` version; `X-1a` is accepted as shorthand for 2003. */
108
+ export function parsePdfxLabel(value: string): PdfXIdentification {
109
+ const normalized = value.trim();
110
+ if (normalized === "X-4") return { kind: "pdfx", version: "X-4" };
111
+ if (normalized === "X-1a" || normalized === "X-1a:2003") return { kind: "pdfx", version: "X-1a:2003" };
112
+ throw new Error(`Invalid --pdfx version: "${value}". Allowed: X-4, X-1a:2003`);
113
+ }
114
+
115
+ // ---------------------------------------------------------------------------
116
+ // Helpers
117
+ // ---------------------------------------------------------------------------
118
+
119
+ function definedEntries(source: DocumentMetadata): DocumentMetadata {
120
+ const entries: DocumentMetadata = {};
121
+ for (const [key, value] of Object.entries(source)) {
122
+ if (value !== undefined && value !== "") (entries as Record<string, unknown>)[key] = value;
123
+ }
124
+ return entries;
125
+ }
126
+
127
+ function optional<T>(value: T | undefined | null, wrap: (value: T) => DocumentMetadata): DocumentMetadata {
128
+ return value === undefined || value === null || value === "" ? {} : wrap(value);
129
+ }
130
+
131
+ function asString(value: unknown): string | undefined {
132
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
133
+ }
134
+
135
+ /** Flattens string | {name} | ({name} | string)[] into "a; b" form. */
136
+ function asAuthorList(value: unknown): string | undefined {
137
+ const names = Array.isArray(value) ? value : [value];
138
+ const flattened = names
139
+ .map((entry) => {
140
+ if (typeof entry === "string") return entry.trim();
141
+ if (entry !== null && typeof entry === "object" && typeof (entry as Record<string, unknown>).name === "string") {
142
+ return ((entry as Record<string, unknown>).name as string).trim();
143
+ }
144
+ return "";
145
+ })
146
+ .filter((name) => name !== "");
147
+ return flattened.length === 0 ? undefined : flattened.join("; ");
148
+ }
149
+
150
+ function asStringList(value: unknown, separator: string): string | undefined {
151
+ const entries = Array.isArray(value) ? value : [value];
152
+ const flattened = entries.map((entry) => (typeof entry === "string" ? entry.trim() : "")).filter((entry) => entry !== "");
153
+ return flattened.length === 0 ? undefined : flattened.join(separator);
154
+ }
@@ -0,0 +1,103 @@
1
+ // src/render/chrome.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
6
+ /**
7
+ * Locates a Chrome/Chromium binary for the renderer.
8
+ *
9
+ * `--executable-browser` wins, then a binary installed by @puppeteer/browsers
10
+ * (the same cache Vivliostyle CLI used), then the usual system locations.
11
+ */
12
+
13
+ import { existsSync, readdirSync, statSync } from "node:fs";
14
+ import { homedir, platform } from "node:os";
15
+ import { join } from "node:path";
16
+
17
+ const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
18
+ const MAC_CHROMIUM = "/Applications/Chromium.app/Contents/MacOS/Chromium";
19
+ const LINUX_PATHS = [
20
+ "/usr/bin/google-chrome",
21
+ "/usr/bin/google-chrome-stable",
22
+ "/usr/bin/chromium",
23
+ "/usr/bin/chromium-browser",
24
+ "/snap/bin/chromium"
25
+ ];
26
+
27
+ /** Directory @puppeteer/browsers installs into. */
28
+ export function puppeteerCacheDir(): string {
29
+ return process.env.PUPPETEER_CACHE_DIR ?? join(homedir(), ".cache", "puppeteer");
30
+ }
31
+
32
+ /** Finds an installed browser in the @puppeteer/browsers cache. */
33
+ export function findCachedBrowser(): string | null {
34
+ const root = join(puppeteerCacheDir(), "chrome");
35
+ if (!existsSync(root)) return null;
36
+
37
+ const candidates: string[] = [];
38
+ for (const build of readdirSync(root)) {
39
+ const buildDir = join(root, build);
40
+ let stat;
41
+ try {
42
+ stat = statSync(buildDir);
43
+ } catch {
44
+ continue;
45
+ }
46
+ if (!stat.isDirectory()) continue;
47
+
48
+ for (const flavour of readdirSync(buildDir)) {
49
+ candidates.push(
50
+ join(buildDir, flavour, "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
51
+ join(buildDir, flavour, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
52
+ join(buildDir, flavour, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
53
+ join(buildDir, flavour, "chrome-linux64", "chrome"),
54
+ join(buildDir, flavour, "chrome-headless-shell-linux64", "chrome-headless-shell")
55
+ );
56
+ }
57
+ }
58
+
59
+ return candidates.find((candidate) => existsSync(candidate)) ?? null;
60
+ }
61
+
62
+ export function systemBrowser(): string | null {
63
+ const candidates = platform() === "darwin" ? [MAC_CHROME, MAC_CHROMIUM] : LINUX_PATHS;
64
+ return candidates.find((candidate) => existsSync(candidate)) ?? null;
65
+ }
66
+
67
+ /**
68
+ * Path of the browser to launch, or `null` when none is installed.
69
+ */
70
+ export function resolveBrowserExecutable(explicit?: string | undefined): string | null {
71
+ const candidates = [explicit, process.env.CHROME_PATH, findCachedBrowser(), systemBrowser()];
72
+ for (const candidate of candidates) {
73
+ if (candidate !== undefined && candidate !== null && candidate !== "" && existsSync(candidate)) return candidate;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Chrome flags for headless rendering.
80
+ *
81
+ * SwiftShader keeps WebGL (three.js, A-Frame) working without a GPU, and the
82
+ * ANGLE/WebGPU flags extend that to WebGPU on headless machines (best effort:
83
+ * pages report `navigator.gpu == null` when the build still lacks it).
84
+ * `--disable-web-security` lets the page load the cross-origin embeds it shows.
85
+ */
86
+ export function chromeArgs(extra: string[] = []): string[] {
87
+ return [
88
+ "--disable-field-trial-config",
89
+ "--disable-back-forward-cache",
90
+ "--disable-component-update",
91
+ "--no-default-browser-check",
92
+ "--disable-features=AcceptCHFrame,AvoidUnnecessaryBeforeUnloadCheckSync,DestroyProfileInBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyPartitioning,Translate,AutofillServerCommunication,DestroyProfileOnBrowserClose",
93
+ "--no-service-autorun",
94
+ "--enable-unsafe-swiftshader",
95
+ "--use-angle=swiftshader",
96
+ "--enable-unsafe-webgpu",
97
+ "--disable-web-security",
98
+ "--hide-scrollbars",
99
+ "--mute-audio",
100
+ "--force-device-scale-factor=1",
101
+ ...extra
102
+ ];
103
+ }
@@ -0,0 +1,293 @@
1
+ // src/render/pdf-postprocess.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
6
+ /**
7
+ * PDF post-processing: document metadata, XMP and standards labeling.
8
+ *
9
+ * Runs on the PDF bytes Chrome printed (Skia output) and applies:
10
+ * - document information entries (title, author, subject, keywords, producer, creator)
11
+ * - the catalog /Lang entry for the document language
12
+ * - an XMP metadata stream kept consistent with the information dictionary
13
+ * - PDF/A or PDF/X identification: XMP identification properties, an
14
+ * OutputIntent with an embedded ICC profile and a stable file identifier
15
+ *
16
+ * This is a "label, don't convert" step — the same semantics vivliostyle-cli
17
+ * gives its PDF/X option: the content is neither converted nor checked, so
18
+ * conformance of the content is the author's responsibility. Verify with
19
+ * veraPDF (or a print provider's preflight) when it matters.
20
+ *
21
+ * The editing follows vivliostyle-cli's mupdf-based post-processing
22
+ * (src/output/pdfx.ts, pdf-document.ts, pdf-version.ts at v11.4).
23
+ */
24
+
25
+ import { randomBytes, randomUUID } from "node:crypto";
26
+ import { existsSync, readFileSync } from "node:fs";
27
+ import { dirname, join, resolve } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import * as mupdf from "mupdf";
30
+ import { buildXmpPacket, pdfDateToXmpDate, toXmpDate, type PdfLabel } from "./xmp.js";
31
+
32
+ /** Document metadata written to the information dictionary and the XMP packet. */
33
+ export type PdfMetadata = {
34
+ title?: string;
35
+ author?: string;
36
+ subject?: string;
37
+ keywords?: string;
38
+ language?: string;
39
+ creator: string;
40
+ producer: string;
41
+ };
42
+
43
+ export type PostProcessOptions = {
44
+ metadata: PdfMetadata;
45
+ label?: PdfLabel;
46
+ /** ICC profile embedded as the OutputIntent; required whenever a label is set. */
47
+ iccProfile?: Uint8Array;
48
+ iccProfileName?: string;
49
+ };
50
+
51
+ type Destroyable = { destroy(): void };
52
+
53
+ type Scope = {
54
+ track<T extends Destroyable>(value: T): T;
55
+ dispose(): void;
56
+ };
57
+
58
+ /**
59
+ * Tracks MuPDF's native objects and destroys them in reverse order. Every
60
+ * PDFObject/Buffer/ColorSpace keeps native memory behind the wasm binding,
61
+ * which is only reclaimed on an explicit destroy.
62
+ */
63
+ function createScope(): Scope {
64
+ const tracked: Destroyable[] = [];
65
+ return {
66
+ track<T extends Destroyable>(value: T): T {
67
+ tracked.push(value);
68
+ return value;
69
+ },
70
+ dispose(): void {
71
+ while (tracked.length > 0) {
72
+ try {
73
+ tracked.pop()?.destroy();
74
+ } catch {
75
+ // Cleanup is best-effort; a failed destroy must not mask the result.
76
+ }
77
+ }
78
+ }
79
+ };
80
+ }
81
+
82
+ // MuPDF exposes PDF version x.y as x * 10 + y.
83
+ type PdfVersion = 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20;
84
+
85
+ // The catalog /Version is written for every required version; MuPDF's wasm
86
+ // binding provides no API for the header version and a full save derives the
87
+ // header from the catalog entry (same approach as vivliostyle-cli).
88
+ function setMinimumPdfVersion(document: mupdf.PDFDocument, minimumVersion: PdfVersion, scope: Scope): void {
89
+ if (document.getVersion() >= minimumVersion) return;
90
+ const trailer = scope.track(document.getTrailer());
91
+ const catalog = scope.track(trailer.get("Root"));
92
+ const version = scope.track(document.newName(`${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`));
93
+ catalog.put("Version", version);
94
+ }
95
+
96
+ function readInfoString(info: mupdf.PDFObject, key: string, scope: Scope): string | undefined {
97
+ const value = scope.track(info.get(key));
98
+ return value.isString() ? value.asString() : undefined;
99
+ }
100
+
101
+ function readTrapped(info: mupdf.PDFObject, scope: Scope): "True" | "False" {
102
+ const trapped = scope.track(info.get("Trapped"));
103
+ return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
104
+ }
105
+
106
+ function openPdfDocument(pdf: Uint8Array, scope: Scope): mupdf.PDFDocument {
107
+ // openDocument returns the Document base type; a PDF input yields a PDFDocument.
108
+ const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf") as mupdf.PDFDocument;
109
+ return scope.track(document);
110
+ }
111
+
112
+ /**
113
+ * Runs `fn` with freshly fetched catalog handles. MuPDF replaces the trailer
114
+ * dict whenever an information entry is written through `setMetaData`, and a
115
+ * PDFObject handle held across such a write ends up detached from the
116
+ * document — edits into it silently disappear on save. Every mutation
117
+ * therefore re-fetches its handles right before it runs.
118
+ */
119
+ function withCatalog<T>(document: mupdf.PDFDocument, scope: Scope, fn: (catalog: mupdf.PDFObject) => T): T {
120
+ const trailer = scope.track(document.getTrailer());
121
+ const catalog = scope.track(trailer.get("Root"));
122
+ return fn(catalog);
123
+ }
124
+
125
+ /** Runs `fn` with a freshly fetched information dictionary handle. */
126
+ function withInfo<T>(document: mupdf.PDFDocument, scope: Scope, fn: (info: mupdf.PDFObject) => T): T {
127
+ const trailer = scope.track(document.getTrailer());
128
+ const info = scope.track(trailer.get("Info"));
129
+ return fn(info);
130
+ }
131
+
132
+ /** Runs `fn` with a freshly fetched trailer handle. */
133
+ function withTrailer<T>(document: mupdf.PDFDocument, scope: Scope, fn: (trailer: mupdf.PDFObject) => T): T {
134
+ return fn(scope.track(document.getTrailer()));
135
+ }
136
+
137
+ /**
138
+ * Applies metadata and standards labeling to a printed PDF.
139
+ *
140
+ * Producer/Creator are always stamped (the wrapper owns them), so a build
141
+ * without explicit metadata still gets a consistent information dictionary
142
+ * and XMP packet. Dates come from what Skia wrote: CreationDate is kept,
143
+ * ModifyDate falls back to it, exactly like vivliostyle-cli handles output
144
+ * from print backends that skip the modification date.
145
+ */
146
+ export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOptions): Promise<Uint8Array> {
147
+ const scope = createScope();
148
+ try {
149
+ const { metadata, label } = options;
150
+ const document = openPdfDocument(pdf, scope);
151
+
152
+ // ── What the print backend already wrote ────────────────────────────────
153
+ const { creationDate, modifyDate, trapped } = withInfo(document, scope, (info) => ({
154
+ creationDate: readInfoString(info, "CreationDate", scope),
155
+ modifyDate: readInfoString(info, "ModDate", scope),
156
+ trapped: readTrapped(info, scope)
157
+ }));
158
+ const createDateXmp = (creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined) ?? toXmpDate(new Date());
159
+ // Acrobat's preflight requires xmp:ModifyDate/MetadataDate; backends like
160
+ // Firefox's cairo skip them, so they take the creation date then.
161
+ const modifyDateXmp = (modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined) ?? createDateXmp;
162
+
163
+ // ── Document information entries ────────────────────────────────────────
164
+ document.setMetaData("info:Producer", metadata.producer);
165
+ document.setMetaData("info:Creator", metadata.creator);
166
+ if (metadata.title !== undefined) document.setMetaData("info:Title", metadata.title);
167
+ if (metadata.author !== undefined) document.setMetaData("info:Author", metadata.author);
168
+ if (metadata.subject !== undefined) document.setMetaData("info:Subject", metadata.subject);
169
+ if (metadata.keywords !== undefined) document.setMetaData("info:Keywords", metadata.keywords);
170
+
171
+ // ── Catalog language ────────────────────────────────────────────────────
172
+ const language = metadata.language;
173
+ if (language !== undefined && language !== "") {
174
+ withCatalog(document, scope, (catalog) => {
175
+ catalog.put("Lang", scope.track(document.newString(language)));
176
+ });
177
+ setMinimumPdfVersion(document, 14, scope);
178
+ }
179
+
180
+ // ── XMP metadata stream ─────────────────────────────────────────────────
181
+ const xmp = buildXmpPacket(
182
+ {
183
+ title: metadata.title,
184
+ author: metadata.author,
185
+ subject: metadata.subject,
186
+ keywords: metadata.keywords,
187
+ producer: metadata.producer,
188
+ creatorTool: metadata.creator,
189
+ createDate: createDateXmp,
190
+ modifyDate: modifyDateXmp,
191
+ metadataDate: toXmpDate(new Date()),
192
+ documentId: `uuid:${randomUUID()}`,
193
+ ...(label !== undefined && label.kind === "pdfx" && label.version === "X-4" ? { trapped } : {})
194
+ },
195
+ label
196
+ );
197
+ withCatalog(document, scope, (catalog) => {
198
+ const xmpBuffer = scope.track(new mupdf.Buffer(xmp));
199
+ const metadataStream = scope.track(document.addStream(xmpBuffer, { Type: "Metadata", Subtype: "XML" }));
200
+ catalog.put("Metadata", metadataStream);
201
+ });
202
+
203
+ // ── OutputIntent with the embedded ICC profile ──────────────────────────
204
+ if (label !== undefined) {
205
+ const profile = options.iccProfile;
206
+ if (profile === undefined) {
207
+ throw new Error(
208
+ label.kind === "pdfx"
209
+ ? "PDF/X labeling requires an ICC profile for the OutputIntent (--icc-profile)."
210
+ : "PDF/A labeling requires an ICC profile for the OutputIntent."
211
+ );
212
+ }
213
+ const profileName = options.iccProfileName ?? "output-intent.icc";
214
+ withCatalog(document, scope, (catalog) => {
215
+ const profileBuffer = scope.track(new mupdf.Buffer(profile));
216
+ const colorSpace = scope.track(new mupdf.ColorSpace(profileBuffer, profileName));
217
+ const profileStream = scope.track(document.addStream(profileBuffer, { N: colorSpace.getNumberOfComponents() }));
218
+ const identifier = scope.track(document.newString("Custom"));
219
+ const profileInfo = scope.track(document.newString(profileName));
220
+ // ISO 32000-1:2008, 7.7.2/14.11.5: OutputConditionIdentifier may be
221
+ // "Custom"; Info and DestOutputProfile are required for nonstandard
222
+ // production conditions.
223
+ const intent = scope.track(
224
+ document.addObject({
225
+ Type: "OutputIntent",
226
+ S: label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX",
227
+ OutputConditionIdentifier: identifier,
228
+ Info: profileInfo,
229
+ DestOutputProfile: profileStream
230
+ })
231
+ );
232
+ catalog.put("OutputIntents", [intent]);
233
+ });
234
+ setMinimumPdfVersion(document, 14, scope);
235
+ }
236
+
237
+ // ── Standards identification outside the XMP packet ─────────────────────
238
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
239
+ // PDF/X-1a:2003 identification lives in the information dictionary, not
240
+ // in XMP (XMP identification is the PDF/X-4 form).
241
+ document.setMetaData("info:GTS_PDFXVersion", "PDF/X-1a:2003");
242
+ withInfo(document, scope, (info) => {
243
+ info.put("Trapped", scope.track(document.newName(trapped)));
244
+ // Acrobat's PDF/X-1a:2003 preflight requires ModDate, which some print
245
+ // backends never write; it takes the creation date then.
246
+ if (modifyDate === undefined && creationDate !== undefined) {
247
+ info.put("ModDate", scope.track(document.newString(creationDate)));
248
+ }
249
+ });
250
+ }
251
+
252
+ // A stable file identifier is required for PDF/A and PDF/X. Written last,
253
+ // against a trailer handle fetched after every information entry write.
254
+ if (label !== undefined) {
255
+ withTrailer(document, scope, (trailer) => {
256
+ const existingId = scope.track(trailer.get("ID"));
257
+ if (!existingId.isArray()) {
258
+ const bytes = randomBytes(16);
259
+ trailer.put("ID", [document.newByteString(bytes), document.newByteString(bytes)]);
260
+ }
261
+ });
262
+ }
263
+
264
+ if (!document.hasUnsavedChanges()) return pdf;
265
+ const output = scope.track(document.saveToBuffer("compress"));
266
+ // Copy so the data stays valid after the buffer is destroyed.
267
+ return new Uint8Array(output.asUint8Array());
268
+ } finally {
269
+ scope.dispose();
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
275
+ * The profile ships unchanged from the ICC ("sRGB_v4_ICC_preference.icc"); its
276
+ * license permits redistribution provided the file, including its embedded
277
+ * copyright notice tag, is not modified (https://www.color.org/srgbprofiles.xalter).
278
+ */
279
+ export function loadDefaultIccProfile(): { bytes: Uint8Array; name: string } {
280
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
281
+ const candidates = [
282
+ // Source layout (vitest, direct TS execution).
283
+ join(moduleDir, "srgb.icc"),
284
+ // Bundled layout: dist/vivliostyle-batch-cli.js ships next to src/.
285
+ resolve(moduleDir, "../src/render/srgb.icc")
286
+ ];
287
+ for (const candidate of candidates) {
288
+ if (existsSync(candidate)) {
289
+ return { bytes: readFileSync(candidate), name: "sRGB_v4_ICC_preference.icc" };
290
+ }
291
+ }
292
+ throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
293
+ }