@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,183 @@
1
+ // src/render/xmp.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
6
+ /**
7
+ * XMP metadata packet builder for the PDF post-processing step
8
+ * (see src/render/pdf-postprocess.ts).
9
+ *
10
+ * The packet follows XMP Specification Part 1 (April 2012) the same way
11
+ * vivliostyle-cli builds it for PDF/X: a packet wrapper Acrobat's preflight
12
+ * accepts, Dublin Core for title/creator/description, the Adobe PDF and XMP
13
+ * namespaces for producer/creator/dates, and the identification namespaces
14
+ * pdfaid (PDF/A, ISO 19005) and pdfxid (PDF/X, ISO 15930).
15
+ */
16
+
17
+ /** PDF/A part (ISO 19005-1/-2/-3/-4). */
18
+ export type PdfAPart = "1" | "2" | "3" | "4";
19
+
20
+ /** PDF/A conformance level. PDF/A-4 has no conformance levels. */
21
+ export type PdfAConformance = "a" | "b" | "u";
22
+
23
+ /** PDF/A labeling request, e.g. `--pdfa 2b`. */
24
+ export type PdfAIdentification = {
25
+ kind: "pdfa";
26
+ part: PdfAPart;
27
+ conformance?: PdfAConformance;
28
+ };
29
+
30
+ /** PDF/X conformance level (ISO 15930), e.g. `--pdfx X-4`. */
31
+ export type PdfXVersion = "X-4" | "X-1a:2003";
32
+
33
+ export type PdfXIdentification = {
34
+ kind: "pdfx";
35
+ version: PdfXVersion;
36
+ };
37
+
38
+ /** Standards label carried into the XMP packet and the PDF catalog. */
39
+ export type PdfLabel = PdfAIdentification | PdfXIdentification;
40
+
41
+ /** Values the XMP packet carries; all but the identifiers are optional. */
42
+ export type XmpFields = {
43
+ title?: string;
44
+ /** Authors joined on ";" end up as individual dc:creator entries. */
45
+ author?: string;
46
+ subject?: string;
47
+ keywords?: string;
48
+ producer?: string;
49
+ creatorTool?: string;
50
+ /** XMP dates (YYYY-MM-DDThh:mm:ssTZD, XMP Part 1, 8.2.1.2). */
51
+ createDate?: string;
52
+ modifyDate?: string;
53
+ metadataDate?: string;
54
+ /** URN written as xmpMM:DocumentID; its presence adds the ID family. */
55
+ documentId?: string;
56
+ trapped?: "True" | "False";
57
+ };
58
+
59
+ const NS = {
60
+ rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
61
+ dc: "http://purl.org/dc/elements/1.1/",
62
+ pdf: "http://ns.adobe.com/pdf/1.3/",
63
+ xmp: "http://ns.adobe.com/xap/1.0/",
64
+ xmpMM: "http://ns.adobe.com/xap/1.0/mm/",
65
+ pdfaid: "http://www.aiim.org/pdfa/ns/id/",
66
+ pdfxid: "http://www.npes.org/pdfx/ns/id/"
67
+ } as const;
68
+
69
+ /** XMP Specification Part 1 (April 2012), 8.2.1.2 date form. */
70
+ export function toXmpDate(date: Date): string {
71
+ const pad = (value: number, length = 2): string => String(value).padStart(length, "0");
72
+ return (
73
+ `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}` +
74
+ `T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}Z`
75
+ );
76
+ }
77
+
78
+ // ISO 32000-1:2008, 7.9.4 writes a date as D:YYYYMMDDHHmmSSOHH'mm, the form
79
+ // Skia in Chromium writes. The offset is kept, not normalized to UTC, so the
80
+ // XMP packet shows the same instant the information dictionary shows.
81
+ const PDF_DATE = /^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:Z|([+\-])(\d{2})'(\d{2})'?)$/;
82
+
83
+ /** Reformats a PDF date string as an XMP date; `undefined` when not one. */
84
+ export function pdfDateToXmpDate(value: string): string | undefined {
85
+ const match = PDF_DATE.exec(value);
86
+ if (match === null) return undefined;
87
+ const [, year, month, day, hour, minute, second, sign, offsetHour, offsetMinute] = match;
88
+ const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
89
+ return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
90
+ }
91
+
92
+ function xmlEscape(text: string): string {
93
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
94
+ }
95
+
96
+ /** dc:title/dc:description: a language alternative with the x-default entry. */
97
+ function languageAlternative(text: string): string {
98
+ return ["<rdf:Alt>", ` <rdf:li xml:lang="x-default">${xmlEscape(text)}</rdf:li>`, "</rdf:Alt>"].join("\n ");
99
+ }
100
+
101
+ /** dc:creator: an ordered sequence; ";" separates individual authors. */
102
+ function creatorSequence(author: string): string {
103
+ const names = author
104
+ .split(";")
105
+ .map((name) => name.trim())
106
+ .filter((name) => name !== "");
107
+ const items = (names.length === 0 ? [author] : names).map((name) => ` <rdf:li>${xmlEscape(name)}</rdf:li>`);
108
+ return ["<rdf:Seq>", ...items, "</rdf:Seq>"].join("\n ");
109
+ }
110
+
111
+ /**
112
+ * Builds the XMP packet for the document. Only defined fields are written;
113
+ * the packet wrapper uses the fixed header id packet scanners look for
114
+ * (XMP Part 1, 7.3.2 makes the wrapper optional, Acrobat rejects its absence).
115
+ */
116
+ export function buildXmpPacket(fields: XmpFields, label?: PdfLabel): string {
117
+ const properties: string[] = [];
118
+
119
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-4") {
120
+ properties.push(`<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>`);
121
+ }
122
+ if (fields.title !== undefined) {
123
+ properties.push(`<dc:title>\n ${languageAlternative(fields.title)}\n </dc:title>`);
124
+ }
125
+ if (fields.author !== undefined) {
126
+ properties.push(`<dc:creator>\n ${creatorSequence(fields.author)}\n </dc:creator>`);
127
+ }
128
+ if (fields.subject !== undefined) {
129
+ properties.push(`<dc:description>\n ${languageAlternative(fields.subject)}\n </dc:description>`);
130
+ }
131
+ if (fields.keywords !== undefined) {
132
+ properties.push(`<pdf:Keywords>${xmlEscape(fields.keywords)}</pdf:Keywords>`);
133
+ }
134
+ if (fields.producer !== undefined) {
135
+ properties.push(`<pdf:Producer>${xmlEscape(fields.producer)}</pdf:Producer>`);
136
+ }
137
+ if (fields.trapped !== undefined) {
138
+ properties.push(`<pdf:Trapped>${fields.trapped}</pdf:Trapped>`);
139
+ }
140
+ if (fields.creatorTool !== undefined) {
141
+ properties.push(`<xmp:CreatorTool>${xmlEscape(fields.creatorTool)}</xmp:CreatorTool>`);
142
+ }
143
+ if (fields.createDate !== undefined) {
144
+ properties.push(`<xmp:CreateDate>${fields.createDate}</xmp:CreateDate>`);
145
+ }
146
+ if (fields.modifyDate !== undefined) {
147
+ properties.push(`<xmp:ModifyDate>${fields.modifyDate}</xmp:ModifyDate>`);
148
+ }
149
+ if (fields.metadataDate !== undefined) {
150
+ properties.push(`<xmp:MetadataDate>${fields.metadataDate}</xmp:MetadataDate>`);
151
+ }
152
+ if (fields.documentId !== undefined) {
153
+ properties.push(
154
+ `<xmpMM:DocumentID>${xmlEscape(fields.documentId)}</xmpMM:DocumentID>`,
155
+ `<xmpMM:VersionID>1</xmpMM:VersionID>`,
156
+ `<xmpMM:RenditionClass>default</xmpMM:RenditionClass>`
157
+ );
158
+ }
159
+ if (label !== undefined && label.kind === "pdfa") {
160
+ properties.push(`<pdfaid:part>${label.part}</pdfaid:part>`);
161
+ // PDF/A-4 (ISO 19005-4) identifies through the part value alone; the
162
+ // conformance levels a/b/u exist for parts 1 to 3 only.
163
+ if (label.part !== "4" && label.conformance !== undefined) {
164
+ properties.push(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`);
165
+ }
166
+ }
167
+
168
+ const body = [
169
+ `<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>`,
170
+ `<x:xmpmeta xmlns:x="adobe:ns:meta/">`,
171
+ ` <rdf:RDF xmlns:rdf="${NS.rdf}">`,
172
+ ` <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}">`,
173
+ ...properties.map((property) => ` ${property}`),
174
+ ` </rdf:Description>`,
175
+ ` </rdf:RDF>`,
176
+ `</x:xmpmeta>`,
177
+ `<?xpacket end="w"?>`
178
+ ].join("\n");
179
+
180
+ // XML 1.0 (Fifth Edition), 2.11: a processor turns a literal CR into LF
181
+ // before parsing, so a CR in a value survives only as a character reference.
182
+ return `${body.replaceAll("\r", "&#xD;")}\n`;
183
+ }
package/src/server.ts ADDED
@@ -0,0 +1,317 @@
1
+ // src/server.ts
2
+
3
+ // Copyright (c) 2026 Christian Mahnke
4
+ // Licensed under the MIT License.
5
+
6
+ /**
7
+ * The static server the renderer serves the document and its assets from.
8
+ *
9
+ * It replaces the Vite based server this package used before: everything is
10
+ * served by us, which is what makes the document's origin (and therefore the
11
+ * base URI of scripts the page runs) ours as well.
12
+ */
13
+
14
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
15
+ import { existsSync, readFileSync, statSync } from "node:fs";
16
+ import { lookup as mimeLookup } from "mime-types";
17
+ import { resolve } from "node:path";
18
+
19
+ export type AssetBaseMapping = {
20
+ urlBase: string;
21
+ localBase: string;
22
+ };
23
+
24
+ export type StaticMap = Record<string, string>;
25
+
26
+ export type SettleGate = {
27
+ /** Hold the gate response until the page reports that it settled. */
28
+ quietMs: number;
29
+ /** Never hold longer than this. */
30
+ deadlineMs: number;
31
+ };
32
+
33
+ export type StaticServerOptions = {
34
+ staticMap?: StaticMap;
35
+ assetBases?: AssetBaseMapping[];
36
+ /** Redirect requests without a local file to the mapped origin. */
37
+ fetchMissing?: boolean;
38
+ settle?: SettleGate | null;
39
+ /** Directory of @vivliostyle/viewer/lib, served under `viewerPath`. */
40
+ viewerLibDir?: string | null;
41
+ /** Page that renders the document; served under the document's directory. */
42
+ viewerFilePath?: string | null;
43
+ /**
44
+ * Document to serve, mapped to its path on the site. `localPath` may be null
45
+ * at first and filled in later: the document is rewritten with the server's
46
+ * URL, which is only known once the server runs.
47
+ */
48
+ entry?: { localPath: string | null; sitePath: string } | null;
49
+ onSettled?: (detail: SettleReport) => void;
50
+ log?: (message: string) => void;
51
+ };
52
+
53
+ export type SettleReport = {
54
+ reason: "settled" | "deadline";
55
+ waitedMs: number;
56
+ detail?: Record<string, unknown>;
57
+ };
58
+
59
+ export type StaticServer = {
60
+ baseUrl: string;
61
+ close: () => Promise<void>;
62
+ };
63
+
64
+ /** Paths the wrapper owns inside the site it serves. */
65
+ export const VIEWER_PAGE_NAME = "__viv-viewer.html";
66
+ export const VIEWER_LIB_PATH = "/__viv-viewer";
67
+ export const SETTLE_GATE_PATH = "/__viv-settle";
68
+ export const SETTLE_READY_PATH = "/__viv-settle-ready";
69
+
70
+ const TRANSPARENT_GIF = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
71
+
72
+ /** CSP that lets the Vivliostyle viewer embed the served documents. */
73
+ function frameAncestors(): string {
74
+ return ["'self'", "http://localhost:*", "https://localhost:*", "http://127.0.0.1:*", "https://127.0.0.1:*"].join(" ");
75
+ }
76
+
77
+ /** Only redirect requests that ask for a file, never bare directory URLs. */
78
+ export function looksLikeFileRequest(urlPath: string): boolean {
79
+ const last = urlPath.slice(urlPath.lastIndexOf("/") + 1);
80
+ return last !== "" && last !== "/" && last.includes(".");
81
+ }
82
+
83
+ export function decodeRequestPath(req: IncomingMessage): string {
84
+ const raw = (req.url ?? "/").split("?")[0];
85
+ try {
86
+ return decodeURIComponent(raw);
87
+ } catch {
88
+ return raw;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Resolves a request path against the explicit static map, then against the
94
+ * asset-base roots.
95
+ */
96
+ export function resolveRequestPath(
97
+ urlPath: string,
98
+ staticMap: StaticMap,
99
+ assetBases: AssetBaseMapping[]
100
+ ): { localPath: string | null; remoteUrl: string | null } {
101
+ // An exact entry whose file is gone (e.g. a derived mapping for an already
102
+ // virtual path) must not shadow a prefix mount that actually serves the file.
103
+ if (Object.hasOwn(staticMap, urlPath)) {
104
+ const localPath = resolve(staticMap[urlPath]);
105
+ if (existsSync(localPath)) return { localPath, remoteUrl: null };
106
+ }
107
+
108
+ for (const [virtual, localBase] of Object.entries(staticMap)) {
109
+ const prefix = virtual.endsWith("/") ? virtual : `${virtual}/`;
110
+ if (!urlPath.startsWith(prefix)) continue;
111
+ const localPath = resolve(localBase, urlPath.slice(prefix.length));
112
+ if (existsSync(localPath)) return { localPath, remoteUrl: null };
113
+ }
114
+
115
+ for (const ab of assetBases) {
116
+ const localPath = resolve(ab.localBase, urlPath.replace(/^\//, ""));
117
+ if (existsSync(localPath)) return { localPath, remoteUrl: null };
118
+ }
119
+
120
+ for (const ab of assetBases) {
121
+ if (!looksLikeFileRequest(urlPath)) continue;
122
+ return { localPath: null, remoteUrl: `${ab.urlBase.replace(/\/$/, "")}${urlPath}` };
123
+ }
124
+
125
+ return { localPath: null, remoteUrl: null };
126
+ }
127
+
128
+ function sendFile(res: ServerResponse, localPath: string): boolean {
129
+ let size: number;
130
+ try {
131
+ const stat = statSync(localPath);
132
+ if (!stat.isFile()) return false;
133
+ size = stat.size;
134
+ } catch {
135
+ return false;
136
+ }
137
+
138
+ const mime = mimeLookup(localPath);
139
+ if (mime) res.setHeader("Content-Type", mime);
140
+ res.setHeader("Content-Length", String(size));
141
+ res.setHeader("Cache-Control", "no-cache");
142
+ res.setHeader("Content-Security-Policy", `frame-ancestors ${frameAncestors()}`);
143
+ res.statusCode = 200;
144
+ res.end(readFileSync(localPath));
145
+ return true;
146
+ }
147
+
148
+ /**
149
+ * Serves the viewer page with its asset references made absolute, so that it
150
+ * can live in the document's directory without dragging its own assets along.
151
+ */
152
+ export function buildViewerPage(viewerHtml: string, viewerLibPath = VIEWER_LIB_PATH): string {
153
+ return viewerHtml
154
+ .replace(/(src|href)="(?!https?:|data:|\/)([^"]+)"/g, (_match, attr: string, path: string) => `${attr}="${viewerLibPath}/${path}"`)
155
+ .replace(/<base[^>]*>/g, "");
156
+ }
157
+
158
+ export async function startStaticServer(options: StaticServerOptions = {}, port = 0): Promise<StaticServer> {
159
+ const staticMap = options.staticMap ?? {};
160
+ const assetBases = options.assetBases ?? [];
161
+ const fetchMissing = options.fetchMissing === true;
162
+ const settle = options.settle ?? null;
163
+ const log = options.log ?? ((): void => undefined);
164
+
165
+ let released = false;
166
+ let holdStartedAt = 0;
167
+ let deadlineTimer: NodeJS.Timeout | null = null;
168
+ let pending: ServerResponse[] = [];
169
+
170
+ const release = (reason: "settled" | "deadline", detail?: Record<string, unknown>): void => {
171
+ if (released) return;
172
+ released = true;
173
+ if (deadlineTimer !== null) clearTimeout(deadlineTimer);
174
+
175
+ const waitedMs = holdStartedAt === 0 ? 0 : Date.now() - holdStartedAt;
176
+ options.onSettled?.({ reason, waitedMs, detail });
177
+
178
+ const waiting = pending;
179
+ pending = [];
180
+ for (const res of waiting) {
181
+ if (res.headersSent || res.writableEnded) continue;
182
+ res.statusCode = 200;
183
+ res.setHeader("Content-Type", "image/gif");
184
+ res.setHeader("Content-Length", String(TRANSPARENT_GIF.length));
185
+ res.end(TRANSPARENT_GIF);
186
+ }
187
+ };
188
+
189
+ const handleSettle = (urlPath: string, query: URLSearchParams, res: ServerResponse): boolean => {
190
+ if (settle === null) return false;
191
+
192
+ if (urlPath === SETTLE_READY_PATH) {
193
+ const detail: Record<string, unknown> = {};
194
+ for (const key of [
195
+ "reason",
196
+ "ms",
197
+ "pending",
198
+ "frames",
199
+ "canvases",
200
+ "containers",
201
+ "mutations",
202
+ "dpr",
203
+ "painted",
204
+ "ready",
205
+ "longtasks"
206
+ ]) {
207
+ const value = query.get(key);
208
+ if (value === null) continue;
209
+ detail[key] = /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
210
+ }
211
+ res.statusCode = 204;
212
+ res.end();
213
+ release("settled", detail);
214
+ return true;
215
+ }
216
+
217
+ if (urlPath !== SETTLE_GATE_PATH) return false;
218
+
219
+ if (released) {
220
+ release("deadline");
221
+ return true;
222
+ }
223
+
224
+ if (holdStartedAt === 0) {
225
+ holdStartedAt = Date.now();
226
+ deadlineTimer = setTimeout(() => release("deadline"), settle.deadlineMs);
227
+ deadlineTimer.unref?.();
228
+ }
229
+
230
+ pending.push(res);
231
+ res.on("close", () => {
232
+ pending = pending.filter((candidate) => candidate !== res);
233
+ });
234
+ return true;
235
+ };
236
+
237
+ const handler = (req: IncomingMessage, res: ServerResponse): void => {
238
+ const urlPath = decodeRequestPath(req);
239
+ const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
240
+ // Every request the page makes transits here: log it (path + status) so
241
+ // render problems become traceable from the per-page logs.
242
+ res.on("finish", () => {
243
+ log(`${urlPath} ${res.statusCode}`);
244
+ });
245
+
246
+ if (handleSettle(urlPath, query, res)) return;
247
+
248
+ // The viewer page lives next to the document so that scripts the page runs
249
+ // resolve relative URLs against the document's directory.
250
+ if (urlPath.endsWith(`/${VIEWER_PAGE_NAME}`)) {
251
+ const html =
252
+ options.viewerFilePath === null || options.viewerFilePath === undefined ? "" : readFileSync(options.viewerFilePath, "utf-8");
253
+ if (html !== "") {
254
+ res.statusCode = 200;
255
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
256
+ res.setHeader("Cache-Control", "no-cache");
257
+ res.end(buildViewerPage(html));
258
+ return;
259
+ }
260
+ }
261
+
262
+ if (options.viewerLibDir != null && urlPath.startsWith(`${VIEWER_LIB_PATH}/`)) {
263
+ const relative = urlPath.slice(VIEWER_LIB_PATH.length + 1);
264
+ if (sendFile(res, resolve(options.viewerLibDir, relative))) return;
265
+ }
266
+
267
+ const entry = options.entry;
268
+ if (entry !== null && entry !== undefined && entry.localPath !== null && urlPath === entry.sitePath) {
269
+ if (sendFile(res, resolve(entry.localPath))) return;
270
+ }
271
+
272
+ const { localPath, remoteUrl } = resolveRequestPath(urlPath, staticMap, assetBases);
273
+
274
+ if (localPath !== null && sendFile(res, localPath)) return;
275
+
276
+ if (remoteUrl !== null && fetchMissing) {
277
+ log(`[fetch] ${urlPath} → ${remoteUrl}`);
278
+ res.statusCode = 302;
279
+ res.setHeader("Location", remoteUrl);
280
+ res.end();
281
+ return;
282
+ }
283
+
284
+ res.statusCode = 404;
285
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
286
+ res.end("Not found");
287
+ };
288
+
289
+ const server: Server = createServer(handler);
290
+
291
+ await new Promise<void>((resolvePromise, reject) => {
292
+ server.once("error", reject);
293
+ server.listen(port, "127.0.0.1", () => {
294
+ server.off("error", reject);
295
+ resolvePromise();
296
+ });
297
+ });
298
+
299
+ const address = server.address();
300
+ const boundPort = typeof address === "object" && address !== null ? address.port : port;
301
+
302
+ return {
303
+ baseUrl: `http://127.0.0.1:${boundPort}`,
304
+ close: () =>
305
+ new Promise<void>((resolvePromise) => {
306
+ release("deadline");
307
+ server.closeAllConnections?.();
308
+ server.close(() => resolvePromise());
309
+ })
310
+ };
311
+ }
312
+
313
+ /** Directory the document has on the mapped site. */
314
+ export function documentDirectoryUrl(sitePath: string, baseUrl: string): string {
315
+ const dir = sitePath.slice(0, sitePath.lastIndexOf("/") + 1);
316
+ return `${baseUrl}${dir}`;
317
+ }