@all-the.rest/astro-image-cdn 0.0.0-stage → 0.1.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.
- package/LICENSE +15 -0
- package/NOTICE +7 -0
- package/README.md +129 -2
- package/package.json +42 -3
- package/src/dev-server.js +74 -0
- package/src/index.d.ts +52 -0
- package/src/index.js +153 -0
- package/src/processor.js +571 -0
- package/src/service.js +468 -0
package/src/processor.js
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { open, readdir, readFile, realpath, rename, mkdir, lstat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import sharp from "sharp";
|
|
5
|
+
|
|
6
|
+
const MANIFEST_VERSION = 2;
|
|
7
|
+
const CACHE_VERSION = 1;
|
|
8
|
+
const TRANSFORM_VERSION = 3;
|
|
9
|
+
const DEFAULT_WIDTHS = [256, 640, 828, 1080, 1200, 1920, 2048];
|
|
10
|
+
const DEFAULT_FORMATS = ["avif", "webp"];
|
|
11
|
+
const SUPPORTED_FORMATS = new Set(["avif", "webp", "jpeg", "png", "svg"]);
|
|
12
|
+
const IMAGE_EXTENSIONS = new Set([
|
|
13
|
+
".avif", ".gif", ".heic", ".heif", ".jpeg", ".jpg", ".png", ".svg", ".tif", ".tiff", ".webp",
|
|
14
|
+
]);
|
|
15
|
+
const EXCLUDED_DIRS = new Set([".astro", ".cache", ".git", "dist", "node_modules"]);
|
|
16
|
+
const AVIF_SEQUENCE_BRAND = Buffer.from("avis");
|
|
17
|
+
|
|
18
|
+
function normalizeFormat(format) {
|
|
19
|
+
return format === "jpg" ? "jpeg" : format;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function normalizeRelativePath(value) {
|
|
23
|
+
return value.split(path.sep).join("/");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function digest(value) {
|
|
27
|
+
return createHash("sha256").update(value).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isInside(parent, candidate) {
|
|
31
|
+
const relative = path.relative(parent, candidate);
|
|
32
|
+
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function pathsOverlap(first, second) {
|
|
36
|
+
return isInside(first, second) || isInside(second, first);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function canonicalizePath(value) {
|
|
40
|
+
let candidate = path.resolve(value);
|
|
41
|
+
const suffix = [];
|
|
42
|
+
while (true) {
|
|
43
|
+
try {
|
|
44
|
+
return path.join(await realpath(candidate), ...suffix.reverse());
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
|
|
47
|
+
const parent = path.dirname(candidate);
|
|
48
|
+
if (parent === candidate) throw error;
|
|
49
|
+
suffix.push(path.basename(candidate));
|
|
50
|
+
candidate = parent;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function releaseWriterLocks(locks) {
|
|
56
|
+
for (const { lockPath, token } of [...locks].reverse()) {
|
|
57
|
+
try {
|
|
58
|
+
if (await readFile(lockPath, "utf8") === token) await unlink(lockPath);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error.code !== "ENOENT") throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function acquireWriterLocks(directories) {
|
|
66
|
+
const canonicalDirectories = [...new Set(await Promise.all(directories.map((directory) => realpath(directory))))]
|
|
67
|
+
.sort((a, b) => a.localeCompare(b));
|
|
68
|
+
const locks = [];
|
|
69
|
+
try {
|
|
70
|
+
for (const directory of canonicalDirectories) {
|
|
71
|
+
const lockPath = path.join(directory, ".astro-image-cdn.lock");
|
|
72
|
+
const token = `${process.pid}\n${randomUUID()}\n`;
|
|
73
|
+
let handle;
|
|
74
|
+
try {
|
|
75
|
+
handle = await open(lockPath, "wx", 0o600);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error.code === "EEXIST") {
|
|
78
|
+
throw new Error(`Another astro-image-cdn process is already writing ${directory}; remove ${lockPath} only after confirming its process has stopped.`, { cause: error });
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
await handle.writeFile(token);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
await handle.close();
|
|
87
|
+
await unlink(lockPath).catch(() => {});
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
await handle.close();
|
|
91
|
+
locks.push({ lockPath, token });
|
|
92
|
+
}
|
|
93
|
+
} catch (error) {
|
|
94
|
+
await releaseWriterLocks(locks);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return () => releaseWriterLocks(locks);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function validatePositiveInteger(value, label) {
|
|
102
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
103
|
+
throw new TypeError(`${label} must contain positive integers; received ${value}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function resolveOptions(options) {
|
|
108
|
+
if (!options || typeof options.rootDir !== "string") {
|
|
109
|
+
throw new TypeError("processImages requires an absolute rootDir");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const rootDir = path.resolve(options.rootDir);
|
|
113
|
+
const sourceDirectories = (options.sources ?? ["src"]).map((source) => path.resolve(rootDir, source));
|
|
114
|
+
const publicDir = path.resolve(rootDir, options.publicDir ?? "public");
|
|
115
|
+
const outputDir = path.resolve(rootDir, options.outputDir ?? ".imagedist");
|
|
116
|
+
const cacheDir = path.resolve(rootDir, options.cacheDir ?? ".astro-image-cdn");
|
|
117
|
+
const widths = [...new Set(options.widths ?? DEFAULT_WIDTHS)].sort((a, b) => a - b);
|
|
118
|
+
const formats = [...new Set((options.formats ?? DEFAULT_FORMATS).map(normalizeFormat))];
|
|
119
|
+
const quality = options.quality ?? 75;
|
|
120
|
+
const concurrency = options.concurrency ?? 4;
|
|
121
|
+
const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
|
|
122
|
+
|
|
123
|
+
for (const width of widths) validatePositiveInteger(width, "widths");
|
|
124
|
+
for (const format of formats) {
|
|
125
|
+
if (!["avif", "webp", "jpeg", "png"].includes(format)) {
|
|
126
|
+
throw new TypeError(`Unsupported configured output format "${format}" for astro-image-cdn. Supported output formats are avif, webp, jpeg, and png.`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
validatePositiveInteger(quality, "quality");
|
|
130
|
+
validatePositiveInteger(concurrency, "concurrency");
|
|
131
|
+
if (typeof dangerouslyProcessSVG !== "boolean") {
|
|
132
|
+
throw new TypeError("dangerouslyProcessSVG must be a boolean");
|
|
133
|
+
}
|
|
134
|
+
if (quality > 100) throw new RangeError("quality must be between 1 and 100");
|
|
135
|
+
if (formats.length === 0) throw new TypeError("formats must contain at least one image format");
|
|
136
|
+
|
|
137
|
+
return { rootDir, sourceDirectories, publicDir, outputDir, cacheDir, widths, formats, quality, concurrency, dangerouslyProcessSVG };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function walk(directory, output, excludedPaths) {
|
|
141
|
+
let entries;
|
|
142
|
+
try {
|
|
143
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (error.code === "ENOENT") return;
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
for (const entry of entries) {
|
|
150
|
+
const fullPath = path.join(directory, entry.name);
|
|
151
|
+
if (excludedPaths.has(fullPath)) continue;
|
|
152
|
+
if (entry.isDirectory()) {
|
|
153
|
+
if (!EXCLUDED_DIRS.has(entry.name)) await walk(fullPath, output, excludedPaths);
|
|
154
|
+
} else if (entry.isFile() && IMAGE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
|
|
155
|
+
output.push(fullPath);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function readJson(filePath, fallback) {
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(await readFile(filePath, "utf8"));
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error.code === "ENOENT") return fallback;
|
|
165
|
+
throw new Error(`Could not read JSON file ${filePath}: ${error.message}`, { cause: error });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function atomicWrite(filePath, data) {
|
|
170
|
+
const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
171
|
+
try {
|
|
172
|
+
await writeFile(temporaryPath, data);
|
|
173
|
+
await rename(temporaryPath, filePath);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
await unlink(temporaryPath).catch(() => {});
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function detectLegacyPublicManifest(outputDir) {
|
|
181
|
+
const manifestPath = path.join(outputDir, "manifest.json");
|
|
182
|
+
try {
|
|
183
|
+
await lstat(manifestPath);
|
|
184
|
+
return manifestPath;
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error.code !== "ENOENT") throw error;
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function hasAvifSequenceBrand(buffer) {
|
|
192
|
+
let offset = 0;
|
|
193
|
+
while (offset + 8 <= buffer.length) {
|
|
194
|
+
const boxType = buffer.toString("ascii", offset + 4, offset + 8);
|
|
195
|
+
let boxSize = buffer.readUInt32BE(offset);
|
|
196
|
+
let headerSize = 8;
|
|
197
|
+
if (boxSize === 1) {
|
|
198
|
+
if (offset + 16 > buffer.length) return false;
|
|
199
|
+
boxSize = Number(buffer.readBigUInt64BE(offset + 8));
|
|
200
|
+
headerSize = 16;
|
|
201
|
+
} else if (boxSize === 0) {
|
|
202
|
+
boxSize = buffer.length - offset;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (boxType === "ftyp") {
|
|
206
|
+
const boxEnd = Math.min(buffer.length, offset + boxSize);
|
|
207
|
+
for (let brandOffset = offset + headerSize; brandOffset + 4 <= boxEnd; brandOffset += 4) {
|
|
208
|
+
if (buffer.subarray(brandOffset, brandOffset + 4).equals(AVIF_SEQUENCE_BRAND)) return true;
|
|
209
|
+
}
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
if (boxSize < headerSize || offset + boxSize > buffer.length) return false;
|
|
213
|
+
offset += boxSize;
|
|
214
|
+
}
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function imageMetadata(buffer, filePath) {
|
|
219
|
+
if (hasAvifSequenceBrand(buffer)) {
|
|
220
|
+
throw new Error(`Animated or multi-page image sources are not supported: ${filePath} is an AVIF image sequence.`);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let metadata;
|
|
224
|
+
try {
|
|
225
|
+
metadata = await sharp(buffer, { failOn: "none" }).metadata();
|
|
226
|
+
} catch (error) {
|
|
227
|
+
throw new Error(`Unable to read image metadata for ${filePath}: ${error.message}`, { cause: error });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (!metadata.width || !metadata.height) {
|
|
231
|
+
throw new Error(`Unable to determine image dimensions for ${filePath}`);
|
|
232
|
+
}
|
|
233
|
+
if ((metadata.pages ?? 1) > 1) {
|
|
234
|
+
throw new Error(`Animated or multi-page image sources are not supported: ${filePath} (${metadata.mediaType ?? metadata.format}, ${metadata.pages} pages).`);
|
|
235
|
+
}
|
|
236
|
+
const rotated = metadata.orientation >= 5 && metadata.orientation <= 8;
|
|
237
|
+
return {
|
|
238
|
+
width: rotated ? metadata.height : metadata.width,
|
|
239
|
+
height: rotated ? metadata.width : metadata.height,
|
|
240
|
+
format: metadata.format,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function getVariants(width, formats) {
|
|
245
|
+
return formats.map((format) => ({ width, format }));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function variantMatches(outputDir, variant) {
|
|
249
|
+
if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
|
|
250
|
+
const filePath = path.resolve(outputDir, variant.file);
|
|
251
|
+
if (!isInside(outputDir, filePath) || filePath === outputDir) return false;
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
const relative = path.relative(outputDir, filePath);
|
|
255
|
+
const segments = relative.split(path.sep);
|
|
256
|
+
let directory = outputDir;
|
|
257
|
+
for (const segment of segments.slice(0, -1)) {
|
|
258
|
+
directory = path.join(directory, segment);
|
|
259
|
+
const directoryInfo = await lstat(directory);
|
|
260
|
+
if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return false;
|
|
261
|
+
}
|
|
262
|
+
const fileInfo = await lstat(filePath);
|
|
263
|
+
if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return false;
|
|
264
|
+
return digest(await readFile(filePath)) === variant.digest;
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function outputExists(outputDir, variants) {
|
|
272
|
+
const matches = await Promise.all(variants.map((variant) => variantMatches(outputDir, variant)));
|
|
273
|
+
return matches.every(Boolean);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function variantKey(variant) {
|
|
277
|
+
return `${variant.width}\0${variant.format}`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function hasCompleteVariantSet(actual, expected) {
|
|
281
|
+
if (!Array.isArray(actual) || actual.length !== expected.length) return false;
|
|
282
|
+
const byKey = new Map();
|
|
283
|
+
for (const variant of actual) {
|
|
284
|
+
if (!variant || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
|
|
285
|
+
const key = variantKey(variant);
|
|
286
|
+
if (byKey.has(key)) return false;
|
|
287
|
+
byKey.set(key, variant);
|
|
288
|
+
}
|
|
289
|
+
return expected.every((variant) => {
|
|
290
|
+
const actualVariant = byKey.get(variantKey(variant));
|
|
291
|
+
return actualVariant?.file === variant.file && actualVariant.height === variant.height;
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function carryForwardVariantDigests(expected, previous) {
|
|
296
|
+
const previousByKey = new Map();
|
|
297
|
+
if (Array.isArray(previous)) {
|
|
298
|
+
for (const variant of previous) {
|
|
299
|
+
if (variant && /^[a-f0-9]{64}$/.test(variant.digest ?? "")) {
|
|
300
|
+
previousByKey.set(variantKey(variant), variant);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return expected.map((variant) => {
|
|
306
|
+
const previousVariant = previousByKey.get(variantKey(variant));
|
|
307
|
+
if (previousVariant?.file === variant.file && previousVariant.height === variant.height) {
|
|
308
|
+
return { ...variant, digest: previousVariant.digest };
|
|
309
|
+
}
|
|
310
|
+
return variant;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function ensureVariantDirectory(outputDir, file) {
|
|
315
|
+
const filePath = path.resolve(outputDir, file);
|
|
316
|
+
if (!isInside(outputDir, filePath) || filePath === outputDir) {
|
|
317
|
+
throw new Error(`Refusing to write image variant outside outputDir: ${file}`);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const segments = path.relative(outputDir, filePath).split(path.sep);
|
|
321
|
+
let directory = outputDir;
|
|
322
|
+
for (const segment of segments.slice(0, -1)) {
|
|
323
|
+
directory = path.join(directory, segment);
|
|
324
|
+
let directoryInfo;
|
|
325
|
+
try {
|
|
326
|
+
directoryInfo = await lstat(directory);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (error.code !== "ENOENT") throw error;
|
|
329
|
+
await mkdir(directory).catch((mkdirError) => {
|
|
330
|
+
if (mkdirError.code !== "EEXIST") throw mkdirError;
|
|
331
|
+
});
|
|
332
|
+
directoryInfo = await lstat(directory);
|
|
333
|
+
}
|
|
334
|
+
if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) {
|
|
335
|
+
throw new Error(`Refusing to write image variant through a symlink or non-directory: ${directory}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return filePath;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function writeVariant(buffer, filePath, width, format, quality) {
|
|
342
|
+
if (format === "svg") {
|
|
343
|
+
await atomicWrite(filePath, buffer);
|
|
344
|
+
return digest(buffer);
|
|
345
|
+
}
|
|
346
|
+
const image = sharp(buffer, { failOn: "none" }).rotate().resize({ width, withoutEnlargement: true });
|
|
347
|
+
if (format === "avif") image.avif({ quality });
|
|
348
|
+
else if (format === "webp") image.webp({ quality });
|
|
349
|
+
else if (format === "jpeg") image.jpeg({ quality });
|
|
350
|
+
else image.png({ quality });
|
|
351
|
+
|
|
352
|
+
const result = await image.toBuffer();
|
|
353
|
+
await atomicWrite(filePath, result);
|
|
354
|
+
return digest(result);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function mapConcurrent(items, concurrency, callback) {
|
|
358
|
+
let nextIndex = 0;
|
|
359
|
+
const results = new Array(items.length);
|
|
360
|
+
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
|
361
|
+
while (nextIndex < items.length) {
|
|
362
|
+
const index = nextIndex++;
|
|
363
|
+
results[index] = await callback(items[index], index);
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
const settled = await Promise.allSettled(workers);
|
|
367
|
+
const failure = settled.find((result) => result.status === "rejected");
|
|
368
|
+
if (failure) throw failure.reason;
|
|
369
|
+
return results;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
373
|
+
const options = resolveOptions(rawOptions);
|
|
374
|
+
const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG } = options;
|
|
375
|
+
let { outputDir, cacheDir } = options;
|
|
376
|
+
const reportedManifestPath = path.join(cacheDir, "manifest.json");
|
|
377
|
+
const canonicalRoot = await canonicalizePath(rootDir);
|
|
378
|
+
const canonicalSources = [];
|
|
379
|
+
for (const sourceDirectory of sourceDirectories) {
|
|
380
|
+
const relative = path.relative(rootDir, sourceDirectory);
|
|
381
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
382
|
+
throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
|
|
383
|
+
}
|
|
384
|
+
const canonicalSource = await canonicalizePath(sourceDirectory);
|
|
385
|
+
if (!isInside(canonicalRoot, canonicalSource)) {
|
|
386
|
+
throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
|
|
387
|
+
}
|
|
388
|
+
canonicalSources.push(canonicalSource);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const canonicalOutputDir = await canonicalizePath(outputDir);
|
|
392
|
+
const canonicalCacheDir = await canonicalizePath(cacheDir);
|
|
393
|
+
const canonicalPublicDir = await canonicalizePath(publicDir);
|
|
394
|
+
if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
|
|
395
|
+
throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
|
|
396
|
+
}
|
|
397
|
+
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
398
|
+
if (isInside(canonicalPublicDir, directory)) {
|
|
399
|
+
throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
for (const canonicalSource of canonicalSources) {
|
|
403
|
+
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
404
|
+
if (pathsOverlap(canonicalSource, directory)) {
|
|
405
|
+
throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
await mkdir(outputDir, { recursive: true });
|
|
411
|
+
await mkdir(cacheDir, { recursive: true });
|
|
412
|
+
outputDir = await realpath(outputDir);
|
|
413
|
+
cacheDir = await realpath(cacheDir);
|
|
414
|
+
const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
|
|
415
|
+
try {
|
|
416
|
+
const legacyPublicManifestPath = await detectLegacyPublicManifest(outputDir);
|
|
417
|
+
const excludedPaths = new Set([outputDir, cacheDir]);
|
|
418
|
+
const files = [];
|
|
419
|
+
if (requestedFiles === undefined) {
|
|
420
|
+
for (const sourceDirectory of sourceDirectories) {
|
|
421
|
+
await walk(sourceDirectory, files, excludedPaths);
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
const uniqueFiles = new Set();
|
|
425
|
+
for (const requestedFile of requestedFiles) {
|
|
426
|
+
if (typeof requestedFile !== "string") {
|
|
427
|
+
throw new TypeError("Requested image paths must be strings");
|
|
428
|
+
}
|
|
429
|
+
const sourcePath = path.resolve(rootDir, requestedFile);
|
|
430
|
+
const relative = path.relative(rootDir, sourcePath);
|
|
431
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
432
|
+
throw new Error(`Requested image must remain inside rootDir: ${sourcePath}`);
|
|
433
|
+
}
|
|
434
|
+
if (!IMAGE_EXTENSIONS.has(path.extname(sourcePath).toLowerCase())) {
|
|
435
|
+
throw new Error(`Requested file is not a supported image: ${sourcePath}`);
|
|
436
|
+
}
|
|
437
|
+
const fileInfo = await lstat(sourcePath);
|
|
438
|
+
if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) {
|
|
439
|
+
throw new Error(`Requested image must be a regular file, not a symlink: ${sourcePath}`);
|
|
440
|
+
}
|
|
441
|
+
const canonicalFile = await realpath(sourcePath);
|
|
442
|
+
if (!isInside(canonicalRoot, canonicalFile) || !canonicalSources.some((source) => isInside(source, canonicalFile))) {
|
|
443
|
+
throw new Error(`Requested image must be inside one of the configured image source directories: ${sourcePath}`);
|
|
444
|
+
}
|
|
445
|
+
uniqueFiles.add(sourcePath);
|
|
446
|
+
}
|
|
447
|
+
files.push(...uniqueFiles);
|
|
448
|
+
}
|
|
449
|
+
files.sort((a, b) => a.localeCompare(b));
|
|
450
|
+
|
|
451
|
+
const manifestPath = path.join(cacheDir, "manifest.json");
|
|
452
|
+
const cachePath = path.join(cacheDir, "cache.json");
|
|
453
|
+
const oldManifest = await readJson(manifestPath, { version: MANIFEST_VERSION, images: {} });
|
|
454
|
+
const oldCache = await readJson(cachePath, { version: CACHE_VERSION, sources: {} });
|
|
455
|
+
const incrementalRequest = requestedFiles !== undefined;
|
|
456
|
+
const manifest = {
|
|
457
|
+
version: MANIFEST_VERSION,
|
|
458
|
+
images: incrementalRequest && oldManifest.images && typeof oldManifest.images === "object"
|
|
459
|
+
? { ...oldManifest.images }
|
|
460
|
+
: {},
|
|
461
|
+
};
|
|
462
|
+
const cache = {
|
|
463
|
+
version: CACHE_VERSION,
|
|
464
|
+
sources: incrementalRequest && oldCache.sources && typeof oldCache.sources === "object"
|
|
465
|
+
? { ...oldCache.sources }
|
|
466
|
+
: {},
|
|
467
|
+
};
|
|
468
|
+
let processed = 0;
|
|
469
|
+
let skipped = 0;
|
|
470
|
+
|
|
471
|
+
const pipeline = JSON.stringify({
|
|
472
|
+
widths,
|
|
473
|
+
formats,
|
|
474
|
+
quality,
|
|
475
|
+
transformVersion: TRANSFORM_VERSION,
|
|
476
|
+
sharpVersion: sharp.versions.sharp,
|
|
477
|
+
libvipsVersion: sharp.versions.vips,
|
|
478
|
+
dangerouslyProcessSVG,
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
|
|
482
|
+
const relativePath = normalizeRelativePath(path.relative(rootDir, sourcePath));
|
|
483
|
+
const sourceBuffer = await readFile(sourcePath);
|
|
484
|
+
const sourceHash = digest(sourceBuffer);
|
|
485
|
+
const fingerprint = digest(`${sourceHash}\0${pipeline}`);
|
|
486
|
+
const cacheEntry = oldCache.sources?.[relativePath];
|
|
487
|
+
const previousEntry = oldManifest.images?.[relativePath];
|
|
488
|
+
const dimensions = await imageMetadata(sourceBuffer, sourcePath);
|
|
489
|
+
const sourceFormat = normalizeFormat(dimensions.format);
|
|
490
|
+
const targetWidths = [...new Set([...widths.filter((width) => width < dimensions.width), dimensions.width])].sort((a, b) => a - b);
|
|
491
|
+
const generatedFormats = sourceFormat === "svg" && !dangerouslyProcessSVG
|
|
492
|
+
? ["svg"]
|
|
493
|
+
: SUPPORTED_FORMATS.has(sourceFormat) ? [...new Set([...formats, sourceFormat])] : formats;
|
|
494
|
+
const expectedVariants = targetWidths.flatMap((width) => getVariants(width, generatedFormats)
|
|
495
|
+
.filter((variant) => variant.format !== "svg" || width === dimensions.width)
|
|
496
|
+
.map((variant) => {
|
|
497
|
+
const file = `${fingerprint.slice(0, 2)}/${fingerprint}_${width}.${variant.format}`;
|
|
498
|
+
return { ...variant, height: Math.max(1, Math.round(width * dimensions.height / dimensions.width)), file };
|
|
499
|
+
}));
|
|
500
|
+
|
|
501
|
+
const isWarm = cacheEntry?.fingerprint === fingerprint
|
|
502
|
+
&& previousEntry?.fingerprint === fingerprint
|
|
503
|
+
&& previousEntry.sourceHash === sourceHash
|
|
504
|
+
&& previousEntry.width === dimensions.width
|
|
505
|
+
&& previousEntry.height === dimensions.height
|
|
506
|
+
&& previousEntry.sourceFormat === dimensions.format
|
|
507
|
+
&& hasCompleteVariantSet(previousEntry.variants, expectedVariants)
|
|
508
|
+
&& await outputExists(outputDir, previousEntry.variants);
|
|
509
|
+
let variants;
|
|
510
|
+
if (isWarm) {
|
|
511
|
+
variants = previousEntry.variants;
|
|
512
|
+
skipped++;
|
|
513
|
+
} else {
|
|
514
|
+
variants = carryForwardVariantDigests(expectedVariants, previousEntry?.variants);
|
|
515
|
+
const missingVariants = [];
|
|
516
|
+
for (const variant of variants) {
|
|
517
|
+
if (!await variantMatches(outputDir, variant)) missingVariants.push(variant);
|
|
518
|
+
}
|
|
519
|
+
await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
|
|
520
|
+
const targetPath = await ensureVariantDirectory(outputDir, variant.file);
|
|
521
|
+
variant.digest = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality);
|
|
522
|
+
});
|
|
523
|
+
processed++;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
return {
|
|
527
|
+
relativePath,
|
|
528
|
+
entry: {
|
|
529
|
+
source: relativePath,
|
|
530
|
+
fingerprint,
|
|
531
|
+
sourceHash,
|
|
532
|
+
sourceFormat: dimensions.format,
|
|
533
|
+
width: dimensions.width,
|
|
534
|
+
height: dimensions.height,
|
|
535
|
+
variants,
|
|
536
|
+
},
|
|
537
|
+
};
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
for (const { relativePath, entry } of results) {
|
|
541
|
+
manifest.images[relativePath] = entry;
|
|
542
|
+
cache.sources[relativePath] = { fingerprint: entry.fingerprint };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
|
|
546
|
+
const oldManifestJson = JSON.stringify(oldManifest, null, 2);
|
|
547
|
+
if (manifestJson !== `${oldManifestJson}\n`) await atomicWrite(manifestPath, manifestJson);
|
|
548
|
+
const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
|
|
549
|
+
if (cacheJson !== `${JSON.stringify(oldCache, null, 2)}\n`) await atomicWrite(cachePath, cacheJson);
|
|
550
|
+
|
|
551
|
+
return { processed, skipped, imageCount: files.length, manifestPath: reportedManifestPath, legacyPublicManifestPath };
|
|
552
|
+
} finally {
|
|
553
|
+
await releaseLocks();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Generate variants for exactly the requested source files, preserving unrelated manifest/cache entries. */
|
|
558
|
+
export async function processRequestedImages(rawOptions, requestedFiles) {
|
|
559
|
+
if (!Array.isArray(requestedFiles)) {
|
|
560
|
+
throw new TypeError("processRequestedImages requires an array of requested image paths");
|
|
561
|
+
}
|
|
562
|
+
return processImagesFromFiles(rawOptions, requestedFiles);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Generate content-addressed variants for every image under the configured source directories. */
|
|
566
|
+
export async function processImages(rawOptions) {
|
|
567
|
+
return processImagesFromFiles(rawOptions, undefined);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
export const DEFAULT_IMAGE_WIDTHS = DEFAULT_WIDTHS;
|
|
571
|
+
export const DEFAULT_IMAGE_FORMATS = DEFAULT_FORMATS;
|