@projektemacher/vivliostyle-batch-cli 0.1.2 → 0.2.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/{LICENCE → LICENSE} +1 -1
- package/README.md +73 -30
- package/dist/index.d.ts +211 -42
- package/dist/vivliostyle-batch-cli.js +1544 -396
- package/package.json +31 -20
- package/src/render/chrome.ts +103 -0
- package/src/render/pdf.ts +306 -0
- package/src/render/viewer.ts +46 -0
- package/src/server.ts +300 -0
- package/src/vivliostyle-cli.ts +1151 -444
package/src/server.ts
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
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 ["reason", "ms", "pending", "frames", "canvases", "containers", "mutations", "dpr", "painted", "ready"]) {
|
|
195
|
+
const value = query.get(key);
|
|
196
|
+
if (value === null) continue;
|
|
197
|
+
detail[key] = /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
|
|
198
|
+
}
|
|
199
|
+
res.statusCode = 204;
|
|
200
|
+
res.end();
|
|
201
|
+
release("settled", detail);
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (urlPath !== SETTLE_GATE_PATH) return false;
|
|
206
|
+
|
|
207
|
+
if (released) {
|
|
208
|
+
release("deadline");
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (holdStartedAt === 0) {
|
|
213
|
+
holdStartedAt = Date.now();
|
|
214
|
+
deadlineTimer = setTimeout(() => release("deadline"), settle.deadlineMs);
|
|
215
|
+
deadlineTimer.unref?.();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
pending.push(res);
|
|
219
|
+
res.on("close", () => {
|
|
220
|
+
pending = pending.filter((candidate) => candidate !== res);
|
|
221
|
+
});
|
|
222
|
+
return true;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const handler = (req: IncomingMessage, res: ServerResponse): void => {
|
|
226
|
+
const urlPath = decodeRequestPath(req);
|
|
227
|
+
const query = new URLSearchParams((req.url ?? "").split("?")[1] ?? "");
|
|
228
|
+
|
|
229
|
+
if (handleSettle(urlPath, query, res)) return;
|
|
230
|
+
|
|
231
|
+
// The viewer page lives next to the document so that scripts the page runs
|
|
232
|
+
// resolve relative URLs against the document's directory.
|
|
233
|
+
if (urlPath.endsWith(`/${VIEWER_PAGE_NAME}`)) {
|
|
234
|
+
const html =
|
|
235
|
+
options.viewerFilePath === null || options.viewerFilePath === undefined ? "" : readFileSync(options.viewerFilePath, "utf-8");
|
|
236
|
+
if (html !== "") {
|
|
237
|
+
res.statusCode = 200;
|
|
238
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
239
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
240
|
+
res.end(buildViewerPage(html));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (options.viewerLibDir != null && urlPath.startsWith(`${VIEWER_LIB_PATH}/`)) {
|
|
246
|
+
const relative = urlPath.slice(VIEWER_LIB_PATH.length + 1);
|
|
247
|
+
if (sendFile(res, resolve(options.viewerLibDir, relative))) return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const entry = options.entry;
|
|
251
|
+
if (entry !== null && entry !== undefined && entry.localPath !== null && urlPath === entry.sitePath) {
|
|
252
|
+
if (sendFile(res, resolve(entry.localPath))) return;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const { localPath, remoteUrl } = resolveRequestPath(urlPath, staticMap, assetBases);
|
|
256
|
+
|
|
257
|
+
if (localPath !== null && sendFile(res, localPath)) return;
|
|
258
|
+
|
|
259
|
+
if (remoteUrl !== null && fetchMissing) {
|
|
260
|
+
log(`[fetch] ${urlPath} → ${remoteUrl}`);
|
|
261
|
+
res.statusCode = 302;
|
|
262
|
+
res.setHeader("Location", remoteUrl);
|
|
263
|
+
res.end();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
res.statusCode = 404;
|
|
268
|
+
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
269
|
+
res.end("Not found");
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const server: Server = createServer(handler);
|
|
273
|
+
|
|
274
|
+
await new Promise<void>((resolvePromise, reject) => {
|
|
275
|
+
server.once("error", reject);
|
|
276
|
+
server.listen(port, "127.0.0.1", () => {
|
|
277
|
+
server.off("error", reject);
|
|
278
|
+
resolvePromise();
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
const address = server.address();
|
|
283
|
+
const boundPort = typeof address === "object" && address !== null ? address.port : port;
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
baseUrl: `http://127.0.0.1:${boundPort}`,
|
|
287
|
+
close: () =>
|
|
288
|
+
new Promise<void>((resolvePromise) => {
|
|
289
|
+
release("deadline");
|
|
290
|
+
server.closeAllConnections?.();
|
|
291
|
+
server.close(() => resolvePromise());
|
|
292
|
+
})
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Directory the document has on the mapped site. */
|
|
297
|
+
export function documentDirectoryUrl(sitePath: string, baseUrl: string): string {
|
|
298
|
+
const dir = sitePath.slice(0, sitePath.lastIndexOf("/") + 1);
|
|
299
|
+
return `${baseUrl}${dir}`;
|
|
300
|
+
}
|