@all-the.rest/astro-image-cdn 0.2.3 → 0.4.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 CHANGED
@@ -68,12 +68,17 @@ With this option, `astro dev` installs the image service and local asset route,
68
68
  | `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths. Values above the source width are omitted. |
69
69
  | `formats` | `["avif", "webp"]` | Output encodings generated for every selected width. Supported: `avif`, `webp`, `jpeg`, `png`. |
70
70
  | `quality` | `75` | Sharp encoder quality from 1 to 100. |
71
+ | `webpEffort` | `4` | Build-wide Sharp WebP encoder effort, an integer from 0 (fastest) to 6 (slowest). |
72
+ | `avifEffort` | `4` | Build-wide Sharp AVIF encoder effort, an integer from 0 (fastest) to 9 (slowest). |
71
73
  | `includeSourceFormat` | `true` | Also generate each supported source-native format. Set `false` for only the formats listed in `formats`. |
72
74
  | `includeNativeWidth` | `true` | Also generate the source's native width when it is not already in `widths`. |
73
75
  | `autoRotate` | `true` | Apply EXIF orientation before resizing. Set `false` to preserve the source's stored pixel orientation and dimensions. |
76
+ | `verification` | `"stat"` | Warm-cache verification strategy. `"stat"` trusts recorded size and mtime and avoids reading unchanged sources and outputs. `"digest"` re-hashes every source and output on every run. |
74
77
  | `concurrency` | `4` | Maximum number of source images processed at once. |
75
78
  | `devOnly` | `false` | Install the integration only for `astro dev`; other Astro commands retain their configured image service. |
76
79
 
80
+ `webpEffort` and `avifEffort` are build-wide encoder settings available to both `astroImageCdn()` and the standalone `processImages()` API. They apply to every generated output of that format and are not per-image Astro request settings. The defaults match Sharp's defaults (4); omitting either option therefore preserves the existing encoder behavior. Invalid or out-of-range values are rejected before image processing or persistent output/cache changes.
81
+
77
82
  Configured formats are generated alongside the source's native raster format when `includeSourceFormat` is enabled (the default). With it disabled, only `formats` are generated. Astro 7.4's default output for raster images is WebP, independent of the order in `formats`; include `webp` or request a configured format explicitly. If the default or an explicit format is unavailable, the service reports which format needs to be added. `widths` are emitted only when they are no wider than the source. The native width is additionally emitted only when `includeNativeWidth` is enabled; if it is already listed in `widths`, it is naturally generated once. For a requested width between generated sizes, the service selects the next available variant, capped at the source's native width.
78
83
 
79
84
  Animated or multi-page sources are rejected rather than silently flattened to a still frame, including GIF, WebP, AVIF sequences, and multi-page TIFF. Convert them to a static image or exclude them from the configured source directories.
@@ -86,11 +91,12 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
86
91
 
87
92
  ## Persistence and cache behavior
88
93
 
89
- - Source bytes, encoder settings, the transform implementation version, and the Sharp/libvips versions are fingerprinted with SHA-256.
90
- - Variant filenames include that fingerprint, width, and format. Each manifest variant stores a SHA-256 digest; warm-cache reuse verifies the digest and rejects symlinks instead of trusting file existence alone.
94
+ - `sourceHash` is the full lowercase SHA-256 of the original source bytes only; it does not change when transform settings change. A separate transform fingerprint is the SHA-256 of that source identity plus the effective transform policy (widths, formats, quality, encoder effort, orientation/SVG settings), the transform implementation version, and the Sharp/libvips versions.
95
+ - Variant filenames include that fingerprint, width, and format. Each manifest variant stores a SHA-256 digest plus the file's size and nanosecond mtime when it was written; the source cache records the source's size and mtime too. Warm-cache reuse rejects symlinks and non-files.
96
+ - With the default `verification: "stat"`, a warm run compares those recorded size/mtime values. Unchanged sources and variants are not opened or hashed at all; only changed or unrecorded files fall back to SHA-256 and Sharp metadata validation. With `verification: "digest"`, every source and variant is re-read and re-hashed on every run. Content changes that preserve both size and mtime are only detected in `"digest"` mode.
91
97
  - Each manifest is checked against the complete set of variants expected for its source and current options, so empty or partial entries trigger repair rather than a false cache hit.
92
98
  - The private cache and manifest are updated atomically and only when their contents change. Concurrent native image requests are deduplicated and batched per event-loop turn; batches are serialized through one writer queue, while the configured concurrency controls processing within each batch. A pre-existing `manifest.json` in `outputDir` is detected, reported in the processing result, and warned about when an Astro-requested image or standalone bulk run processes images; it is never modified. Verify its ownership, then manually move it outside public output or remove it before publishing. A filesystem lock allows only one process to write a given output/cache pair; overlapping processes fail with the lock path instead of racing. If a process is interrupted, verify it has stopped and remove any leftover `.astro-image-cdn.lock` file before retrying; the next run can rebuild missing variants.
93
- - Warm runs re-hash source bytes but skip Sharp transformations when the fingerprint and every expected output still match.
99
+ - Warm runs skip Sharp transformations when the fingerprint and every expected output still match. They also skip source reads when the recorded source stat still matches.
94
100
  - Old content-addressed files are intentionally retained. Request-driven Astro processing preserves unrelated manifest entries; an explicit standalone `processImages()` run reconciles the manifest with the files found under its source directories. Neither mode deletes historical output files.
95
101
  - Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
96
102
 
@@ -122,7 +128,7 @@ await adoptImageVariants({
122
128
  });
123
129
  ```
