@all-the.rest/astro-image-cdn 0.3.0 → 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
@@ -73,6 +73,7 @@ With this option, `astro dev` installs the image service and local asset route,
73
73
  | `includeSourceFormat` | `true` | Also generate each supported source-native format. Set `false` for only the formats listed in `formats`. |
74
74
  | `includeNativeWidth` | `true` | Also generate the source's native width when it is not already in `widths`. |
75
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. |
76
77
  | `concurrency` | `4` | Maximum number of source images processed at once. |
77
78
  | `devOnly` | `false` | Install the integration only for `astro dev`; other Astro commands retain their configured image service. |
78
79
 
@@ -91,10 +92,11 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
91
92
  ## Persistence and cache behavior
92
93
 
93
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.
94
- - 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.
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.
95
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.
96
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.
97
- - 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.
98
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.
99
101
  - Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
100
102
 
@@ -126,7 +128,7 @@ await adoptImageVariants({
126
128
  });
127
129
  ```
128
130
 
129
- 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.
130
132
 
131
133
  ## API
132
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@all-the.rest/astro-image-cdn",
3
- "version": "0.3.0",
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
@@ -17,6 +17,12 @@ interface AstroImageCdnBaseOptions {
17
17
  webpEffort?: number;
18
18
  /** AVIF encoder effort, integer from 0 (fastest) to 9 (slowest). Defaults to Sharp's default, 4. */
19
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";
20
26
  /** Also generate a supported source-native format. Defaults to true. */
21
27
  includeSourceFormat?: boolean;
22
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, resolveEncoderEfforts } 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));
@@ -83,6 +83,7 @@ export default function astroImageCdn(options) {
83
83
  }
84
84
  const baseUrl = typeof options.baseUrl === "string" ? normalizeBaseUrl(options.baseUrl) : "";
85
85
  const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
86
+ const verification = resolveVerification(options);
86
87
  let projectRoot;
87
88
  let outputDir;
88
89
  let cacheDir;
@@ -114,6 +115,7 @@ export default function astroImageCdn(options) {
114
115
  quality: options.quality ?? 75,
115
116
  webpEffort,
116
117
  avifEffort,
118
+ verification,
117
119
  includeSourceFormat: options.includeSourceFormat ?? true,
118
120
  includeNativeWidth: options.includeNativeWidth ?? true,
119
121
  autoRotate: options.autoRotate ?? true,
package/src/processor.js CHANGED
@@ -10,6 +10,7 @@ const DEFAULT_WIDTHS = [256, 640, 828, 1080, 1200, 1920, 2048];
10
10
  const DEFAULT_FORMATS = ["avif", "webp"];
11
11
  const DEFAULT_WEBP_EFFORT = 4;
12
12
  const DEFAULT_AVIF_EFFORT = 4;
13
+ const DEFAULT_VERIFICATION = "stat";
13
14
  const SUPPORTED_FORMATS = new Set(["avif", "webp", "jpeg", "png", "svg"]);
14
15
  const IMAGE_EXTENSIONS = new Set([
15
16
  ".avif", ".gif", ".heic", ".heif", ".jpeg", ".jpg", ".png", ".svg", ".tif", ".tiff", ".webp",
@@ -129,6 +130,14 @@ export function resolveEncoderEfforts(options) {
129
130
  return { webpEffort, avifEffort };
130
131
  }
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
+
132
141
  function heightMatchesExpected(expected, actual) {
133
142
  return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
134
143
  }
@@ -147,6 +156,7 @@ function resolveOptions(options) {
147
156
  const formats = [...new Set((options.formats ?? DEFAULT_FORMATS).map(normalizeFormat))];
148
157
  const quality = options.quality ?? 75;
149
158
  const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
159
+ const verification = resolveVerification(options);
150
160
  const concurrency = options.concurrency ?? 4;
151
161
  const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
152
162
  const includeSourceFormat = options.includeSourceFormat ?? true;
@@ -181,6 +191,7 @@ function resolveOptions(options) {
181
191
  quality,
182
192
  webpEffort,
183
193
  avifEffort,
194
+ verification,
184
195
  concurrency,
185
196
  dangerouslyProcessSVG,
186
197
  includeSourceFormat,
@@ -335,9 +346,37 @@ function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
335
346
  })));
336
347
  }
337
348
 
338
- async function readMatchingVariant(outputDir, variant) {
339
- if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return undefined;
340
- 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);
341
380
  if (!isInside(outputDir, filePath) || filePath === outputDir) return undefined;
342
381
 
343
382
  try {
@@ -349,33 +388,49 @@ async function readMatchingVariant(outputDir, variant) {
349
388
  const directoryInfo = await lstat(directory);
350
389
  if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return undefined;
351
390
  }
352
- const fileInfo = await lstat(filePath);
353
- if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return undefined;
354
- const buffer = await readFile(filePath);
355
- return digest(buffer) === variant.digest ? buffer : undefined;
391
+ const info = await fileStat(filePath);
392
+ return info ? { filePath, ...info } : undefined;
356
393
  } catch (error) {
357
394
  if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
358
395
  throw error;
359
396
  }
360
397
  }
361
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
+
362
407
  async function variantMatches(outputDir, variant) {
363
408
  return (await readMatchingVariant(outputDir, variant)) !== undefined;
364
409
  }
365
410
 
366
- async function verifiedVariantHeight(outputDir, variant, expectedVariant) {
367
- const buffer = await readMatchingVariant(outputDir, variant);
368
- 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;
369
424
  let metadata;
370
425
  try {
371
- metadata = await sharp(buffer, { failOn: "none" }).metadata();
426
+ metadata = await sharp(matched.buffer, { failOn: "none" }).metadata();
372
427
  } catch {
373
428
  return undefined;
374
429
  }
375
430
  if (normalizeVariantFormat(metadata) !== expectedVariant.format
376
431
  || metadata.width !== expectedVariant.width
377
432
  || !heightMatchesExpected(expectedVariant.height, metadata.height)) return undefined;
378
- return metadata.height;
433
+ return { ...variant, height: metadata.height, size: matched.size, mtimeNs: matched.mtimeNs };
379
434
  }
380
435
 
381
436
  function variantKey(variant) {
@@ -386,7 +441,7 @@ function hasCompleteVariantSet(actual, expected) {
386
441
  if (!Array.isArray(actual) || actual.length !== expected.length) return false;
387
442
  const byKey = new Map();
388
443
  for (const variant of actual) {
389
- if (!variant || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
444
+ if (!hasValidVariantIdentity(variant)) return false;
390
445
  const key = variantKey(variant);
391
446
  if (byKey.has(key)) return false;
392
447
  byKey.set(key, variant);
@@ -397,15 +452,15 @@ function hasCompleteVariantSet(actual, expected) {
397
452
  });
398
453
  }
399
454
 
400
- async function verifiedOutputVariants(outputDir, actual, expected) {
455
+ async function verifiedOutputVariants(outputDir, actual, expected, verification) {
401
456
  if (!hasCompleteVariantSet(actual, expected)) return undefined;
402
457
  const actualByKey = new Map(actual.map((variant) => [variantKey(variant), variant]));
403
458
  const verified = [];
404
459
  for (const expectedVariant of expected) {
405
460
  const variant = actualByKey.get(variantKey(expectedVariant));
406
- const height = await verifiedVariantHeight(outputDir, variant, expectedVariant);
407
- if (height === undefined) return undefined;
408
- verified.push({ ...variant, height });
461
+ const verifiedVariant = await verifyVariant(outputDir, variant, expectedVariant, verification);
462
+ if (!verifiedVariant) return undefined;
463
+ verified.push(verifiedVariant);
409
464
  }
410
465
  return verified;
411
466
  }
@@ -414,7 +469,7 @@ function carryForwardVariantDigests(expected, previous) {
414
469
  const previousByKey = new Map();
415
470
  if (Array.isArray(previous)) {
416
471
  for (const variant of previous) {
417
- if (variant && /^[a-f0-9]{64}$/.test(variant.digest ?? "")) {
472
+ if (hasValidVariantIdentity(variant)) {
418
473
  previousByKey.set(variantKey(variant), variant);
419
474
  }
420
475
  }
@@ -423,7 +478,14 @@ function carryForwardVariantDigests(expected, previous) {
423
478
  return expected.map((variant) => {
424
479
  const previousVariant = previousByKey.get(variantKey(variant));
425
480
  if (previousVariant?.file === variant.file && heightMatchesExpected(variant.height, previousVariant.height)) {
426
- 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
+ };
427
489
  }
428
490
  return variant;
429
491
  });
@@ -459,7 +521,14 @@ async function ensureVariantDirectory(outputDir, file) {
459
521
  async function writeVariant(buffer, filePath, variant, options, expectedHeight) {
460
522
  if (variant.format === "svg") {
461
523
  await atomicWrite(filePath, buffer);
462
- return { digest: digest(buffer), width: variant.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
+ };
463
532
  }
464
533
  const image = sharp(buffer, { failOn: "none" });
465
534
  if (options.autoRotate) image.rotate();
@@ -471,7 +540,14 @@ async function writeVariant(buffer, filePath, variant, options, expectedHeight)
471
540
 
472
541
  const { data, info } = await image.toBuffer({ resolveWithObject: true });
473
542
  await atomicWrite(filePath, data);
474
- 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
+ };
475
551
  }
476
552
 
477
553
  async function mapConcurrent(items, concurrency, callback) {
@@ -491,7 +567,7 @@ async function mapConcurrent(items, concurrency, callback) {
491
567
 
492
568
  async function processImagesFromFiles(rawOptions, requestedFiles) {
493
569
  const options = resolveOptions(rawOptions);
494
- const { rootDir, sourceDirectories, publicDir, concurrency, autoRotate } = options;
570
+ const { rootDir, sourceDirectories, publicDir, concurrency, autoRotate, verification } = options;
495
571
  let { outputDir, cacheDir } = options;
496
572
  const reportedManifestPath = path.join(cacheDir, "manifest.json");
497
573
  const canonicalRoot = await canonicalizePath(rootDir);
@@ -592,15 +668,36 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
592
668
 
593
669
  const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
594
670
  const relativePath = normalizeRelativePath(path.relative(rootDir, sourcePath));
595
- const sourceBuffer = await readFile(sourcePath);
596
- const sourceHash = digest(sourceBuffer);
597
- const fingerprint = digest(`${sourceHash}\0${pipeline}`);
598
671
  const cacheEntry = oldCache.sources?.[relativePath];
599
672
  const previousEntry = oldManifest.images?.[relativePath];
600
- const dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
601
- const sourceFormat = normalizeFormat(dimensions.format);
602
- const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
603
- 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]));
604
701
 
605
702
  const canReuse = cacheEntry?.fingerprint === fingerprint
606
703
  && previousEntry?.fingerprint === fingerprint
@@ -608,9 +705,24 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
608
705
  && previousEntry.width === dimensions.width
609
706
  && previousEntry.height === dimensions.height
610
707
  && previousEntry.sourceFormat === dimensions.format;
611
- const verifiedVariants = canReuse
612
- ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected)
708
+ let verifiedVariants = canReuse
709
+ ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected, verification)
613
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
+
614
726
  const isWarm = verifiedVariants !== undefined;
615
727
  let variants;
616
728
  if (isWarm) {
@@ -620,9 +732,9 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
620
732
  variants = carryForwardVariantDigests(expected, previousEntry?.variants);
621
733
  const missingVariants = [];
622
734
  for (const variant of variants) {
623
- const height = await verifiedVariantHeight(outputDir, variant, expectedByKey.get(variantKey(variant)));
624
- if (height === undefined) missingVariants.push(variant);
625
- 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);
626
738
  }
627
739
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
628
740
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
@@ -631,14 +743,14 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
631
743
  if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
632
744
  throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
633
745
  }
634
- variant.height = output.height;
635
- variant.digest = output.digest;
746
+ Object.assign(variant, output);
636
747
  });
637
748
  processed++;
638
749
  }
639
750
 
640
751
  return {
641
752
  relativePath,
753
+ sourceInfo,
642
754
  entry: {
643
755
  source: relativePath,
644
756
  fingerprint,
@@ -651,9 +763,13 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
651
763
  };
652
764
  });
653
765
 
654
- for (const { relativePath, entry } of results) {
766
+ for (const { relativePath, entry, sourceInfo } of results) {
655
767
  manifest.images[relativePath] = entry;
656
- 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
+ };
657
773
  }
658
774
 
659
775
  const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
@@ -681,7 +797,7 @@ export async function adoptImageVariants(rawOptions, adoption) {
681
797
  throw new TypeError("adoptImageVariants requires a variants array");
682
798
  }
683
799
 
684
- const { rootDir, sourceDirectories, publicDir } = options;
800
+ const { rootDir, sourceDirectories, publicDir, verification, autoRotate } = options;
685
801
  const sourcePath = path.resolve(rootDir, adoption.sourcePath);
686
802
  const relativePath = path.relative(rootDir, sourcePath);
687
803
  if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
@@ -744,29 +860,107 @@ export async function adoptImageVariants(rawOptions, adoption) {
744
860
  const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
745
861
  const createdPaths = [];
746
862
  try {
747
- const sourceBuffer = await readFile(sourcePath);
748
- const sourceHash = digest(sourceBuffer);
749
- if (sourceHash !== adoption.sourceHash) {
750
- 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;
751
905
  }
752
906
 
753
- const dimensions = await imageMetadata(sourceBuffer, sourcePath, options.autoRotate);
754
- const sourceFormat = normalizeFormat(dimensions.format);
755
907
  const fingerprint = digest(`${sourceHash}\0${pipelineSettings(options)}`);
756
- const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
908
+ const expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
757
909
  const supplied = new Map();
758
910
  for (const variant of adoption.variants) {
759
- const key = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
760
- if (supplied.has(key)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
761
- 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
+ }
762
959
  }
763
960
 
764
961
  const validated = [];
765
962
  for (const expectedVariant of expected) {
766
963
  const suppliedVariant = supplied.get(variantKey(expectedVariant));
767
- if (!suppliedVariant) {
768
- throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
769
- }
770
964
  const inputPath = path.resolve(rootDir, suppliedVariant.path);
771
965
  const inputInfo = await lstat(inputPath);
772
966
  if (!inputInfo.isFile() || inputInfo.isSymbolicLink()) {
@@ -795,15 +989,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
795
989
  });
796
990
  }
797
991
 
798
- const outputVariants = validated.map(({ buffer, ...variant }) => variant);
799
992
  const writeTargets = [];
800
993
  for (const variant of validated) {
801
994
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
802
995
  try {
803
996
  const info = await lstat(targetPath);
804
- if (!info.isFile() || info.isSymbolicLink() || !await variantMatches(outputDir, variant)) {
997
+ if (!info.isFile() || info.isSymbolicLink()) {
805
998
  throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
806
999
  }
1000
+ const matched = await readMatchingVariant(outputDir, variant);
1001
+ if (!matched) {
1002
+ throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
1003
+ }
1004
+ variant.size = matched.size;
1005
+ variant.mtimeNs = matched.mtimeNs;
807
1006
  } catch (error) {
808
1007
  if (error.code !== "ENOENT") throw error;
809
1008
  writeTargets.push({ targetPath, variant });
@@ -811,32 +1010,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
811
1010
  }
812
1011
 
813
1012
  for (const { targetPath, variant } of writeTargets) {
814
- const sourceVariant = validated.find((candidate) => candidate.file === variant.file);
815
- 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();
816
1017
  createdPaths.push({ targetPath, variant });
817
1018
  }
818
1019
 
819
- if (digest(await readFile(sourcePath)) !== sourceHash) {
1020
+ if ((!canTrustPrevious || writeTargets.length > 0) && digest(await readFile(sourcePath)) !== sourceHash) {
820
1021
  throw new Error(`Adopted source changed during migration: ${sourcePath}`);
821
1022
  }
822
1023
 
823
- const manifestPath = path.join(cacheDir, "manifest.json");
824
- const cachePath = path.join(cacheDir, "cache.json");
825
- const [oldManifest, oldCache, oldCacheText] = await Promise.all([
826
- readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
827
- readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
828
- readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error)),
829
- ]);
830
- const manifest = {
831
- version: MANIFEST_VERSION,
832
- images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
833
- };
834
- const cache = {
835
- version: CACHE_VERSION,
836
- sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
837
- };
838
- manifest.images[normalizeRelativePath(relativePath)] = {
839
- source: normalizeRelativePath(relativePath),
1024
+ const outputVariants = validated.map(({ buffer, ...variant }) => variant);
1025
+ manifest.images[key] = {
1026
+ source: key,
840
1027
  fingerprint,
841
1028
  sourceHash,
842
1029
  sourceFormat: dimensions.format,
@@ -844,22 +1031,12 @@ export async function adoptImageVariants(rawOptions, adoption) {
844
1031
  height: dimensions.height,
845
1032
  variants: outputVariants,
846
1033
  };
847
- cache.sources[normalizeRelativePath(relativePath)] = { fingerprint };
848
- const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
849
- const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
850
- const manifestChanged = manifestJson !== `${JSON.stringify(oldManifest, null, 2)}\n`;
851
- const cacheChanged = cacheJson !== `${JSON.stringify(oldCache, null, 2)}\n`;
852
-
853
- if (cacheChanged) await atomicWrite(cachePath, cacheJson);
854
- try {
855
- if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
856
- } catch (error) {
857
- if (cacheChanged) {
858
- if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
859
- else await atomicWrite(cachePath, oldCacheText).catch(() => {});
860
- }
861
- throw error;
862
- }
1034
+ cache.sources[key] = {
1035
+ fingerprint,
1036
+ ...(sourceInfo ? { sourceSize: sourceInfo.size, sourceMtimeNs: sourceInfo.mtimeNs } : {}),
1037
+ autoRotate,
1038
+ };
1039
+ await persistState();
863
1040
 
864
1041
  return {
865
1042
  fingerprint,