@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -26
- package/dist/index.d.ts +99 -1
- package/dist/vivliostyle-batch-cli.js +990 -46
- package/package.json +23 -19
- package/scripts/convert-docs-pdf.mjs +520 -0
- package/src/metadata.ts +154 -0
- package/src/render/pdf-postprocess.ts +293 -0
- package/src/render/pdf.ts +221 -23
- package/src/render/srgb.icc +0 -0
- package/src/render/xmp.ts +183 -0
- package/src/server.ts +18 -1
- package/src/vivliostyle-cli.ts +324 -18
package/src/render/pdf.ts
CHANGED
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
* The viewer page is served by our own static server (see src/server.ts), so
|
|
10
10
|
* the document's origin — and therefore the base URI of the scripts the page
|
|
11
11
|
* runs — is the site we serve, not an internal viewer base.
|
|
12
|
+
*
|
|
13
|
+
* Printed pages run through the post-processing step (see
|
|
14
|
+
* src/render/pdf-postprocess.ts), which stamps the document metadata and
|
|
15
|
+
* applies the requested PDF/A or PDF/X labeling.
|
|
12
16
|
*/
|
|
13
17
|
|
|
14
18
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
@@ -17,6 +21,8 @@ import puppeteer from "puppeteer-core";
|
|
|
17
21
|
import { PDFDocument } from "pdf-lib";
|
|
18
22
|
import log from "loglevel";
|
|
19
23
|
import { chromeArgs, resolveBrowserExecutable } from "./chrome.js";
|
|
24
|
+
import { postProcessPdf } from "./pdf-postprocess.js";
|
|
25
|
+
import type { PdfLabel } from "./xmp.js";
|
|
20
26
|
|
|
21
27
|
export type ViewerParams = Record<string, string | number | boolean | undefined>;
|
|
22
28
|
|
|
@@ -46,6 +52,11 @@ export type RenderPdfRequest = {
|
|
|
46
52
|
subject?: string;
|
|
47
53
|
keywords?: string;
|
|
48
54
|
language?: string;
|
|
55
|
+
/** Standards labeling applied to the printed PDF (PDF/A or PDF/X). */
|
|
56
|
+
pdfLabel?: PdfLabel;
|
|
57
|
+
/** ICC profile embedded as the OutputIntent; required whenever a label is set. */
|
|
58
|
+
iccProfile?: Uint8Array;
|
|
59
|
+
iccProfileName?: string;
|
|
49
60
|
/** Hard limit for the whole render. */
|
|
50
61
|
timeoutMs?: number;
|
|
51
62
|
/** Wait for the page to report that it settled before printing. */
|
|
@@ -71,20 +82,19 @@ export type RenderPdfResult = {
|
|
|
71
82
|
|
|
72
83
|
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
73
84
|
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return document.save();
|
|
85
|
+
/** The wrapper owns the producer/creator entries of every PDF it prints. */
|
|
86
|
+
const TOOL_IDENTITY = "vivliostyle-batch-cli";
|
|
87
|
+
|
|
88
|
+
function pdfMetadata(request: RenderPdfRequest) {
|
|
89
|
+
return {
|
|
90
|
+
...(request.title === undefined ? {} : { title: request.title }),
|
|
91
|
+
...(request.author === undefined ? {} : { author: request.author }),
|
|
92
|
+
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
93
|
+
...(request.keywords === undefined ? {} : { keywords: request.keywords }),
|
|
94
|
+
...(request.language === undefined ? {} : { language: request.language }),
|
|
95
|
+
creator: TOOL_IDENTITY,
|
|
96
|
+
producer: TOOL_IDENTITY
|
|
97
|
+
};
|
|
88
98
|
}
|
|
89
99
|
|
|
90
100
|
type SettleState = { reason: string; at: number };
|
|
@@ -98,9 +108,13 @@ export type FrameRenderCapability = {
|
|
|
98
108
|
webgpu: boolean;
|
|
99
109
|
canvasCount: number;
|
|
100
110
|
canvases: string;
|
|
101
|
-
iframeCount: number;
|
|
111
|
+
iframeCount: number | null;
|
|
102
112
|
dpr: number;
|
|
103
113
|
resized: string | null;
|
|
114
|
+
/** A-Frame scenes materialized into 2D overlay canvases for print. */
|
|
115
|
+
materialized?: number;
|
|
116
|
+
/** Scene-graph state at print time (debug aid). */
|
|
117
|
+
sceneDiag?: string | null;
|
|
104
118
|
};
|
|
105
119
|
|
|
106
120
|
/**
|
|
@@ -130,8 +144,179 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
130
144
|
try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
|
|
131
145
|
}
|
|
132
146
|
try { window.dispatchEvent(new Event("resize")); } catch(e){}
|
|
147
|
+
// Bridge the viewer's broken page lifecycle. A-Frame scenes can end up
|
|
148
|
+
// loaded-but-never-playing in the paginated tree (render loop, default
|
|
149
|
+
// lights and asset loads all missed their window) while the same page
|
|
150
|
+
// renders fine in a real browser. Start the scene's own loop and give
|
|
151
|
+
// collapsed scenes a box (their display:block stylesheet does not reach
|
|
152
|
+
// the re-parented tree, so unsized unknown elements stay inline).
|
|
153
|
+
try {
|
|
154
|
+
var bridgeScenes = document.querySelectorAll("a-scene");
|
|
155
|
+
for (var bi = 0; bi < bridgeScenes.length; bi++) {
|
|
156
|
+
var bridgeScene = bridgeScenes[bi];
|
|
157
|
+
if (!bridgeScene.isPlaying && typeof bridgeScene.play === "function") {
|
|
158
|
+
try { bridgeScene.play(); } catch (e) {}
|
|
159
|
+
}
|
|
160
|
+
if (bridgeScene.clientWidth === 0 || bridgeScene.clientHeight === 0) {
|
|
161
|
+
var sized = bridgeScene.parentElement;
|
|
162
|
+
while (sized && (sized.clientWidth === 0 || sized.clientHeight === 0)) sized = sized.parentElement;
|
|
163
|
+
if (sized) {
|
|
164
|
+
bridgeScene.style.display = "block";
|
|
165
|
+
bridgeScene.style.width = sized.clientWidth + "px";
|
|
166
|
+
bridgeScene.style.height = sized.clientHeight + "px";
|
|
167
|
+
if (typeof bridgeScene.resize === "function") bridgeScene.resize();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
await nextFrame();
|
|
172
|
+
} catch(e){}
|
|
173
|
+
// Give each scene what it needs to render like the browser does, then
|
|
174
|
+
// materialize its WebGL canvas into a 2D overlay (2D canvases always
|
|
175
|
+
// survive print-to-PDF): re-kick unloaded assets, swap unlit materials for
|
|
176
|
+
// flat ones when no lights exist, render, and blit synchronously.
|
|
177
|
+
var materialized = 0;
|
|
178
|
+
var sceneDiag = "";
|
|
179
|
+
try {
|
|
180
|
+
var scenes = document.querySelectorAll("a-scene");
|
|
181
|
+
for (var si = 0; si < scenes.length; si++) {
|
|
182
|
+
var sceneEl = scenes[si];
|
|
183
|
+
// The viewer clones scenes into its page boxes; only the VISIBLE one
|
|
184
|
+
// (with a box) is what the PDF will show. The hidden original's render
|
|
185
|
+
// would materialize nothing.
|
|
186
|
+
if (!(sceneEl.clientWidth > 0 && sceneEl.clientHeight > 0)) continue;
|
|
187
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
188
|
+
try {
|
|
189
|
+
var gltfEl = sceneEl.querySelector("[gltf-model]");
|
|
190
|
+
if (gltfEl) {
|
|
191
|
+
var gmObj = gltfEl.object3D;
|
|
192
|
+
sceneDiag += " gmKids=" + gmObj.children.length + "/" + (gltfEl.components["gltf-model"] ? String(gltfEl.components["gltf-model"].model !== null) : "nocomp");
|
|
193
|
+
}
|
|
194
|
+
sceneDiag += " tree=" + sceneEl.object3D.children.map(function (c) { return c.type + (c.children ? ":" + c.children.length : ""); }).join("|").slice(0, 110);
|
|
195
|
+
} catch (e) {
|
|
196
|
+
sceneDiag += " diagErr " + String(e).slice(0, 50);
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
var assetItems = sceneEl.querySelectorAll("a-asset-item");
|
|
200
|
+
var assetWaits = [];
|
|
201
|
+
for (var ai = 0; ai < assetItems.length; ai++) {
|
|
202
|
+
var assetEl = assetItems[ai];
|
|
203
|
+
if (assetEl.hasLoaded) continue;
|
|
204
|
+
assetWaits.push(
|
|
205
|
+
new Promise(function (resolve) {
|
|
206
|
+
var settled = false;
|
|
207
|
+
var finish = function () {
|
|
208
|
+
if (settled) return;
|
|
209
|
+
settled = true;
|
|
210
|
+
resolve();
|
|
211
|
+
};
|
|
212
|
+
assetEl.addEventListener("loaded", finish, { once: true });
|
|
213
|
+
assetEl.addEventListener("error", finish, { once: true });
|
|
214
|
+
setTimeout(finish, 8000);
|
|
215
|
+
var src = assetEl.getAttribute("src");
|
|
216
|
+
if (src) assetEl.setAttribute("src", src);
|
|
217
|
+
})
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (assetWaits.length > 0) {
|
|
221
|
+
await Promise.race([Promise.all(assetWaits), new Promise(function (r) { setTimeout(r, 9000); })]);
|
|
222
|
+
}
|
|
223
|
+
} catch (e) {}
|
|
224
|
+
try {
|
|
225
|
+
var lightsFound = 0;
|
|
226
|
+
sceneEl.object3D.traverse(function (n) { if (n.isLight) lightsFound++; });
|
|
227
|
+
if (lightsFound === 0) {
|
|
228
|
+
var basicCtor = null;
|
|
229
|
+
sceneEl.object3D.traverse(function (n) {
|
|
230
|
+
if (n.isMesh && n.material && n.material.isMeshBasicMaterial && basicCtor === null) basicCtor = n.material.constructor;
|
|
231
|
+
});
|
|
232
|
+
if (basicCtor) {
|
|
233
|
+
sceneEl.object3D.traverse(function (n) {
|
|
234
|
+
if (!n.isMesh || !n.material || n.material.isMeshBasicMaterial) return;
|
|
235
|
+
try {
|
|
236
|
+
var m = n.material;
|
|
237
|
+
var flat = new basicCtor({ color: m.color ? m.color.clone() : undefined });
|
|
238
|
+
flat.side = m.side;
|
|
239
|
+
flat.transparent = m.transparent;
|
|
240
|
+
flat.opacity = m.opacity;
|
|
241
|
+
if (m.map) flat.map = m.map;
|
|
242
|
+
n.material = flat;
|
|
243
|
+
} catch (e) {}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} catch(e){}
|
|
248
|
+
try {
|
|
249
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
250
|
+
var glCanvas = sceneEl.canvas;
|
|
251
|
+
if (!glCanvas || glCanvas.width === 0 || glCanvas.height === 0) continue;
|
|
252
|
+
var overlay = document.createElement("canvas");
|
|
253
|
+
overlay.setAttribute("data-viv-gl-overlay", "");
|
|
254
|
+
overlay.width = glCanvas.width;
|
|
255
|
+
overlay.height = glCanvas.height;
|
|
256
|
+
overlay.style.position = "absolute";
|
|
257
|
+
overlay.style.pointerEvents = "none";
|
|
258
|
+
overlay.style.width = glCanvas.clientWidth + "px";
|
|
259
|
+
overlay.style.height = glCanvas.clientHeight + "px";
|
|
260
|
+
var cr = glCanvas.getBoundingClientRect();
|
|
261
|
+
var pr = (glCanvas.offsetParent || document.body).getBoundingClientRect();
|
|
262
|
+
overlay.style.left = cr.left - pr.left + "px";
|
|
263
|
+
overlay.style.top = cr.top - pr.top + "px";
|
|
264
|
+
overlay.style.zIndex = "1";
|
|
265
|
+
(glCanvas.parentNode || document.body).appendChild(overlay);
|
|
266
|
+
overlay.getContext("2d").drawImage(glCanvas, 0, 0);
|
|
267
|
+
// Empty capture = the scene never initialized in this tree (its
|
|
268
|
+
// framework lifecycle was lost to the viewer's re-parenting). Replace
|
|
269
|
+
// it with a fresh copy: the custom-element upgrade re-runs the full
|
|
270
|
+
// framework lifecycle (assets, lights, render loop) in the now-sized
|
|
271
|
+
// tree.
|
|
272
|
+
var empty = true;
|
|
273
|
+
try {
|
|
274
|
+
var dd = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
275
|
+
for (var di = 3; di < dd.length; di += 256) {
|
|
276
|
+
if (dd[di] > 0) {
|
|
277
|
+
empty = false;
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
} catch (e) {
|
|
282
|
+
empty = false;
|
|
283
|
+
}
|
|
284
|
+
if (empty) {
|
|
285
|
+
var fresh = sceneEl.cloneNode(true);
|
|
286
|
+
sceneEl.parentNode.replaceChild(fresh, sceneEl);
|
|
287
|
+
sceneEl = fresh;
|
|
288
|
+
// Enough time for the fresh scene's asset fetches (a real GLB over
|
|
289
|
+
// the network) + first renders.
|
|
290
|
+
await new Promise(function (r) {
|
|
291
|
+
setTimeout(r, 8000);
|
|
292
|
+
});
|
|
293
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
294
|
+
}
|
|
295
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
296
|
+
var gl2 = sceneEl.canvas;
|
|
297
|
+
if (!gl2 || gl2.width === 0 || gl2.height === 0) continue;
|
|
298
|
+
overlay.width = gl2.width;
|
|
299
|
+
overlay.height = gl2.height;
|
|
300
|
+
overlay.getContext("2d").drawImage(gl2, 0, 0);
|
|
301
|
+
materialized++;
|
|
302
|
+
try {
|
|
303
|
+
var od = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
304
|
+
var alphaN = 0;
|
|
305
|
+
var orangeN = 0;
|
|
306
|
+
for (var oi = 3; oi < od.length; oi += 16) {
|
|
307
|
+
if (od[oi] > 0) alphaN++;
|
|
308
|
+
if (od[oi - 3] > 150 && od[oi - 2] > 60 && od[oi - 2] < 200 && od[oi - 1] < 110 && od[oi - 3] > od[oi - 2] + 40) orangeN++;
|
|
309
|
+
}
|
|
310
|
+
glSample = [alphaN, orangeN];
|
|
311
|
+
} catch (e) {}
|
|
312
|
+
} catch (e) {}
|
|
313
|
+
}
|
|
314
|
+
} catch(e){}
|
|
133
315
|
// Hooks like echarts re-init dispose the canvas synchronously; let layout
|
|
134
316
|
// settle a frame before measuring so sizes reflect the repainted state.
|
|
317
|
+
// This also lets render loops refill their drawing buffers after the
|
|
318
|
+
// resize above — drawImage on a just-resized WebGL canvas would read the
|
|
319
|
+
// cleared buffer.
|
|
135
320
|
try { await nextFrame(); } catch(e){}
|
|
136
321
|
if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
|
|
137
322
|
var webgl = false, webgl2 = false;
|
|
@@ -150,7 +335,9 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
150
335
|
canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
|
|
151
336
|
iframeCount: document.querySelectorAll("iframe").length,
|
|
152
337
|
dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
|
|
153
|
-
resized: resized
|
|
338
|
+
resized: resized,
|
|
339
|
+
materialized: materialized,
|
|
340
|
+
sceneDiag: sceneDiag
|
|
154
341
|
};
|
|
155
342
|
})(${JSON.stringify(factor)})`;
|
|
156
343
|
}
|
|
@@ -158,7 +345,7 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
158
345
|
/** Best-effort capability + HiDPI pass over every frame before `page.pdf()`. */
|
|
159
346
|
export async function prepareForPrint(
|
|
160
347
|
page: {
|
|
161
|
-
frames: () => Array<{ evaluate: (script: string) => Promise<unknown> }>;
|
|
348
|
+
frames: () => Array<{ url?: () => string; evaluate: (script: string) => Promise<unknown> }>;
|
|
162
349
|
},
|
|
163
350
|
options: { canvasScale?: number; settleMs?: number } = {}
|
|
164
351
|
): Promise<FrameRenderCapability[]> {
|
|
@@ -169,8 +356,9 @@ export async function prepareForPrint(
|
|
|
169
356
|
for (const frame of page.frames()) {
|
|
170
357
|
try {
|
|
171
358
|
out.push((await frame.evaluate(script)) as FrameRenderCapability);
|
|
172
|
-
} catch {
|
|
359
|
+
} catch (err) {
|
|
173
360
|
// Cross-origin embeds that refuse evaluation still print as pixels.
|
|
361
|
+
log.trace("frame probe failed", frame.url?.() ?? "(frame)", err instanceof Error ? err.message : String(err));
|
|
174
362
|
continue;
|
|
175
363
|
}
|
|
176
364
|
}
|
|
@@ -183,12 +371,13 @@ export async function prepareForPrint(
|
|
|
183
371
|
/** One-line summary for logs: capabilities per frame that owns content. */
|
|
184
372
|
export function summarizeCapabilities(caps: FrameRenderCapability[]): string {
|
|
185
373
|
return caps
|
|
186
|
-
.filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
|
|
374
|
+
.filter((c) => c.canvasCount > 0 || (c.iframeCount ?? 0) > 0 || c.fixture !== null)
|
|
187
375
|
.map(
|
|
188
376
|
(c) =>
|
|
189
377
|
`${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
|
|
190
378
|
`webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
|
|
191
|
-
(c.resized !== null ? ` resized=[${c.resized}]` : "")
|
|
379
|
+
(c.resized !== null ? ` resized=[${c.resized}]` : "") +
|
|
380
|
+
(c.materialized ? ` materialized=${c.materialized} ${c.sceneDiag ?? ""}` : "")
|
|
192
381
|
)
|
|
193
382
|
.join(" | ");
|
|
194
383
|
}
|
|
@@ -228,11 +417,16 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
228
417
|
|
|
229
418
|
page.on("pageerror", (err: unknown) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
|
|
230
419
|
// Viewer and page errors are the usual reason a render produces nothing.
|
|
420
|
+
// Debug/info console messages (fetch traces from the runtime script) are
|
|
421
|
+
// shown at debug level, so -d traces every page-side request.
|
|
422
|
+
const debugConsole = log.getLevel() <= log.levels.DEBUG;
|
|
231
423
|
page.on("console", (message) => {
|
|
232
424
|
const type = message.type();
|
|
233
|
-
if (type !== "error" && type !== "warn") return;
|
|
425
|
+
if (type !== "error" && type !== "warn" && !(debugConsole && (type === "debug" || type === "info"))) return;
|
|
234
426
|
const where = message.location();
|
|
235
|
-
log
|
|
427
|
+
log[debugConsole && type !== "error" && type !== "warn" ? "trace" : "warn"](
|
|
428
|
+
`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`
|
|
429
|
+
);
|
|
236
430
|
});
|
|
237
431
|
page.on("requestfailed", (request) => {
|
|
238
432
|
log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
|
|
@@ -293,7 +487,11 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
293
487
|
tagged: true
|
|
294
488
|
});
|
|
295
489
|
|
|
296
|
-
const stamped = await
|
|
490
|
+
const stamped = await postProcessPdf(pdf, {
|
|
491
|
+
metadata: pdfMetadata(request),
|
|
492
|
+
...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
|
|
493
|
+
...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
|
|
494
|
+
});
|
|
297
495
|
mkdirSync(dirname(request.output), { recursive: true });
|
|
298
496
|
writeFileSync(request.output, stamped);
|
|
299
497
|
|
|
Binary file
|
|
@@ -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("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
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", "
")}\n`;
|
|
183
|
+
}
|
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 [
|
|
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
|
|