124
130
 
125
- The helper verifies the current source hash and each required output's actual format and dimensions before writing. It requires the complete variant set implied by the options; extras (such as legacy native-width files) are ignored. Outputs are atomically written under `outputDir`, and the private manifest/cache are updated only after validation. Repeated calls reuse matching targets; failures leave the prior manifest and existing outputs untouched, and old source variants are never removed. Supply the source hash recorded when the existing outputs were produced so a changed source cannot accidentally adopt stale files.
131
+ The helper verifies the current source hash and each required output's actual format and dimensions before writing. It requires the complete variant set implied by the options; extras (such as legacy native-width files) are ignored. Outputs are atomically written under `outputDir`, and the private manifest/cache are updated only after validation. Under the default `verification: "stat"`, a repeated call whose targets and manifest already match returns without reading the supplied legacy files or copying bytes; `verification: "digest"` re-validates every supplied variant. Failures leave the prior manifest and existing outputs untouched, and old source variants are never removed. Supply the source hash recorded when the existing outputs were produced so a changed source cannot accidentally adopt stale files.
126
132
 
127
133
  ## API
128
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@all-the.rest/astro-image-cdn",
3
- "version": "0.2.3",
3
+ "version": "0.4.0",
4
4
  "description": "Persistent, incremental image variants for Astro's native image components",
5
5
  "type": "module",
6
6
  "license": "ISC",
