@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
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
+ // The inverse of the PDF date form above: XMP Part 1, 8.2.1.2 date.
93
+ const XMP_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+\-]\d{2}:\d{2})$/;
94
+
95
+ /** Reformats an XMP date string as a PDF date; `undefined` when not one. */
96
+ export function xmpDateToPdfDate(value: string): string | undefined {
97
+ const match = XMP_DATE.exec(value);
98
+ if (match === null) return undefined;
99
+ const [, year, month, day, hour, minute, second, zone] = match;
100
+ const offset = zone === "Z" ? "Z" : `${zone.slice(0, 3)}'${zone.slice(4, 6)}`;
101
+ return `D:${year}${month}${day}${hour}${minute}${second}${offset}`;
102
+ }
103
+
104
+ function xmlEscape(text: string): string {
105
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
106
+ }
107
+
108
+ /** dc:title/dc:description: a language alternative with the x-default entry. */
109
+ function languageAlternative(text: string): string {
110
+ return ["<rdf:Alt>", ` <rdf:li xml:lang="x-default">${xmlEscape(text)}</rdf:li>`, "</rdf:Alt>"].join("\n ");
111
+ }
112
+
113
+ /** dc:creator: an ordered sequence; ";" separates individual authors. */
114
+ function creatorSequence(author: string): string {
115
+ const names = author
116
+ .split(";")
117
+ .map((name) => name.trim())
118
+ .filter((name) => name !== "");
119
+ const items = (names.length === 0 ? [author] : names).map((name) => ` <rdf:li>${xmlEscape(name)}</rdf:li>`);
120
+ return ["<rdf:Seq>", ...items, "</rdf:Seq>"].join("\n ");
121
+ }
122
+
123
+ /**
124
+ * Builds the XMP packet for the document. Only defined fields are written;
125
+ * the packet wrapper uses the fixed header id packet scanners look for
126
+ * (XMP Part 1, 7.3.2 makes the wrapper optional, Acrobat rejects its absence).
127
+ */
128
+ export function buildXmpPacket(fields: XmpFields, label?: PdfLabel): string {
129
+ const properties: string[] = [];
130
+
131
+ if (label !== undefined && label.kind === "pdfx" && label.version === "X-4") {
132
+ properties.push(`<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>`);
133
+ }
134
+ if (fields.title !== undefined) {
135
+ properties.push(`<dc:title>\n ${languageAlternative(fields.title)}\n </dc:title>`);
136
+ }
137
+ if (fields.author !== undefined) {
138
+ properties.push(`<dc:creator>\n ${creatorSequence(fields.author)}\n </dc:creator>`);
139
+ }
140
+ if (fields.subject !== undefined) {
141
+ properties.push(`<dc:description>\n ${languageAlternative(fields.subject)}\n </dc:description>`);
142
+ }
143
+ if (fields.keywords !== undefined) {
144
+ properties.push(`<pdf:Keywords>${xmlEscape(fields.keywords)}</pdf:Keywords>`);
145
+ }
146
+ if (fields.producer !== undefined) {
147
+ properties.push(`<pdf:Producer>${xmlEscape(fields.producer)}</pdf:Producer>`);
148
+ }
149
+ if (fields.trapped !== undefined) {
150
+ properties.push(`<pdf:Trapped>${fields.trapped}</pdf:Trapped>`);
151
+ }
152
+ if (fields.creatorTool !== undefined) {
153
+ properties.push(`<xmp:CreatorTool>${xmlEscape(fields.creatorTool)}</xmp:CreatorTool>`);
154
+ }
155
+ if (fields.createDate !== undefined) {
156
+ properties.push(`<xmp:CreateDate>${fields.createDate}</xmp:CreateDate>`);
157
+ }
158
+ if (fields.modifyDate !== undefined) {
159
+ properties.push(`<xmp:ModifyDate>${fields.modifyDate}</xmp:ModifyDate>`);
160
+ }
161
+ if (fields.metadataDate !== undefined) {
162
+ properties.push(`<xmp:MetadataDate>${fields.metadataDate}</xmp:MetadataDate>`);
163
+ }
164
+ if (fields.documentId !== undefined) {
165
+ properties.push(
166
+ `<xmpMM:DocumentID>${xmlEscape(fields.documentId)}</xmpMM:DocumentID>`,
167
+ `<xmpMM:VersionID>1</xmpMM:VersionID>`,
168
+ `<xmpMM:RenditionClass>default</xmpMM:RenditionClass>`
169
+ );
170
+ }
171
+ if (label !== undefined && label.kind === "pdfa") {
172
+ properties.push(`<pdfaid:part>${label.part}</pdfaid:part>`);
173
+ // PDF/A-4 (ISO 19005-4) identifies through the part value alone; the
174
+ // conformance levels a/b/u exist for parts 1 to 3 only.
175
+ if (label.part !== "4" && label.conformance !== undefined) {
176
+ properties.push(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`);
177
+ }
178
+ }
179
+
180
+ const body = [
181
+ `<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>`,
182
+ `<x:xmpmeta xmlns:x="adobe:ns:meta/">`,
183
+ ` <rdf:RDF xmlns:rdf="${NS.rdf}">`,
184
+ ` <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}">`,
185
+ ...properties.map((property) => ` ${property}`),
186
+ ` </rdf:Description>`,
187
+ ` </rdf:RDF>`,
188
+ `</x:xmpmeta>`,
189
+ `<?xpacket end="w"?>`
190
+ ].join("\n");
191
+
192
+ // XML 1.0 (Fifth Edition), 2.11: a processor turns a literal CR into LF
193
+ // before parsing, so a CR in a value survives only as a character reference.
194
+ return `${body.replaceAll("\r", "&#xD;")}\n`;
195
+ }
package/src/server.ts CHANGED
@@ -191,7 +191,19 @@ export async function startStaticServer(options: StaticServerOptions = {}, port
191
191
 
192
192
  if (urlPath === SETTLE_READY_PATH) {
193
193
  const detail: Record<string, unknown> = {};
194
- for (const key of ["reason", "ms", "pending", "frames", "canvases", "containers", "mutations", "dpr", "painted", "ready"]) {
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
+ ]) {
195
207
  const value = query.get(key);
196
208
  if (value === null) continue;
197
209
  detail[key] = /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
@@ -225,6 +237,11 @@ export async function startStaticServer(options: StaticServerOptions = {}, port
225
237
  const handler = (req: IncomingMessage, res: ServerResponse): void => {
226
238
  const urlPath = decodeRequestPath(req);
227
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
+ });
228
245
 
229
246
  if (handleSettle(urlPath, query, res)) return;
230
247