@format.dev/zip 0.0.0 → 0.1.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 +8 -25
- package/dist/index.d.mts +279 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1001 -0
- package/dist/index.mjs.map +1 -0
- package/dist/scan.d.mts +61 -0
- package/dist/scan.d.mts.map +1 -0
- package/dist/scan.mjs +263 -0
- package/dist/scan.mjs.map +1 -0
- package/dist/web.d.mts +245 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +13896 -0
- package/dist/web.mjs.map +1 -0
- package/package.json +67 -34
- package/index.d.ts +0 -2
- package/index.js +0 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1001 @@
|
|
|
1
|
+
import { strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { parse } from "node-html-parser";
|
|
3
|
+
import { MIME_TO_EXT } from "@format.dev/utils";
|
|
4
|
+
import { join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
6
|
+
|
|
7
|
+
//#region src/parse-css.ts
|
|
8
|
+
const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
|
|
9
|
+
const CSS_URL_RE = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s][^)]*?))\s*\)/gi;
|
|
10
|
+
const CSS_IMPORT_RE = /@import\s+(?:url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"]+?))\s*\)|"([^"]*)"|'([^']*)')/gi;
|
|
11
|
+
function matchAll$1(input, pattern) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const match of input.matchAll(pattern)) {
|
|
14
|
+
const value = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5];
|
|
15
|
+
if (value != null) out.push(value.trim());
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Pull every `url(...)` target and every `@import` target out of a CSS string.
|
|
21
|
+
* Comments are stripped first so a commented-out reference is never collected.
|
|
22
|
+
* Pure and IO-free.
|
|
23
|
+
*/
|
|
24
|
+
function parseCssRefs(cssText) {
|
|
25
|
+
const withoutComments = cssText.replace(CSS_COMMENT_RE, "");
|
|
26
|
+
const imports = matchAll$1(withoutComments, CSS_IMPORT_RE);
|
|
27
|
+
return {
|
|
28
|
+
urls: matchAll$1(withoutComments.replace(CSS_IMPORT_RE, ""), CSS_URL_RE).filter((ref) => !ref.startsWith("#")),
|
|
29
|
+
imports
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/parse.ts
|
|
35
|
+
/**
|
|
36
|
+
* Pull raw asset references out of an HTML string with a single parse pass.
|
|
37
|
+
* Pure and IO-free.
|
|
38
|
+
*/
|
|
39
|
+
function parseHtmlRefs(html) {
|
|
40
|
+
const root = parse(html);
|
|
41
|
+
const imgSrcs = root.querySelectorAll("img[src]").map((element) => element.getAttribute("src")).filter((src) => src != null);
|
|
42
|
+
const svgHrefs = root.querySelectorAll("image, use").map((element) => element.getAttribute("href") ?? element.getAttribute("xlink:href")).filter((href) => href != null && !href.startsWith("#"));
|
|
43
|
+
const linkHrefs = root.querySelectorAll("link[rel=\"stylesheet\"][href]").map((element) => element.getAttribute("href")).filter((href) => href != null);
|
|
44
|
+
const styleBlocks = root.querySelectorAll("style").map((element) => element.innerHTML);
|
|
45
|
+
const styleAttrs = root.querySelectorAll("[style]").map((element) => element.getAttribute("style") ?? "");
|
|
46
|
+
return {
|
|
47
|
+
imgSrcs,
|
|
48
|
+
svgHrefs,
|
|
49
|
+
linkHrefs,
|
|
50
|
+
inlineCss: [...styleBlocks, ...styleAttrs]
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/errors.ts
|
|
56
|
+
var FormatZipError = class extends Error {
|
|
57
|
+
constructor(code, message, options) {
|
|
58
|
+
super(message, options);
|
|
59
|
+
this.code = code;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
var MissingAssetError = class extends FormatZipError {
|
|
63
|
+
constructor(relPath) {
|
|
64
|
+
super("MISSING_ASSET", `Asset not found: ${relPath}`);
|
|
65
|
+
this.relPath = relPath;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Thrown by `zip()` when the HTML references a local asset that resolves to no
|
|
70
|
+
* file: an empty `src`/`href`/`url("")`, or one like `/`, `.`, or `..` that
|
|
71
|
+
* points at the bundle root (a directory) rather than a file. A same-document
|
|
72
|
+
* fragment (`url(#gradient)`) is not this: it names an element already in the
|
|
73
|
+
* document and is skipped silently. Reported with a warning instead of thrown
|
|
74
|
+
* when `skipMissing` is set.
|
|
75
|
+
*/
|
|
76
|
+
var UnresolvableRefError = class extends FormatZipError {
|
|
77
|
+
constructor(ref) {
|
|
78
|
+
const reason = ref.trim() === "" ? "it is empty" : "it resolves to the bundle root, not a file";
|
|
79
|
+
super("UNRESOLVABLE_REF", `Unresolvable asset reference ${JSON.stringify(ref)}: ${reason}`);
|
|
80
|
+
this.ref = ref;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const toBullets = (items) => items.map((item) => `- ${item}`).join("\n");
|
|
84
|
+
function buildAssetMismatchMessage(detail) {
|
|
85
|
+
const { documentName, mode, missing, known, brokenRemote = [] } = detail;
|
|
86
|
+
const sections = [`Missing assets for document "${documentName}"`];
|
|
87
|
+
if (missing.length) sections.push(`Missing local assets:\n${toBullets(missing)}`);
|
|
88
|
+
if (brokenRemote.length) sections.push(`Unreachable remote assets:\n${toBullets(brokenRemote)}`);
|
|
89
|
+
if (known.length) sections.push(`Known assets:\n${toBullets(known)}`);
|
|
90
|
+
if (missing.length) {
|
|
91
|
+
const placement = "Add the missing files to your shared assets folder (`sharedAssetsDir`) or the document's `assets` folder";
|
|
92
|
+
sections.push(mode === "dynamic" ? `${placement}.` : `${placement}, or consider using dynamic assets. Check the CLI options for \`--assets\`.`);
|
|
93
|
+
}
|
|
94
|
+
if (brokenRemote.length) sections.push("Make sure the remote assets are reachable when the document is built.");
|
|
95
|
+
return sections.join("\n\n");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Thrown by a compiled document wrapper when rendered HTML references assets
|
|
99
|
+
* the bundle cannot supply: local files not in its known-asset set, or remote
|
|
100
|
+
* URLs that could not be loaded. Carries enough context for the consumer to fix
|
|
101
|
+
* the source: add the file to the shared assets folder or the document's
|
|
102
|
+
* `./assets/` folder, switch asset mode, or make the remote URL reachable.
|
|
103
|
+
*/
|
|
104
|
+
var AssetMismatchError = class extends FormatZipError {
|
|
105
|
+
documentName;
|
|
106
|
+
mode;
|
|
107
|
+
missing;
|
|
108
|
+
known;
|
|
109
|
+
remoteRefs;
|
|
110
|
+
brokenRemote;
|
|
111
|
+
constructor(detail) {
|
|
112
|
+
super("ASSET_MISMATCH", buildAssetMismatchMessage(detail));
|
|
113
|
+
this.name = "AssetMismatchError";
|
|
114
|
+
this.documentName = detail.documentName;
|
|
115
|
+
this.mode = detail.mode;
|
|
116
|
+
this.missing = detail.missing;
|
|
117
|
+
this.known = detail.known;
|
|
118
|
+
this.remoteRefs = detail.remoteRefs ?? [];
|
|
119
|
+
this.brokenRemote = detail.brokenRemote ?? [];
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
var InvalidExtensionError = class extends FormatZipError {
|
|
123
|
+
constructor(url, mimeType) {
|
|
124
|
+
super("INVALID_EXTENSION", `Cannot infer asset extension from URL and MIME type: ${url} (${mimeType})`);
|
|
125
|
+
this.url = url;
|
|
126
|
+
this.mimeType = mimeType;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Thrown by `zip()` when the HTML references remote (http/https) assets and
|
|
131
|
+
* `remoteAssets` is not enabled. PDF generation never fetches remote
|
|
132
|
+
* references at render time, so a zip built without them produces a broken
|
|
133
|
+
* PDF — failing loudly here makes the gap visible at the source.
|
|
134
|
+
*/
|
|
135
|
+
var RemoteAssetsDisabledError = class extends FormatZipError {
|
|
136
|
+
constructor(urls) {
|
|
137
|
+
super("REMOTE_ASSETS_DISABLED", `Cannot fetch remote assets.\n\nYour HTML references the following remote assets:\n${toBullets(urls)}\n\nUse \`remoteAssets.enabled\` to fetch assets, or use local assets (recommended).`);
|
|
138
|
+
this.urls = urls;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Thrown when a remote asset cannot be fetched because the network itself
|
|
143
|
+
* failed (offline machine, DNS failure, blocked egress, timeout) — as opposed
|
|
144
|
+
* to the server answering with an error status. The message is written for the
|
|
145
|
+
* common trap: a CI runner with no outbound network access.
|
|
146
|
+
*/
|
|
147
|
+
var RemoteAssetFetchError = class extends FormatZipError {
|
|
148
|
+
constructor(url, cause) {
|
|
149
|
+
super("REMOTE_ASSET_FETCH", `Could not fetch remote asset "${url}". The machine running this build needs network access to that host`, { cause });
|
|
150
|
+
this.url = url;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region package.json
|
|
156
|
+
var version = "0.1.0";
|
|
157
|
+
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/constants.ts
|
|
160
|
+
const platformSuffix = typeof process !== "undefined" && process.platform ? ` (${process.platform}) node ${process.version}` : "";
|
|
161
|
+
const USER_AGENT = `@format.dev/zip/${version}${platformSuffix}`;
|
|
162
|
+
const MANIFEST_FILE_NAME = "format.manifest.json";
|
|
163
|
+
/**
|
|
164
|
+
* Fixed modification time stamped into every ZIP entry so archives are
|
|
165
|
+
* reproducible. Without it, fflate writes `Date.now()` into each entry, so a
|
|
166
|
+
* byte-identical asset set hashes differently on every build and can't be
|
|
167
|
+
* deduplicated by content. Noon UTC on 1980-01-01 (the ZIP epoch) stays at or
|
|
168
|
+
* above the format's 1980 minimum in every timezone. fflate encodes the DOS
|
|
169
|
+
* time from local components, so output is reproducible within a timezone,
|
|
170
|
+
* which is what content dedup from a given runtime needs.
|
|
171
|
+
*/
|
|
172
|
+
const ZIP_EPOCH = Date.UTC(1980, 0, 1, 12);
|
|
173
|
+
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region src/path-utils.ts
|
|
176
|
+
/** Collapse '.', '..', and duplicate slashes, mirroring `path.posix.normalize`. */
|
|
177
|
+
function normalizePath(input) {
|
|
178
|
+
const isAbsolute = input.startsWith("/");
|
|
179
|
+
const out = [];
|
|
180
|
+
for (const segment of input.split("/")) {
|
|
181
|
+
if (segment === "" || segment === ".") continue;
|
|
182
|
+
if (segment === "..") {
|
|
183
|
+
if (out.length > 0 && out[out.length - 1] !== "..") out.pop();
|
|
184
|
+
else if (!isAbsolute) out.push("..");
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
out.push(segment);
|
|
188
|
+
}
|
|
189
|
+
const joined = out.join("/");
|
|
190
|
+
if (isAbsolute) return "/" + joined;
|
|
191
|
+
return joined || ".";
|
|
192
|
+
}
|
|
193
|
+
/** Split a path into dir/name/ext, mirroring `path.posix.parse`. */
|
|
194
|
+
function parsePath(input) {
|
|
195
|
+
const lastSlash = input.lastIndexOf("/");
|
|
196
|
+
const dir = lastSlash >= 0 ? input.slice(0, lastSlash) : "";
|
|
197
|
+
const base = lastSlash >= 0 ? input.slice(lastSlash + 1) : input;
|
|
198
|
+
const lastDot = base.lastIndexOf(".");
|
|
199
|
+
if (lastDot <= 0) return {
|
|
200
|
+
dir,
|
|
201
|
+
name: base,
|
|
202
|
+
ext: ""
|
|
203
|
+
};
|
|
204
|
+
return {
|
|
205
|
+
dir,
|
|
206
|
+
name: base.slice(0, lastDot),
|
|
207
|
+
ext: base.slice(lastDot)
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** Join and normalize '/'-separated segments, mirroring `path.posix.join`. */
|
|
211
|
+
function joinPath(...segments) {
|
|
212
|
+
return normalizePath(segments.filter(Boolean).join("/"));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Small, fast, non-cryptographic hash (FNV-1a, 32-bit) rendered as 8 hex chars.
|
|
216
|
+
* Used only to give a remote asset's query string a stable, collision-resistant
|
|
217
|
+
* filename suffix — it is not security-sensitive.
|
|
218
|
+
*/
|
|
219
|
+
function hash8(input) {
|
|
220
|
+
let hash = 2166136261;
|
|
221
|
+
for (let index = 0; index < input.length; index++) {
|
|
222
|
+
hash ^= input.charCodeAt(index);
|
|
223
|
+
hash = Math.imul(hash, 16777619);
|
|
224
|
+
}
|
|
225
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/helpers.ts
|
|
230
|
+
/**
|
|
231
|
+
* Fetch a remote asset and return its bytes, parsed MIME type, and the
|
|
232
|
+
* validators the server sent, so a caller holding the bytes can later ask
|
|
233
|
+
* whether they changed with {@link fetchRemoteIfChanged}.
|
|
234
|
+
*
|
|
235
|
+
* Uses `fetch` + `arrayBuffer()` rather than a Node stream so the remote path
|
|
236
|
+
* stays portable across Node, workers, and browsers.
|
|
237
|
+
*
|
|
238
|
+
* @throws {RemoteAssetFetchError} when the network itself fails (offline, DNS,
|
|
239
|
+
* blocked egress, timeout). HTTP error statuses throw a plain Error — the
|
|
240
|
+
* server was reachable, so it's a different problem.
|
|
241
|
+
*/
|
|
242
|
+
async function fetchRemote(params) {
|
|
243
|
+
return readRemoteResponse(await requestRemote(params), params.url);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Ask the server whether a remote asset changed since `validators` were
|
|
247
|
+
* issued. Returns `null` on `304 Not Modified`, otherwise the full asset. A
|
|
248
|
+
* server that sent no validators gets an ordinary request, so this always
|
|
249
|
+
* downloads there.
|
|
250
|
+
*
|
|
251
|
+
* @throws {RemoteAssetFetchError} and plain HTTP errors, as {@link fetchRemote}.
|
|
252
|
+
*/
|
|
253
|
+
async function fetchRemoteIfChanged(params) {
|
|
254
|
+
const { validators } = params;
|
|
255
|
+
const headers = new Headers(params.headers);
|
|
256
|
+
if (validators.etag) headers.set("If-None-Match", validators.etag);
|
|
257
|
+
if (validators.lastModified) headers.set("If-Modified-Since", validators.lastModified);
|
|
258
|
+
const response = await requestRemote({
|
|
259
|
+
...params,
|
|
260
|
+
headers
|
|
261
|
+
});
|
|
262
|
+
if (response.status === 304) return null;
|
|
263
|
+
return readRemoteResponse(response, params.url);
|
|
264
|
+
}
|
|
265
|
+
async function requestRemote(params) {
|
|
266
|
+
const { url, headers: requestHeaders, timeoutMs = 15e3 } = params;
|
|
267
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
268
|
+
const headers = new Headers(requestHeaders);
|
|
269
|
+
if (!headers.has("User-Agent")) headers.set("User-Agent", USER_AGENT);
|
|
270
|
+
try {
|
|
271
|
+
return await fetch(url, {
|
|
272
|
+
signal,
|
|
273
|
+
redirect: "follow",
|
|
274
|
+
headers
|
|
275
|
+
});
|
|
276
|
+
} catch (cause) {
|
|
277
|
+
throw new RemoteAssetFetchError(url, cause);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async function readRemoteResponse(response, url) {
|
|
281
|
+
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
|
|
282
|
+
return {
|
|
283
|
+
bytes: new Uint8Array(await response.arrayBuffer()),
|
|
284
|
+
mimeType: parseContentType(response.headers.get("content-type") || void 0),
|
|
285
|
+
validators: {
|
|
286
|
+
etag: response.headers.get("etag") ?? void 0,
|
|
287
|
+
lastModified: response.headers.get("last-modified") ?? void 0
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* The fetcher every remote read in this package goes through: the caller's
|
|
293
|
+
* `remoteAssets.fetch` when they supplied one, otherwise {@link fetchRemote}.
|
|
294
|
+
* Binds the headers and timeout from the same options so a custom fetcher gets
|
|
295
|
+
* the same request shape the built-in one would have used.
|
|
296
|
+
*/
|
|
297
|
+
function remoteFetcher(options) {
|
|
298
|
+
const fetcher = options?.remoteAssets?.fetch ?? fetchRemote;
|
|
299
|
+
return (url) => fetcher({
|
|
300
|
+
url,
|
|
301
|
+
headers: options?.remoteAssets?.headers,
|
|
302
|
+
timeoutMs: options?.remoteAssets?.timeoutMs
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Probe each remote URL and return the ones that can't be loaded — a failed
|
|
307
|
+
* request or a non-OK status, the same "broken" definition `fetchRemote` uses.
|
|
308
|
+
* Collects every failure rather than stopping at the first, so callers can report
|
|
309
|
+
* the full set. Runs the probes concurrently.
|
|
310
|
+
*/
|
|
311
|
+
async function findBrokenRemoteAssets(params) {
|
|
312
|
+
const { urls, headers, timeoutMs, fetch: customFetch } = params;
|
|
313
|
+
const probe = customFetch ?? fetchRemote;
|
|
314
|
+
return (await Promise.all(urls.map(async (url) => {
|
|
315
|
+
try {
|
|
316
|
+
await probe({
|
|
317
|
+
url,
|
|
318
|
+
headers,
|
|
319
|
+
timeoutMs
|
|
320
|
+
});
|
|
321
|
+
return null;
|
|
322
|
+
} catch {
|
|
323
|
+
return url;
|
|
324
|
+
}
|
|
325
|
+
}))).filter((url) => url !== null);
|
|
326
|
+
}
|
|
327
|
+
function parseContentType(header) {
|
|
328
|
+
if (!header) return;
|
|
329
|
+
const [mime] = header.split(";", 1);
|
|
330
|
+
return mime?.trim().toLowerCase();
|
|
331
|
+
}
|
|
332
|
+
function isRemoteOrigin(href) {
|
|
333
|
+
try {
|
|
334
|
+
const url = new URL(href);
|
|
335
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
336
|
+
} catch {
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function isSameOrigin(href, base) {
|
|
341
|
+
try {
|
|
342
|
+
return new URL(href, base).origin === base;
|
|
343
|
+
} catch {
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function randomLocalOrigin() {
|
|
348
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
349
|
+
if (uuid) return `https://${uuid}`;
|
|
350
|
+
return `https://local-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;
|
|
351
|
+
}
|
|
352
|
+
const LOCAL_ORIGIN_BASE = randomLocalOrigin();
|
|
353
|
+
const isLocalOrigin = (href) => isSameOrigin(href, LOCAL_ORIGIN_BASE);
|
|
354
|
+
function normalizeDir(rawDir) {
|
|
355
|
+
const abs = normalizePath("/" + rawDir.replace(/^\/+/, ""));
|
|
356
|
+
return abs === "/" ? "" : abs.slice(1);
|
|
357
|
+
}
|
|
358
|
+
function urlToZipName(url, mimeType) {
|
|
359
|
+
const u = new URL(url);
|
|
360
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error(`Unsupported protocol: ${u.protocol}`);
|
|
361
|
+
let pathname = u.pathname;
|
|
362
|
+
if (pathname.endsWith("/")) pathname += "index";
|
|
363
|
+
let { dir, name, ext } = parsePath(pathname);
|
|
364
|
+
if (!ext && mimeType) ext = MIME_TO_EXT[mimeType.toLowerCase()];
|
|
365
|
+
if (!ext) throw new InvalidExtensionError(url, mimeType);
|
|
366
|
+
const qs = [...u.searchParams.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("&");
|
|
367
|
+
const queryHash = qs ? `__${hash8(qs)}` : "";
|
|
368
|
+
const hostname = u.hostname.toLowerCase();
|
|
369
|
+
const port = `_${u.port || (u.protocol === "https:" ? "443" : "80")}`;
|
|
370
|
+
const safeDir = normalizeDir(dir);
|
|
371
|
+
const safeName = `${name.replace(/[^\w.-]/g, "_")}${queryHash}${ext}`;
|
|
372
|
+
return joinPath("remote", `${hostname}${port}`, safeDir, safeName);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Resolve a local href to a safe, POSIX-style relative path for a zip entry.
|
|
376
|
+
* - Strips query/hash
|
|
377
|
+
* - Resolves dot-segments relative to baseRel
|
|
378
|
+
* - Drops leading slashes
|
|
379
|
+
* - Normalizes duplicate slashes
|
|
380
|
+
*
|
|
381
|
+
* Returns `null` for a ref that names no file to bundle: a bare fragment
|
|
382
|
+
* (`#gradient`), a `data:` URL, or anything that resolves to the bundle root
|
|
383
|
+
* itself. This is a pure path helper — what a null means (skip a fragment, or
|
|
384
|
+
* report a broken `src`/`href`/`url()`) is the caller's policy, not this
|
|
385
|
+
* function's.
|
|
386
|
+
*/
|
|
387
|
+
function resolveLocalRef(href, baseRel = ".") {
|
|
388
|
+
if (href.startsWith("#") || href.startsWith("data:")) return null;
|
|
389
|
+
const base = new URL("/" + normalizePath(baseRel), LOCAL_ORIGIN_BASE);
|
|
390
|
+
let pathname = new URL(href, base).pathname.replace(/^\/+/, "");
|
|
391
|
+
pathname = normalizePath(pathname);
|
|
392
|
+
if (pathname === ".") return null;
|
|
393
|
+
return pathname;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
//#endregion
|
|
397
|
+
//#region src/zip.ts
|
|
398
|
+
const utf8 = new TextDecoder("utf-8");
|
|
399
|
+
/**
|
|
400
|
+
* Resolve a local ref to its bundle path, or surface it when it names no file to
|
|
401
|
+
* bundle. A bare `#id` fragment is a same-document reference (an SVG paint
|
|
402
|
+
* server, clip-path, mask, or filter), so it returns null and is skipped
|
|
403
|
+
* silently. Anything else that resolves to nothing is a broken reference — an
|
|
404
|
+
* empty `src`/`href`/`url("")`, or one like `/` or `.` that points at the bundle
|
|
405
|
+
* root — so it is reported rather than dropped: a warning when `skipMissing` is
|
|
406
|
+
* set, an {@link UnresolvableRefError} otherwise.
|
|
407
|
+
*/
|
|
408
|
+
function resolveLocalOrReport(ref, baseRel, options) {
|
|
409
|
+
const local = resolveLocalRef(ref, baseRel);
|
|
410
|
+
if (local) return local;
|
|
411
|
+
if (ref.startsWith("#")) return null;
|
|
412
|
+
if (options?.skipMissing) {
|
|
413
|
+
console.warn(`[zip] Unresolvable asset reference, skipping: ${JSON.stringify(ref)}`);
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
throw new UnresolvableRefError(ref);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Read a local CSS file through the resolver, record it, then walk its contents.
|
|
420
|
+
*/
|
|
421
|
+
async function processCssFile(cssRel, context) {
|
|
422
|
+
if (context.visitedCss.has(cssRel)) return;
|
|
423
|
+
context.visitedCss.add(cssRel);
|
|
424
|
+
const bytes = await context.resolve(cssRel);
|
|
425
|
+
if (!bytes) {
|
|
426
|
+
console.warn(`[zip] CSS file not found, skipping: ${cssRel}`);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
context.assetPaths.add(cssRel);
|
|
430
|
+
await processCssContent(utf8.decode(bytes), cssRel, context);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Fetch a remote CSS file, record its URL, then walk its contents.
|
|
434
|
+
*/
|
|
435
|
+
async function processRemoteCssFile(remoteUrl, context) {
|
|
436
|
+
if (context.visitedCss.has(remoteUrl)) return;
|
|
437
|
+
context.visitedCss.add(remoteUrl);
|
|
438
|
+
try {
|
|
439
|
+
const { bytes } = await remoteFetcher(context.options)(remoteUrl);
|
|
440
|
+
context.assetPaths.add(remoteUrl);
|
|
441
|
+
await processCssContent(utf8.decode(bytes), ".", context, remoteUrl);
|
|
442
|
+
} catch (error) {
|
|
443
|
+
if (context.options?.skipMissing) {
|
|
444
|
+
console.log(`[zip] Could not fetch remote CSS "${remoteUrl}". Continuing as skipMissing is set.`, error);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
throw error;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Walk one CSS string: record every local/remote url() target and follow every
|
|
452
|
+
* @import. `baseRel` is the referring file's path so relative refs resolve
|
|
453
|
+
* correctly; `remoteBaseUrl` switches resolution into remote-URL space.
|
|
454
|
+
*/
|
|
455
|
+
async function processCssContent(cssText, baseRel, context, remoteBaseUrl) {
|
|
456
|
+
const { assetPaths, options } = context;
|
|
457
|
+
const allowRemote = options?.remoteAssets?.enabled === true;
|
|
458
|
+
const { urls, imports } = parseCssRefs(cssText);
|
|
459
|
+
const importPromises = [];
|
|
460
|
+
for (const importPath of imports) {
|
|
461
|
+
if (remoteBaseUrl) {
|
|
462
|
+
if (!allowRemote) continue;
|
|
463
|
+
try {
|
|
464
|
+
const url = new URL(importPath, remoteBaseUrl).toString();
|
|
465
|
+
if (isRemoteOrigin(url)) importPromises.push(processRemoteCssFile(url, context));
|
|
466
|
+
} catch (error) {
|
|
467
|
+
console.warn(`[zip] Error parsing remote CSS @import (base: ${remoteBaseUrl}, path: ${importPath})`, error);
|
|
468
|
+
}
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (isLocalOrigin(importPath)) {
|
|
472
|
+
const local = resolveLocalOrReport(importPath, baseRel, options);
|
|
473
|
+
if (local) importPromises.push(processCssFile(local, context));
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (isRemoteOrigin(importPath)) {
|
|
477
|
+
if (allowRemote) {
|
|
478
|
+
importPromises.push(processRemoteCssFile(new URL(importPath).toString(), context));
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
context.skippedRemote.add(importPath);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
for (const ref of urls) {
|
|
485
|
+
if (remoteBaseUrl) {
|
|
486
|
+
if (!allowRemote) continue;
|
|
487
|
+
try {
|
|
488
|
+
const url = new URL(ref, remoteBaseUrl).toString();
|
|
489
|
+
if (isRemoteOrigin(url)) assetPaths.add(url);
|
|
490
|
+
} catch (error) {
|
|
491
|
+
console.warn(`[zip] Error parsing remote CSS url() (base: ${remoteBaseUrl}, path: ${ref})`, error);
|
|
492
|
+
}
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
if (isLocalOrigin(ref)) {
|
|
496
|
+
const local = resolveLocalOrReport(ref, baseRel, options);
|
|
497
|
+
if (local) assetPaths.add(local);
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (isRemoteOrigin(ref)) {
|
|
501
|
+
if (allowRemote) {
|
|
502
|
+
assetPaths.add(new URL(ref).toString());
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
context.skippedRemote.add(ref);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
await Promise.all(importPromises);
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Collect every asset path referenced by `html`: `<img src>`, inline-SVG
|
|
512
|
+
* `<image>`/`<use>` hrefs, `<link rel=stylesheet>` (following nested @import
|
|
513
|
+
* chains via the resolver), and `url(...)` in `<style>` blocks and style
|
|
514
|
+
* attributes. Local refs come back as bundle-root relative paths; remote URLs
|
|
515
|
+
* are included only when `options.remoteAssets.enabled` is set.
|
|
516
|
+
*
|
|
517
|
+
* @throws {RemoteAssetsDisabledError} when remote refs are found and
|
|
518
|
+
* `remoteAssets` is not enabled — a zip without them produces a broken PDF.
|
|
519
|
+
*/
|
|
520
|
+
async function collectAssetPaths(html, resolve$1, options) {
|
|
521
|
+
const { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parseHtmlRefs(html);
|
|
522
|
+
const assetPaths = /* @__PURE__ */ new Set();
|
|
523
|
+
const allowRemote = options?.remoteAssets?.enabled === true;
|
|
524
|
+
const context = {
|
|
525
|
+
resolve: resolve$1,
|
|
526
|
+
assetPaths,
|
|
527
|
+
visitedCss: /* @__PURE__ */ new Set(),
|
|
528
|
+
skippedRemote: /* @__PURE__ */ new Set(),
|
|
529
|
+
options
|
|
530
|
+
};
|
|
531
|
+
const addElementRef = (ref) => {
|
|
532
|
+
if (isLocalOrigin(ref)) {
|
|
533
|
+
const local = resolveLocalOrReport(ref, ".", options);
|
|
534
|
+
if (local) assetPaths.add(local);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (!isRemoteOrigin(ref)) return;
|
|
538
|
+
if (allowRemote) {
|
|
539
|
+
assetPaths.add(ref);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
context.skippedRemote.add(ref);
|
|
543
|
+
};
|
|
544
|
+
for (const src of imgSrcs) addElementRef(src);
|
|
545
|
+
for (const href of svgHrefs) addElementRef(href);
|
|
546
|
+
const handleError = (error) => {
|
|
547
|
+
if (options?.skipMissing) {
|
|
548
|
+
console.warn("[zip] Error processing CSS content. Continuing as skipMissing is set.");
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
throw error;
|
|
552
|
+
};
|
|
553
|
+
const cssPromises = [];
|
|
554
|
+
for (const href of linkHrefs) {
|
|
555
|
+
if (isLocalOrigin(href)) {
|
|
556
|
+
const local = resolveLocalOrReport(href, ".", options);
|
|
557
|
+
if (local) cssPromises.push(processCssFile(local, context).catch(handleError));
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
if (!isRemoteOrigin(href)) continue;
|
|
561
|
+
if (allowRemote) {
|
|
562
|
+
cssPromises.push(processRemoteCssFile(href, context).catch(handleError));
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
context.skippedRemote.add(href);
|
|
566
|
+
}
|
|
567
|
+
for (const cssText of inlineCss) cssPromises.push(processCssContent(cssText, ".", context).catch(handleError));
|
|
568
|
+
await Promise.all(cssPromises);
|
|
569
|
+
if (!allowRemote && context.skippedRemote.size > 0) throw new RemoteAssetsDisabledError([...context.skippedRemote].sort());
|
|
570
|
+
return assetPaths;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Resolve every collected asset to its bytes, keyed by zip entry name. Local
|
|
574
|
+
* paths go through the resolver; remote URLs (internal) are fetched and renamed
|
|
575
|
+
* deterministically, with a manifest mapping original URLs to entries.
|
|
576
|
+
*/
|
|
577
|
+
async function buildFileMap(assetPaths, resolve$1, options) {
|
|
578
|
+
const files = {};
|
|
579
|
+
const allowRemote = options?.remoteAssets?.enabled ?? false;
|
|
580
|
+
const localPaths = [...assetPaths].filter(isLocalOrigin);
|
|
581
|
+
const localEntries = await Promise.all(localPaths.map(async (name) => ({
|
|
582
|
+
name,
|
|
583
|
+
bytes: await resolve$1(name)
|
|
584
|
+
})));
|
|
585
|
+
for (const { name, bytes } of localEntries) {
|
|
586
|
+
if (bytes) {
|
|
587
|
+
files[name] = bytes;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
if (options?.skipMissing) {
|
|
591
|
+
console.warn(`[zip] Missing local asset, skipping: ${name}`);
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
throw new MissingAssetError(name);
|
|
595
|
+
}
|
|
596
|
+
if (!allowRemote) return files;
|
|
597
|
+
const remotePaths = [...assetPaths].filter(isRemoteOrigin);
|
|
598
|
+
const manifest = {};
|
|
599
|
+
const fetchOne = remoteFetcher(options);
|
|
600
|
+
const remoteEntries = await Promise.all(remotePaths.map(async (url) => {
|
|
601
|
+
try {
|
|
602
|
+
const { bytes, mimeType } = await fetchOne(url);
|
|
603
|
+
return {
|
|
604
|
+
url,
|
|
605
|
+
name: urlToZipName(url, mimeType),
|
|
606
|
+
bytes
|
|
607
|
+
};
|
|
608
|
+
} catch (error) {
|
|
609
|
+
if (options?.skipMissing) {
|
|
610
|
+
console.warn(`[zip] Missing remote asset, skipping: ${url}`);
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
console.error(`[zip] Failed to fetch external asset: ${url}`, error);
|
|
614
|
+
throw new MissingAssetError(url);
|
|
615
|
+
}
|
|
616
|
+
}));
|
|
617
|
+
for (const entry of remoteEntries) {
|
|
618
|
+
if (!entry) continue;
|
|
619
|
+
manifest[entry.url] = entry.name;
|
|
620
|
+
files[entry.name] = entry.bytes;
|
|
621
|
+
}
|
|
622
|
+
files[MANIFEST_FILE_NAME] = strToU8(JSON.stringify({ remoteAssets: manifest }));
|
|
623
|
+
return files;
|
|
624
|
+
}
|
|
625
|
+
/** Entry names of an existing archive. A static-mode zip's entries are the document's known-asset set. */
|
|
626
|
+
function listZipEntries(bytes) {
|
|
627
|
+
return Object.keys(unzipSync(bytes)).sort();
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* The remote assets an archive already holds, from the manifest
|
|
631
|
+
* {@link mergeRemoteAssets} writes, sorted by URL. Empty when the archive has
|
|
632
|
+
* no manifest. Lets a caller compare what was bundled with what the server
|
|
633
|
+
* serves now.
|
|
634
|
+
*/
|
|
635
|
+
function readRemoteAssets(bytes) {
|
|
636
|
+
const entries = unzipSync(bytes);
|
|
637
|
+
const manifestEntry = entries[MANIFEST_FILE_NAME];
|
|
638
|
+
if (!manifestEntry) return [];
|
|
639
|
+
try {
|
|
640
|
+
const { remoteAssets = {} } = JSON.parse(utf8.decode(manifestEntry));
|
|
641
|
+
return Object.entries(remoteAssets).filter(([, name]) => entries[name] !== void 0).map(([url, name]) => ({
|
|
642
|
+
url,
|
|
643
|
+
bytes: entries[name]
|
|
644
|
+
})).sort((a, b) => a.url.localeCompare(b.url));
|
|
645
|
+
} catch {
|
|
646
|
+
return [];
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Fetch every remote (http/https) asset `html` references and merge it into an
|
|
651
|
+
* existing archive, alongside a manifest mapping each URL to its zip entry.
|
|
652
|
+
* Remote stylesheets are walked too, so a remote CSS file's fonts and images
|
|
653
|
+
* come along with it. Local CSS already inside the archive is also walked for
|
|
654
|
+
* remote references.
|
|
655
|
+
*
|
|
656
|
+
* URLs already present in the archive's manifest are not fetched again, so
|
|
657
|
+
* calling this repeatedly over the same archive is idempotent and cheap.
|
|
658
|
+
*
|
|
659
|
+
* @returns the merged archive bytes; the input `zip` unchanged when `html`
|
|
660
|
+
* references nothing remote that isn't already bundled; or `undefined` when
|
|
661
|
+
* there is no input archive and nothing remote to fetch.
|
|
662
|
+
* @throws {RemoteAssetFetchError} when the network itself is unreachable.
|
|
663
|
+
*/
|
|
664
|
+
async function mergeRemoteAssets(args) {
|
|
665
|
+
const { html, zip: existingZip, options } = args;
|
|
666
|
+
const entries = existingZip ? unzipSync(existingZip) : {};
|
|
667
|
+
const manifest = {};
|
|
668
|
+
const manifestEntry = entries[MANIFEST_FILE_NAME];
|
|
669
|
+
if (manifestEntry) try {
|
|
670
|
+
const parsed = JSON.parse(utf8.decode(manifestEntry));
|
|
671
|
+
Object.assign(manifest, parsed.remoteAssets);
|
|
672
|
+
} catch {
|
|
673
|
+
console.warn(`[zip] Could not parse existing ${MANIFEST_FILE_NAME}, rebuilding the remote manifest`);
|
|
674
|
+
}
|
|
675
|
+
const resolveFromZip = async (relPath) => entries[relPath] ?? null;
|
|
676
|
+
const remoteUrls = [...await collectAssetPaths(html, resolveFromZip, {
|
|
677
|
+
...options,
|
|
678
|
+
remoteAssets: {
|
|
679
|
+
...options?.remoteAssets,
|
|
680
|
+
enabled: true
|
|
681
|
+
}
|
|
682
|
+
})].filter(isRemoteOrigin).filter((url) => !(url in manifest));
|
|
683
|
+
if (remoteUrls.length === 0) return existingZip;
|
|
684
|
+
const fetchOne = remoteFetcher(options);
|
|
685
|
+
const fetched = await Promise.all(remoteUrls.map(async (url) => {
|
|
686
|
+
const { bytes, mimeType } = await fetchOne(url);
|
|
687
|
+
return {
|
|
688
|
+
url,
|
|
689
|
+
name: urlToZipName(url, mimeType),
|
|
690
|
+
bytes
|
|
691
|
+
};
|
|
692
|
+
}));
|
|
693
|
+
for (const { url, name, bytes } of fetched) {
|
|
694
|
+
manifest[url] = name;
|
|
695
|
+
entries[name] = bytes;
|
|
696
|
+
}
|
|
697
|
+
entries[MANIFEST_FILE_NAME] = strToU8(JSON.stringify({ remoteAssets: manifest }));
|
|
698
|
+
return zipSync(entries, {
|
|
699
|
+
level: deflateLevel(options),
|
|
700
|
+
mtime: ZIP_EPOCH
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
function deflateLevel(options) {
|
|
704
|
+
const level = options?.zlib?.level;
|
|
705
|
+
return typeof level === "number" && level >= 0 && level <= 9 ? level : 6;
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Build a ZIP archive of every asset `html` references, resolving bytes through
|
|
709
|
+
* `resolve`. Runs in Node, workers, and browsers (node-html-parser scans the
|
|
710
|
+
* HTML).
|
|
711
|
+
*
|
|
712
|
+
* @returns the archive bytes, or `undefined` when `html` references no assets.
|
|
713
|
+
* @throws {MissingAssetError} when `skipMissing` is unset and the resolver
|
|
714
|
+
* returns `null` for a referenced asset.
|
|
715
|
+
* @throws {UnresolvableRefError} when `skipMissing` is unset and a local ref
|
|
716
|
+
* names no file — an empty `src`/`href`/`url("")`, or one like `/` or `.` that
|
|
717
|
+
* resolves to the bundle root.
|
|
718
|
+
* @throws {RemoteAssetsDisabledError} when `html` references remote (http/https)
|
|
719
|
+
* assets and `remoteAssets` is not enabled — they would be missing from the
|
|
720
|
+
* archive and the PDF.
|
|
721
|
+
*/
|
|
722
|
+
async function zip$1(html, resolve$1, options) {
|
|
723
|
+
const assetPaths = await collectAssetPaths(html, resolve$1, options);
|
|
724
|
+
if (assetPaths.size === 0) return;
|
|
725
|
+
return zipSync(await buildFileMap(assetPaths, resolve$1, options), {
|
|
726
|
+
level: deflateLevel(options),
|
|
727
|
+
mtime: ZIP_EPOCH
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
//#endregion
|
|
732
|
+
//#region src/dir-resolver.ts
|
|
733
|
+
/**
|
|
734
|
+
* Node-only resolver that reads asset paths from a filesystem directory.
|
|
735
|
+
* Returns `null` for any path that does not resolve to a readable file, or that
|
|
736
|
+
* resolves outside the directory (path-traversal guard).
|
|
737
|
+
*
|
|
738
|
+
* This is what the Node `zip(html, dir)` overload uses under the hood, and the
|
|
739
|
+
* compile-time resolver. It pulls in `node:fs`, so it lives in its own module
|
|
740
|
+
* and is never reachable from the `@format.dev/zip/web` entry.
|
|
741
|
+
*/
|
|
742
|
+
function dirResolver(dir) {
|
|
743
|
+
const root = resolve(dir);
|
|
744
|
+
return async (relPath) => {
|
|
745
|
+
const target = resolve(join(root, relPath));
|
|
746
|
+
if (target !== root && !target.startsWith(root + sep)) return null;
|
|
747
|
+
try {
|
|
748
|
+
return new Uint8Array(await readFile(target));
|
|
749
|
+
} catch (error) {
|
|
750
|
+
const code = error.code;
|
|
751
|
+
if (code === "ENOENT" || code === "EISDIR" || code === "ENOTDIR") return null;
|
|
752
|
+
throw error;
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/junk-files.ts
|
|
759
|
+
const EXACT_JUNK_NAMES = new Set([
|
|
760
|
+
".DS_Store",
|
|
761
|
+
".Spotlight-V100",
|
|
762
|
+
".DocumentRevisions-V100",
|
|
763
|
+
".fseventsd",
|
|
764
|
+
".TemporaryItems",
|
|
765
|
+
".Trashes",
|
|
766
|
+
".VolumeIcon.icns",
|
|
767
|
+
".apdisk",
|
|
768
|
+
".directory"
|
|
769
|
+
]);
|
|
770
|
+
const CASE_INSENSITIVE_JUNK_NAMES = new Set([
|
|
771
|
+
"thumbs.db",
|
|
772
|
+
"ehthumbs.db",
|
|
773
|
+
"ehthumbs_vista.db",
|
|
774
|
+
"desktop.ini"
|
|
775
|
+
]);
|
|
776
|
+
/**
|
|
777
|
+
* True when `name` (a single path segment, not a full path) is OS-generated
|
|
778
|
+
* junk rather than a real file. Used to keep these out of asset listings,
|
|
779
|
+
* archives, and cache hashes.
|
|
780
|
+
*/
|
|
781
|
+
function isSystemJunkFile(name) {
|
|
782
|
+
if (EXACT_JUNK_NAMES.has(name)) return true;
|
|
783
|
+
if (CASE_INSENSITIVE_JUNK_NAMES.has(name.toLowerCase())) return true;
|
|
784
|
+
const isAppleDoubleFork = name.startsWith("._");
|
|
785
|
+
const isLinuxTrash = name.startsWith(".Trash-");
|
|
786
|
+
const isNfsLock = name.startsWith(".nfs");
|
|
787
|
+
return isAppleDoubleFork || isLinuxTrash || isNfsLock;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
//#endregion
|
|
791
|
+
//#region src/zip-dir.ts
|
|
792
|
+
/**
|
|
793
|
+
* Zip the entire contents of a directory, preserving relative paths as entry
|
|
794
|
+
* names ('/'-separated). No HTML scanning — this is the static-asset-mode
|
|
795
|
+
* builder: every known asset ships, so any render works. Only OS-generated
|
|
796
|
+
* junk (`.DS_Store`, `Thumbs.db`, and friends) is skipped.
|
|
797
|
+
*
|
|
798
|
+
* Node-only (reads the filesystem).
|
|
799
|
+
*
|
|
800
|
+
* @returns the archive bytes, or `undefined` when the directory is missing or
|
|
801
|
+
* empty — callers write no zip at all for asset-less documents.
|
|
802
|
+
*/
|
|
803
|
+
async function zipDir(dir, options) {
|
|
804
|
+
const entries = await readdir(dir, {
|
|
805
|
+
recursive: true,
|
|
806
|
+
withFileTypes: true
|
|
807
|
+
}).catch(() => []);
|
|
808
|
+
const files = {};
|
|
809
|
+
for (const entry of entries) {
|
|
810
|
+
if (!entry.isFile() || isSystemJunkFile(entry.name)) continue;
|
|
811
|
+
const absolute = join(entry.parentPath, entry.name);
|
|
812
|
+
const entryName = relative(dir, absolute).split("\\").join("/");
|
|
813
|
+
files[entryName] = new Uint8Array(await readFile(absolute));
|
|
814
|
+
}
|
|
815
|
+
if (Object.keys(files).length === 0) return;
|
|
816
|
+
const ordered = {};
|
|
817
|
+
for (const name of Object.keys(files).sort()) ordered[name] = files[name];
|
|
818
|
+
return zipSync(ordered, {
|
|
819
|
+
level: deflateLevel(options),
|
|
820
|
+
mtime: ZIP_EPOCH
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
//#endregion
|
|
825
|
+
//#region src/url-resolver.ts
|
|
826
|
+
/**
|
|
827
|
+
* Web-standard resolver that maps asset paths to URLs and fetches them. This is
|
|
828
|
+
* the dynamic-mode runtime resolver: the compiled wrapper bakes in the
|
|
829
|
+
* `{ relPath: url }` map and fetches only the bytes a given render references.
|
|
830
|
+
* Returns `null` for unmapped paths. Portable — uses only `fetch`.
|
|
831
|
+
*/
|
|
832
|
+
function urlResolver(urlMap) {
|
|
833
|
+
return async (relPath) => {
|
|
834
|
+
const url = urlMap[relPath];
|
|
835
|
+
if (!url) return null;
|
|
836
|
+
const res = await fetch(url);
|
|
837
|
+
if (!res.ok) throw new Error(`Failed to fetch asset "${relPath}" from ${url}: HTTP ${res.status}`);
|
|
838
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
//#endregion
|
|
843
|
+
//#region src/scan-core.ts
|
|
844
|
+
/**
|
|
845
|
+
* Build a `scanAssetRefs(html)` from a parser pair: every local asset reference
|
|
846
|
+
* in the HTML itself, as bundle-root relative paths. Pure and IO-free — it
|
|
847
|
+
* does not follow external stylesheets (that needs a resolver, in `zip()`).
|
|
848
|
+
* Remote (http/https) references are ignored.
|
|
849
|
+
*/
|
|
850
|
+
function makeScanAssetRefs(parsers) {
|
|
851
|
+
return (html) => {
|
|
852
|
+
const { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html);
|
|
853
|
+
const refs = /* @__PURE__ */ new Set();
|
|
854
|
+
const addLocal = (ref) => {
|
|
855
|
+
if (!isLocalOrigin(ref)) return;
|
|
856
|
+
const local = resolveLocalRef(ref);
|
|
857
|
+
if (local) refs.add(local);
|
|
858
|
+
};
|
|
859
|
+
for (const src of imgSrcs) addLocal(src);
|
|
860
|
+
for (const href of svgHrefs) addLocal(href);
|
|
861
|
+
for (const href of linkHrefs) addLocal(href);
|
|
862
|
+
for (const cssText of inlineCss) {
|
|
863
|
+
const { urls, imports } = parsers.parseCssRefs(cssText);
|
|
864
|
+
for (const url of urls) addLocal(url);
|
|
865
|
+
for (const target of imports) addLocal(target);
|
|
866
|
+
}
|
|
867
|
+
return [...refs];
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Build a `scanRemoteRefs(html)` from a parser pair: every remote (http/https)
|
|
872
|
+
* asset reference in the HTML itself. The mirror of `makeScanAssetRefs` for
|
|
873
|
+
* remote URLs, so the lean (scan-lite) and parser-backed (parse.ts) scanners
|
|
874
|
+
* stay in step. Pure and IO-free — it does not fetch anything.
|
|
875
|
+
*/
|
|
876
|
+
function makeScanRemoteRefs(parsers) {
|
|
877
|
+
return (html) => {
|
|
878
|
+
const { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html);
|
|
879
|
+
const refs = /* @__PURE__ */ new Set();
|
|
880
|
+
const addRemote = (ref) => {
|
|
881
|
+
if (isRemoteOrigin(ref)) refs.add(ref);
|
|
882
|
+
};
|
|
883
|
+
for (const src of imgSrcs) addRemote(src);
|
|
884
|
+
for (const href of svgHrefs) addRemote(href);
|
|
885
|
+
for (const href of linkHrefs) addRemote(href);
|
|
886
|
+
for (const cssText of inlineCss) {
|
|
887
|
+
const { urls, imports } = parsers.parseCssRefs(cssText);
|
|
888
|
+
for (const url of urls) addRemote(url);
|
|
889
|
+
for (const target of imports) addRemote(target);
|
|
890
|
+
}
|
|
891
|
+
return [...refs].sort();
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
//#endregion
|
|
896
|
+
//#region src/scan-lite.ts
|
|
897
|
+
const IMG_SRC_RE = /<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
898
|
+
const SVG_REF_TAG_RE = /<(?:image|use)\b[^>]*?\s(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
899
|
+
const LINK_TAG_RE = /<link\b[^>]*>/gi;
|
|
900
|
+
const HREF_RE = /\shref\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
|
|
901
|
+
const REL_STYLESHEET_RE = /\srel\s*=\s*(?:"stylesheet"|'stylesheet')/i;
|
|
902
|
+
const STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
|
903
|
+
const STYLE_ATTR_RE = /\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
904
|
+
const ENTITIES = {
|
|
905
|
+
"&": "&",
|
|
906
|
+
""": "\"",
|
|
907
|
+
"'": "'",
|
|
908
|
+
"<": "<",
|
|
909
|
+
">": ">"
|
|
910
|
+
};
|
|
911
|
+
function decodeEntities(value) {
|
|
912
|
+
return value.replace(/&(?:amp|quot|#39|lt|gt);/g, (entity) => ENTITIES[entity] ?? entity);
|
|
913
|
+
}
|
|
914
|
+
function matchAll(input, pattern) {
|
|
915
|
+
const out = [];
|
|
916
|
+
for (const match of input.matchAll(pattern)) {
|
|
917
|
+
const value = match[1] ?? match[2];
|
|
918
|
+
if (value != null) out.push(decodeEntities(value));
|
|
919
|
+
}
|
|
920
|
+
return out;
|
|
921
|
+
}
|
|
922
|
+
/** Regex equivalent of parse.ts's `parseHtmlRefs`. Pure and IO-free. */
|
|
923
|
+
function parseHtmlRefs$1(html) {
|
|
924
|
+
const imgSrcs = matchAll(html, IMG_SRC_RE);
|
|
925
|
+
const svgHrefs = matchAll(html, SVG_REF_TAG_RE).filter((href) => !href.startsWith("#"));
|
|
926
|
+
const linkHrefs = [];
|
|
927
|
+
for (const tagMatch of html.matchAll(LINK_TAG_RE)) {
|
|
928
|
+
const tag = tagMatch[0];
|
|
929
|
+
if (!REL_STYLESHEET_RE.test(tag)) continue;
|
|
930
|
+
const href = HREF_RE.exec(tag);
|
|
931
|
+
const value = href?.[1] ?? href?.[2];
|
|
932
|
+
if (value != null) linkHrefs.push(decodeEntities(value));
|
|
933
|
+
}
|
|
934
|
+
const styleBlocks = [...html.matchAll(STYLE_BLOCK_RE)].map((match) => match[1] ?? "");
|
|
935
|
+
const styleAttrs = matchAll(html, STYLE_ATTR_RE);
|
|
936
|
+
return {
|
|
937
|
+
imgSrcs,
|
|
938
|
+
svgHrefs,
|
|
939
|
+
linkHrefs,
|
|
940
|
+
inlineCss: [...styleBlocks, ...styleAttrs]
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Scan an HTML string for the local asset references it carries, returning each
|
|
945
|
+
* as a bundle-root relative path. Dependency-free implementation for browser,
|
|
946
|
+
* worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.
|
|
947
|
+
*/
|
|
948
|
+
const scanAssetRefs = makeScanAssetRefs({
|
|
949
|
+
parseHtmlRefs: parseHtmlRefs$1,
|
|
950
|
+
parseCssRefs
|
|
951
|
+
});
|
|
952
|
+
/**
|
|
953
|
+
* Scan an HTML string for the remote (http/https) asset references it carries.
|
|
954
|
+
* Dependency-free counterpart to scan-remote.ts's `scanRemoteRefs`, so the
|
|
955
|
+
* static-mode wrapper can list remote refs without pulling in node-html-parser.
|
|
956
|
+
*/
|
|
957
|
+
const scanRemoteRefs$1 = makeScanRemoteRefs({
|
|
958
|
+
parseHtmlRefs: parseHtmlRefs$1,
|
|
959
|
+
parseCssRefs
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
//#endregion
|
|
963
|
+
//#region src/scan-remote.ts
|
|
964
|
+
/**
|
|
965
|
+
* Every remote (http/https) asset reference in an HTML string: `<img src>`,
|
|
966
|
+
* inline-SVG `<image>`/`<use>` hrefs, `<link rel=stylesheet>` hrefs, and
|
|
967
|
+
* `url()`/`@import` targets in `<style>` blocks and style attributes.
|
|
968
|
+
*
|
|
969
|
+
* Parser-backed (node-html-parser) counterpart to scan-lite's regex
|
|
970
|
+
* `scanRemoteRefs`; both are built from `makeScanRemoteRefs`, so they stay in
|
|
971
|
+
* step. Pure and IO-free — it does not fetch anything. PDF rendering never
|
|
972
|
+
* fetches remote references, so anything this returns will be missing from the
|
|
973
|
+
* output unless it's bundled (see `mergeRemoteAssets`) or removed.
|
|
974
|
+
*/
|
|
975
|
+
const scanRemoteRefs = makeScanRemoteRefs({
|
|
976
|
+
parseHtmlRefs,
|
|
977
|
+
parseCssRefs
|
|
978
|
+
});
|
|
979
|
+
|
|
980
|
+
//#endregion
|
|
981
|
+
//#region src/index.ts
|
|
982
|
+
/**
|
|
983
|
+
* Build a ZIP of every asset `html` references.
|
|
984
|
+
*
|
|
985
|
+
* `source` is either a directory path (read from disk via {@link dirResolver})
|
|
986
|
+
* or a custom {@link AssetResolver}. For browser, worker, and edge runtimes,
|
|
987
|
+
* import from `@format.dev/zip/web` instead — that entry takes a resolver only and
|
|
988
|
+
* carries no `node:*` dependencies.
|
|
989
|
+
*
|
|
990
|
+
* @param html - The rendered Format HTML to scan for asset references.
|
|
991
|
+
* @param source - A directory path (Node) or an {@link AssetResolver} returning the bytes for each referenced path.
|
|
992
|
+
* @param options - {@link ZipOptions}: remote-asset fetching, compression level, and missing-asset handling.
|
|
993
|
+
* @returns the archive bytes, or `undefined` when `html` references no assets.
|
|
994
|
+
*/
|
|
995
|
+
function zip(html, source, options) {
|
|
996
|
+
return zip$1(html, typeof source === "string" ? dirResolver(source) : source, options);
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
//#endregion
|
|
1000
|
+
export { AssetMismatchError, FormatZipError, InvalidExtensionError, MissingAssetError, RemoteAssetFetchError, RemoteAssetsDisabledError, UnresolvableRefError, dirResolver, fetchRemote, fetchRemoteIfChanged, findBrokenRemoteAssets, isSystemJunkFile, listZipEntries, mergeRemoteAssets, readRemoteAssets, scanAssetRefs, scanRemoteRefs, urlResolver, zip, zipDir };
|
|
1001
|
+
//# sourceMappingURL=index.mjs.map
|