package/src/index.d.ts CHANGED
@@ -13,6 +13,16 @@ interface AstroImageCdnBaseOptions {
13
13
  formats?: Array<"avif" | "webp" | "jpeg" | "png">;
14
14
  /** Encoder quality from 1 to 100. Defaults to 75. */
15
15
  quality?: number;
16
+ /** WebP encoder effort, integer from 0 (fastest) to 6 (slowest). Defaults to Sharp's default, 4. */
17
+ webpEffort?: number;
18
+ /** AVIF encoder effort, integer from 0 (fastest) to 9 (slowest). Defaults to Sharp's default, 4. */
19
+ avifEffort?: number;
20
+ /**
21
+ * Warm-cache verification strategy. "stat" (default) trusts recorded file size and mtime,
22
+ * avoiding source/output reads when nothing changed. "digest" re-hashes every source and
23
+ * output on every run.
24
+ */
25
+ verification?: "stat" | "digest";
16
26
  /** Also generate a supported source-native format. Defaults to true. */
17
27
  includeSourceFormat?: boolean;
18
28
  /** Also generate the source's native width when it is not configured. Defaults to true. */
package/src/index.js CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { realpathSync } from "node:fs";
4
4
  import path from "node:path";
5
- import { DEFAULT_IMAGE_FORMATS, DEFAULT_IMAGE_WIDTHS } from "./processor.js";
5
+ import { DEFAULT_IMAGE_FORMATS, DEFAULT_IMAGE_WIDTHS, resolveEncoderEfforts, resolveVerification } from "./processor.js";
6
6
  import { installDevAssetMiddleware } from "./dev-server.js";
7
7
 
8
8
  const serviceEntrypoint = fileURLToPath(new URL("./service.js", import.meta.url));
@@ -82,6 +82,8 @@ export default function astroImageCdn(options) {
82
82
  throw new TypeError("astroImageCdn requires a baseUrl unless devOnly is true");
83
83
  }
84
84
  const baseUrl = typeof options.baseUrl === "string" ? normalizeBaseUrl(options.baseUrl) : "";
85
+ const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
86
+ const verification = resolveVerification(options);
85
87
  let projectRoot;
86
88
  let outputDir;
87
89
  let cacheDir;
@@ -111,6 +113,9 @@ export default function astroImageCdn(options) {
111
113
  widths: options.widths ?? DEFAULT_IMAGE_WIDTHS,
112
114
  formats: options.formats ?? DEFAULT_IMAGE_FORMATS,
113
115
  quality: options.quality ?? 75,
116
+ webpEffort,
117
+ avifEffort,
118
+ verification,
114
119
  includeSourceFormat: options.includeSourceFormat ?? true,
115
120
  includeNativeWidth: options.includeNativeWidth ?? true,
116
121
  autoRotate: options.autoRotate ?? true,
package/src/processor.js CHANGED
@@ -8,6 +8,9 @@ const CACHE_VERSION = 1;
8
8
  const TRANSFORM_VERSION = 3;
9
9
  const DEFAULT_WIDTHS = [256, 640, 828, 1080, 1200, 1920, 2048];
10
10
  const DEFAULT_FORMATS = ["avif", "webp"];
11
+ const DEFAULT_WEBP_EFFORT = 4;
12
+ const DEFAULT_AVIF_EFFORT = 4;
13
+ const DEFAULT_VERIFICATION = "stat";
11
14
  const SUPPORTED_FORMATS = new Set(["avif", "webp", "jpeg", "png", "svg"]);
12
15
  const IMAGE_EXTENSIONS = new Set([
13
16
  ".avif", ".gif", ".heic", ".heif", ".jpeg", ".jpg", ".png", ".svg", ".tif", ".tiff", ".webp",
@@ -110,6 +113,31 @@ function validatePositiveInteger(value, label) {
110
113
  }
111
114
  }
112
115
 
116
+ function validateEffort(value, label, maximum) {
117
+ if (!Number.isSafeInteger(value)) {
118
+ throw new TypeError(`${label} must be an integer between 0 and ${maximum}; received ${value}`);
119
+ }
120
+ if (value < 0 || value > maximum) {
121
+ throw new RangeError(`${label} must be between 0 and ${maximum}; received ${value}`);
122
+ }
123
+ }
124
+
125
+ export function resolveEncoderEfforts(options) {
126
+ const webpEffort = options.webpEffort === undefined ? DEFAULT_WEBP_EFFORT : options.webpEffort;
127
+ const avifEffort = options.avifEffort === undefined ? DEFAULT_AVIF_EFFORT : options.avifEffort;
128
+ validateEffort(webpEffort, "webpEffort", 6);
129
+ validateEffort(avifEffort, "avifEffort", 9);
130
+ return { webpEffort, avifEffort };
131
+ }
132
+
133
+ export function resolveVerification(options) {
134
+ const verification = options.verification ?? DEFAULT_VERIFICATION;
135
+ if (verification !== "stat" && verification !== "digest") {
136
+ throw new TypeError(`verification must be "stat" or "digest"; received ${JSON.stringify(verification)}`);
137
+ }
138
+ return verification;
139
+ }
140
+
113
141
  function heightMatchesExpected(expected, actual) {
114
142
  return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
115
143
  }
@@ -127,6 +155,8 @@ function resolveOptions(options) {
127
155
  const widths = [...new Set(options.widths ?? DEFAULT_WIDTHS)].sort((a, b) => a - b);
128
156
  const formats = [...new Set((options.formats ?? DEFAULT_FORMATS).map(normalizeFormat))];
129
157
  const quality = options.quality ?? 75;
158
+ const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
159
+ const verification = resolveVerification(options);
130
160
  const concurrency = options.concurrency ?? 4;
131
161
  const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
132
162
  const includeSourceFormat = options.includeSourceFormat ?? true;
@@ -159,6 +189,9 @@ function resolveOptions(options) {
159
189
  widths,
160
190
  formats,
161
191
  quality,
192
+ webpEffort,
193
+ avifEffort,
194
+ verification,
162
195
  concurrency,
163
196
  dangerouslyProcessSVG,
164
197
  includeSourceFormat,
@@ -280,6 +313,8 @@ function pipelineSettings(options) {
280
313
  widths: options.widths,
281
314
  formats: options.formats,
282
315
  quality: options.quality,
316
+ webpEffort: options.webpEffort,
317
+ avifEffort: options.avifEffort,
283
318
  transformVersion: TRANSFORM_VERSION,
284
319
  sharpVersion: sharp.versions.sharp,
285
320
  libvipsVersion: sharp.versions.vips,
@@ -311,9 +346,37 @@ function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
311
346
  })));
312
347
  }
313
348
 
314
- async function readMatchingVariant(outputDir, variant) {
315
- if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return undefined;
316
- const filePath = path.resolve(outputDir, variant.file);
349
+ function hasValidVariantIdentity(variant) {
350
+ return Boolean(variant)
351
+ && typeof variant.file === "string"
352
+ && /^[a-f0-9]{64}$/.test(variant.digest ?? "");
353
+ }
354
+
355
+ async function fileStat(filePath) {
356
+ const info = await lstat(filePath, { bigint: true });
357
+ if (!info.isFile() || info.isSymbolicLink()) return undefined;
358
+ return { size: Number(info.size), mtimeNs: info.mtimeNs.toString() };
359
+ }
360
+
361
+ async function sourceFileStat(filePath) {
362
+ try {
363
+ return await fileStat(filePath);
364
+ } catch (error) {
365
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ function matchesRecordedStat(variant, info) {
371
+ return Number.isSafeInteger(variant?.size)
372
+ && variant.size === info.size
373
+ && typeof variant?.mtimeNs === "string"
374
+ && variant.mtimeNs === info.mtimeNs;
375
+ }
376
+
377
+ async function inspectVariantFile(outputDir, file) {
378
+ if (typeof file !== "string") return undefined;
379
+ const filePath = path.resolve(outputDir, file);
317
380
  if (!isInside(outputDir, filePath) || filePath === outputDir) return undefined;
318
381
 
319
382
  try {
@@ -325,33 +388,49 @@ async function readMatchingVariant(outputDir, variant) {
325
388
  const directoryInfo = await lstat(directory);
326
389
  if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return undefined;
327
390
  }
328
- const fileInfo = await lstat(filePath);
329
- if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return undefined;
330
- const buffer = await readFile(filePath);
331
- return digest(buffer) === variant.digest ? buffer : undefined;
391
+ const info = await fileStat(filePath);
392
+ return info ? { filePath, ...info } : undefined;
332
393
  } catch (error) {
333
394
  if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
334
395
  throw error;
335
396
  }
336
397
  }
337
398
 
399
+ async function readMatchingVariant(outputDir, variant) {
400
+ if (!hasValidVariantIdentity(variant)) return undefined;
401
+ const inspected = await inspectVariantFile(outputDir, variant.file);
402
+ if (!inspected) return undefined;
403
+ const buffer = await readFile(inspected.filePath);
404
+ return digest(buffer) === variant.digest ? { buffer, ...inspected } : undefined;
405
+ }
406
+
338
407
  async function variantMatches(outputDir, variant) {
339
408
  return (await readMatchingVariant(outputDir, variant)) !== undefined;
340
409
  }
341
410
 
342
- async function verifiedVariantHeight(outputDir, variant, expectedVariant) {
343
- const buffer = await readMatchingVariant(outputDir, variant);
344
- if (!buffer) return undefined;
411
+ async function verifyVariant(outputDir, variant, expectedVariant, verification) {
412
+ if (!hasValidVariantIdentity(variant) || !expectedVariant) return undefined;
413
+ if (verification === "stat") {
414
+ const inspected = await inspectVariantFile(outputDir, variant.file);
415
+ if (inspected
416
+ && matchesRecordedStat(variant, inspected)
417
+ && heightMatchesExpected(expectedVariant.height, variant.height)) {
418
+ return { ...variant, size: inspected.size, mtimeNs: inspected.mtimeNs };
419
+ }
420
+ }
421
+
422
+ const matched = await readMatchingVariant(outputDir, variant);
423
+ if (!matched) return undefined;
345
424
  let metadata;
346
425
  try {
347
- metadata = await sharp(buffer, { failOn: "none" }).metadata();
426
+ metadata = await sharp(matched.buffer, { failOn: "none" }).metadata();
348
427
  } catch {
349
428
  return undefined;
350
429
  }
351
430
  if (normalizeVariantFormat(metadata) !== expectedVariant.format
352
431
  || metadata.width !== expectedVariant.width
353
432
  || !heightMatchesExpected(expectedVariant.height, metadata.height)) return undefined;
354
- return metadata.height;
433
+ return { ...variant, height: metadata.height, size: matched.size, mtimeNs: matched.mtimeNs };
355
434
  }
356
435
 
357
436
  function variantKey(variant) {
@@ -362,7 +441,7 @@ function hasCompleteVariantSet(actual, expected) {
362
441
  if (!Array.isArray(actual) || actual.length !== expected.length) return false;
363
442
  const byKey = new Map();
364
443
  for (const variant of actual) {
365
- if (!variant || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
444
+ if (!hasValidVariantIdentity(variant)) return false;
366
445
  const key = variantKey(variant);
367
446
  if (byKey.has(key)) return false;
368
447
  byKey.set(key, variant);
@@ -373,15 +452,15 @@ function hasCompleteVariantSet(actual, expected) {
373
452
  });
374
453
  }
375
454
 
376
- async function verifiedOutputVariants(outputDir, actual, expected) {
455
+ async function verifiedOutputVariants(outputDir, actual, expected, verification) {
377
456
  if (!hasCompleteVariantSet(actual, expected)) return undefined;
378
457
  const actualByKey = new Map(actual.map((variant) => [variantKey(variant), variant]));
379
458
  const verified = [];
380
459
  for (const expectedVariant of expected) {
381
460
  const variant = actualByKey.get(variantKey(expectedVariant));
382
- const height = await verifiedVariantHeight(outputDir, variant, expectedVariant);
383
- if (height === undefined) return undefined;
384
- verified.push({ ...variant, height });
461
+ const verifiedVariant = await verifyVariant(outputDir, variant, expectedVariant, verification);
462
+ if (!verifiedVariant) return undefined;
463
+ verified.push(verifiedVariant);
385
464
  }
386
465
  return verified;
387
466
  }
@@ -390,7 +469,7 @@ function carryForwardVariantDigests(expected, previous) {
390
469
  const previousByKey = new Map();
391
470
  if (Array.isArray(previous)) {
392
471
  for (const variant of previous) {
393
- if (variant && /^[a-f0-9]{64}$/.test(variant.digest ?? "")) {
472
+ if (hasValidVariantIdentity(variant)) {
394
473
  previousByKey.set(variantKey(variant), variant);
395
474
  }
396
475
  }
@@ -399,7 +478,14 @@ function carryForwardVariantDigests(expected, previous) {
399
478
  return expected.map((variant) => {
400
479
  const previousVariant = previousByKey.get(variantKey(variant));
401
480
  if (previousVariant?.file === variant.file && heightMatchesExpected(variant.height, previousVariant.height)) {
402
- return { ...variant, height: previousVariant.height, digest: previousVariant.digest };
481
+ return {
482
+ ...variant,
483
+ height: previousVariant.height,
484
+ digest: previousVariant.digest,
485
+ ...(Number.isSafeInteger(previousVariant.size) && typeof previousVariant.mtimeNs === "string"
486
+ ? { size: previousVariant.size, mtimeNs: previousVariant.mtimeNs }
487
+ : {}),
488
+ };
403
489
  }
404
490
  return variant;
405
491
  });
@@ -432,22 +518,36 @@ async function ensureVariantDirectory(outputDir, file) {
432
518
  return filePath;
433
519
  }
434
520
 
435
- async function writeVariant(buffer, filePath, width, format, quality, autoRotate, expectedHeight) {
436
- if (format === "svg") {
521
+ async function writeVariant(buffer, filePath, variant, options, expectedHeight) {
522
+ if (variant.format === "svg") {
437
523
  await atomicWrite(filePath, buffer);
438
- return { digest: digest(buffer), width, height: expectedHeight };
524
+ const fileInfo = await lstat(filePath, { bigint: true });
525
+ return {
526
+ digest: digest(buffer),
527
+ width: variant.width,
528
+ height: expectedHeight,
529
+ size: Number(fileInfo.size),
530
+ mtimeNs: fileInfo.mtimeNs.toString(),
531
+ };
439
532
  }
440
533
  const image = sharp(buffer, { failOn: "none" });
441
- if (autoRotate) image.rotate();
442
- image.resize({ width, withoutEnlargement: true });
443
- if (format === "avif") image.avif({ quality });
444
- else if (format === "webp") image.webp({ quality });
445
- else if (format === "jpeg") image.jpeg({ quality });
446
- else image.png({ quality });
534
+ if (options.autoRotate) image.rotate();
535
+ image.resize({ width: variant.width, withoutEnlargement: true });
536
+ if (variant.format === "avif") image.avif({ quality: options.quality, effort: options.avifEffort });
537
+ else if (variant.format === "webp") image.webp({ quality: options.quality, effort: options.webpEffort });
538
+ else if (variant.format === "jpeg") image.jpeg({ quality: options.quality });
539
+ else image.png({ quality: options.quality });
447
540
 
448
541
  const { data, info } = await image.toBuffer({ resolveWithObject: true });
449
542
  await atomicWrite(filePath, data);
450
- return { digest: digest(data), width: info.width, height: info.height };
543
+ const fileInfo = await lstat(filePath, { bigint: true });
544
+ return {
545
+ digest: digest(data),
546
+ width: info.width,
547
+ height: info.height,
548
+ size: Number(fileInfo.size),
549
+ mtimeNs: fileInfo.mtimeNs.toString(),
550
+ };
451
551
  }
452
552
 
453
553
  async function mapConcurrent(items, concurrency, callback) {
@@ -467,7 +567,7 @@ async function mapConcurrent(items, concurrency, callback) {
467
567
 
468
568
  async function processImagesFromFiles(rawOptions, requestedFiles) {
469
569
  const options = resolveOptions(rawOptions);
470
- const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG, autoRotate } = options;
570
+ const { rootDir, sourceDirectories, publicDir, concurrency, autoRotate, verification } = options;
471
571
  let { outputDir, cacheDir } = options;
472
572
  const reportedManifestPath = path.join(cacheDir, "manifest.json");
473
573
  const canonicalRoot = await canonicalizePath(rootDir);
@@ -568,15 +668,36 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
568
668
 
569
669
  const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
570
670
  const relativePath = normalizeRelativePath(path.relative(rootDir, sourcePath));
571
- const sourceBuffer = await readFile(sourcePath);
572
- const sourceHash = digest(sourceBuffer);
573
- const fingerprint = digest(`${sourceHash}\0${pipeline}`);
574
671
  const cacheEntry = oldCache.sources?.[relativePath];
575
672
  const previousEntry = oldManifest.images?.[relativePath];
576
- const dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
577
- const sourceFormat = normalizeFormat(dimensions.format);
578
- const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
579
- const expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
673
+ let sourceInfo = await sourceFileStat(sourcePath);
674
+ const canTrustSourceStat = verification === "stat"
675
+ && sourceInfo
676
+ && cacheEntry?.sourceSize === sourceInfo.size
677
+ && cacheEntry?.sourceMtimeNs === sourceInfo.mtimeNs
678
+ && cacheEntry?.autoRotate === autoRotate
679
+ && previousEntry
680
+ && typeof previousEntry.sourceHash === "string"
681
+ && Number.isSafeInteger(previousEntry.width) && previousEntry.width > 0
682
+ && Number.isSafeInteger(previousEntry.height) && previousEntry.height > 0
683
+ && typeof previousEntry.sourceFormat === "string";
684
+
685
+ let sourceBuffer;
686
+ let sourceHash;
687
+ let dimensions;
688
+ if (canTrustSourceStat) {
689
+ sourceHash = previousEntry.sourceHash;
690
+ dimensions = { width: previousEntry.width, height: previousEntry.height, format: previousEntry.sourceFormat };
691
+ } else {
692
+ sourceBuffer = await readFile(sourcePath);
693
+ sourceHash = digest(sourceBuffer);
694
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
695
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
696
+ }
697
+
698
+ let fingerprint = digest(`${sourceHash}\0${pipeline}`);
699
+ let expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
700
+ let expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
580
701
 
581
702
  const canReuse = cacheEntry?.fingerprint === fingerprint
582
703
  && previousEntry?.fingerprint === fingerprint
@@ -584,9 +705,24 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
584
705
  && previousEntry.width === dimensions.width
585
706
  && previousEntry.height === dimensions.height
586
707
  && previousEntry.sourceFormat === dimensions.format;
587
- const verifiedVariants = canReuse
588
- ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected)
708
+ let verifiedVariants = canReuse
709
+ ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected, verification)
589
710
  : undefined;
711
+
712
+ if (verifiedVariants === undefined && sourceBuffer === undefined) {
713
+ sourceBuffer = await readFile(sourcePath);
714
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
715
+ const actualHash = digest(sourceBuffer);
716
+ if (actualHash !== sourceHash) {
717
+ sourceHash = actualHash;
718
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
719
+ fingerprint = digest(`${sourceHash}\0${pipeline}`);
720
+ expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
721
+ expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
722
+ verifiedVariants = undefined;
723
+ }
724
+ }
725
+
590
726
  const isWarm = verifiedVariants !== undefined;
591
727
  let variants;
592
728
  if (isWarm) {
@@ -596,25 +732,25 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
596
732
  variants = carryForwardVariantDigests(expected, previousEntry?.variants);
597
733
  const missingVariants = [];
598
734
  for (const variant of variants) {
599
- const height = await verifiedVariantHeight(outputDir, variant, expectedByKey.get(variantKey(variant)));
600
- if (height === undefined) missingVariants.push(variant);
601
- else variant.height = height;
735
+ const verified = await verifyVariant(outputDir, variant, expectedByKey.get(variantKey(variant)), "digest");
736
+ if (!verified) missingVariants.push(variant);
737
+ else Object.assign(variant, verified);
602
738
  }
603
739
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
604
740
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
605
741
  const expectedVariant = expectedByKey.get(variantKey(variant));
606
- const output = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate, expectedVariant.height);
742
+ const output = await writeVariant(sourceBuffer, targetPath, variant, options, expectedVariant.height);
607
743
  if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
608
744
  throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
609
745
  }
610
- variant.height = output.height;
611
- variant.digest = output.digest;
746
+ Object.assign(variant, output);
612
747
  });
613
748
  processed++;
614
749
  }
615
750
 
616
751
  return {
617
752
  relativePath,
753
+ sourceInfo,
618
754
  entry: {
619
755
  source: relativePath,
620
756
  fingerprint,
@@ -627,9 +763,13 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
627
763
  };
628
764
  });
629
765
 
630
- for (const { relativePath, entry } of results) {
766
+ for (const { relativePath, entry, sourceInfo } of results) {
631
767
  manifest.images[relativePath] = entry;
632
- cache.sources[relativePath] = { fingerprint: entry.fingerprint };
768
+ cache.sources[relativePath] = {
769
+ fingerprint: entry.fingerprint,
770
+ ...(sourceInfo ? { sourceSize: sourceInfo.size, sourceMtimeNs: sourceInfo.mtimeNs } : {}),
771
+ autoRotate,
772
+ };
633
773
  }
634
774
 
635
775
  const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
@@ -657,7 +797,7 @@ export async function adoptImageVariants(rawOptions, adoption) {
657
797
  throw new TypeError("adoptImageVariants requires a variants array");
658
798
  }
659
799
 
660
- const { rootDir, sourceDirectories, publicDir } = options;
800
+ const { rootDir, sourceDirectories, publicDir, verification, autoRotate } = options;
661
801
  const sourcePath = path.resolve(rootDir, adoption.sourcePath);
662
802
  const relativePath = path.relative(rootDir, sourcePath);
663
803
  if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
@@ -720,29 +860,107 @@ export async function adoptImageVariants(rawOptions, adoption) {
720
860
  const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
721
861
  const createdPaths = [];
722
862
  try {
723
- const sourceBuffer = await readFile(sourcePath);
724
- const sourceHash = digest(sourceBuffer);
725
- if (sourceHash !== adoption.sourceHash) {
726
- throw new Error(`Adopted source changed: expected SHA-256 ${adoption.sourceHash}, received ${sourceHash} for ${sourcePath}`);
863
+ const manifestPath = path.join(cacheDir, "manifest.json");
864
+ const cachePath = path.join(cacheDir, "cache.json");
865
+ const [oldManifest, oldCache] = await Promise.all([
866
+ readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
867
+ readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
868
+ ]);
869
+ const manifest = {
870
+ version: MANIFEST_VERSION,
871
+ images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
872
+ };
873
+ const cache = {
874
+ version: CACHE_VERSION,
875
+ sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
876
+ };
877
+ const key = normalizeRelativePath(relativePath);
878
+ const previousEntry = manifest.images[key];
879
+ const cacheEntry = cache.sources[key];
880
+ let sourceInfo = await sourceFileStat(sourcePath);
881
+ const canTrustPrevious = verification === "stat"
882
+ && sourceInfo
883
+ && cacheEntry?.sourceSize === sourceInfo.size
884
+ && cacheEntry?.sourceMtimeNs === sourceInfo.mtimeNs
885
+ && cacheEntry?.autoRotate === autoRotate
886
+ && previousEntry
887
+ && previousEntry.sourceHash === adoption.sourceHash
888
+ && Number.isSafeInteger(previousEntry.width) && previousEntry.width > 0
889
+ && Number.isSafeInteger(previousEntry.height) && previousEntry.height > 0
890
+ && typeof previousEntry.sourceFormat === "string";
891
+
892
+ let sourceHash;
893
+ let dimensions;
894
+ if (canTrustPrevious) {
895
+ sourceHash = adoption.sourceHash;
896
+ dimensions = { width: previousEntry.width, height: previousEntry.height, format: previousEntry.sourceFormat };
897
+ } else {
898
+ const sourceBuffer = await readFile(sourcePath);
899
+ sourceHash = digest(sourceBuffer);
900
+ if (sourceHash !== adoption.sourceHash) {
901
+ throw new Error(`Adopted source changed: expected SHA-256 ${adoption.sourceHash}, received ${sourceHash} for ${sourcePath}`);
902
+ }
903
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
904
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
727
905
  }
728
906
 
729
- const dimensions = await imageMetadata(sourceBuffer, sourcePath, options.autoRotate);
730
- const sourceFormat = normalizeFormat(dimensions.format);
731
907
  const fingerprint = digest(`${sourceHash}\0${pipelineSettings(options)}`);
732
- const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
908
+ const expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
733
909
  const supplied = new Map();
734
910
  for (const variant of adoption.variants) {
735
- const key = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
736
- if (supplied.has(key)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
737
- supplied.set(key, variant);
911
+ const variantKeyValue = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
912
+ if (supplied.has(variantKeyValue)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
913
+ supplied.set(variantKeyValue, variant);
914
+ }
915
+ for (const expectedVariant of expected) {
916
+ if (!supplied.has(variantKey(expectedVariant))) {
917
+ throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
918
+ }
919
+ }
920
+
921
+ const persistState = async () => {
922
+ const manifestChanged = JSON.stringify(manifest.images[key]) !== JSON.stringify(oldManifest.images?.[key]);
923
+ const cacheChanged = JSON.stringify(cache.sources[key]) !== JSON.stringify(oldCache.sources?.[key]);
924
+ if (!manifestChanged && !cacheChanged) return;
925
+
926
+ const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
927
+ const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
928
+ let oldCacheText;
929
+ if (cacheChanged) {
930
+ oldCacheText = await readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error));
931
+ await atomicWrite(cachePath, cacheJson);
932
+ }
933
+ try {
934
+ if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
935
+ } catch (error) {
936
+ if (cacheChanged) {
937
+ if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
938
+ else await atomicWrite(cachePath, oldCacheText).catch(() => {});
939
+ }
940
+ throw error;
941
+ }
942
+ };
943
+
944
+ if (canTrustPrevious
945
+ && previousEntry.fingerprint === fingerprint
946
+ && cacheEntry?.fingerprint === fingerprint) {
947
+ const verifiedVariants = await verifiedOutputVariants(outputDir, previousEntry.variants, expected, verification);
948
+ if (verifiedVariants) {
949
+ manifest.images[key] = { ...previousEntry, variants: verifiedVariants };
950
+ cache.sources[key] = {
951
+ fingerprint,
952
+ sourceSize: sourceInfo.size,
953
+ sourceMtimeNs: sourceInfo.mtimeNs,
954
+ autoRotate,
955
+ };
956
+ await persistState();
957
+ return { fingerprint, adopted: expected.length, reused: expected.length, manifestPath };
958
+ }
738
959
  }
739
960
 
740
961
  const validated = [];
741
962
  for (const expectedVariant of expected) {
742
963
  const suppliedVariant = supplied.get(variantKey(expectedVariant));
743
- if (!suppliedVariant) {
744
- throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
745
- }
746
964
  const inputPath = path.resolve(rootDir, suppliedVariant.path);
747
965
  const inputInfo = await lstat(inputPath);
748
966
  if (!inputInfo.isFile() || inputInfo.isSymbolicLink()) {
@@ -771,15 +989,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
771
989
  });
772
990
  }
773
991
 
774
- const outputVariants = validated.map(({ buffer, ...variant }) => variant);
775
992
  const writeTargets = [];
776
993
  for (const variant of validated) {
777
994
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
778
995
  try {
779
996
  const info = await lstat(targetPath);
780
- if (!info.isFile() || info.isSymbolicLink() || !await variantMatches(outputDir, variant)) {
997
+ if (!info.isFile() || info.isSymbolicLink()) {
998
+ throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
999
+ }
1000
+ const matched = await readMatchingVariant(outputDir, variant);
1001
+ if (!matched) {
781
1002
  throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
782
1003
  }
1004
+ variant.size = matched.size;
1005
+ variant.mtimeNs = matched.mtimeNs;
783
1006
  } catch (error) {
784
1007
  if (error.code !== "ENOENT") throw error;
785
1008
  writeTargets.push({ targetPath, variant });
@@ -787,32 +1010,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
787
1010
  }
788
1011
 
789
1012
  for (const { targetPath, variant } of writeTargets) {
790
- const sourceVariant = validated.find((candidate) => candidate.file === variant.file);
791
- await atomicWrite(targetPath, sourceVariant.buffer);
1013
+ await atomicWrite(targetPath, variant.buffer);
1014
+ const fileInfo = await lstat(targetPath, { bigint: true });
1015
+ variant.size = Number(fileInfo.size);
1016
+ variant.mtimeNs = fileInfo.mtimeNs.toString();
792
1017
  createdPaths.push({ targetPath, variant });
793
1018
  }
794
1019
 
795
- if (digest(await readFile(sourcePath)) !== sourceHash) {
1020
+ if ((!canTrustPrevious || writeTargets.length > 0) && digest(await readFile(sourcePath)) !== sourceHash) {
796
1021
  throw new Error(`Adopted source changed during migration: ${sourcePath}`);
797
1022
  }
798
1023
 
799
- const manifestPath = path.join(cacheDir, "manifest.json");
800
- const cachePath = path.join(cacheDir, "cache.json");
801
- const [oldManifest, oldCache, oldCacheText] = await Promise.all([
802
- readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
803
- readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
804
- readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error)),
805
- ]);
806
- const manifest = {
807
- version: MANIFEST_VERSION,
808
- images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
809
- };
810
- const cache = {
811
- version: CACHE_VERSION,
812
- sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
813
- };
814
- manifest.images[normalizeRelativePath(relativePath)] = {
815
- source: normalizeRelativePath(relativePath),
1024
+ const outputVariants = validated.map(({ buffer, ...variant }) => variant);
1025
+ manifest.images[key] = {
1026
+ source: key,
816
1027
  fingerprint,
817
1028
  sourceHash,
818
1029
  sourceFormat: dimensions.format,
@@ -820,22 +1031,12 @@ export async function adoptImageVariants(rawOptions, adoption) {
820
1031
  height: dimensions.height,
821
1032
  variants: outputVariants,
822
1033
  };
823
- cache.sources[normalizeRelativePath(relativePath)] = { fingerprint };
824
- const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
825
- const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
826
- const manifestChanged = manifestJson !== `${JSON.stringify(oldManifest, null, 2)}\n`;
827
- const cacheChanged = cacheJson !== `${JSON.stringify(oldCache, null, 2)}\n`;
828
-
829
- if (cacheChanged) await atomicWrite(cachePath, cacheJson);
830
- try {
831
- if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
832
- } catch (error) {
833
- if (cacheChanged) {
834
- if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
835
- else await atomicWrite(cachePath, oldCacheText).catch(() => {});
836
- }
837
- throw error;
838
- }
1034
+ cache.sources[key] = {
1035
+ fingerprint,
1036
+ ...(sourceInfo ? { sourceSize: sourceInfo.size, sourceMtimeNs: sourceInfo.mtimeNs } : {}),
1037
+ autoRotate,
1038
+ };
1039
+ await persistState();
839
1040
 
840
1041
  return {
841
1042
  fingerprint,