@all-the.rest/astro-image-cdn 0.3.0 → 0.4.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/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,11 +92,12 @@ 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.
98
- - 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
+ - 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.
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; use `pruneImages()` when reclaiming that space is intended.
99
101
  - Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
100
102
 
101
103
  ### Adopting existing variants
@@ -126,7 +128,41 @@ 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.
132
+
133
+ ### Pruning stale variants
134
+
135
+ Because old variants are retained, `outputDir` keeps growing after style or pipeline changes. `pruneImages()` deletes files under `outputDir` that the private manifest does not reference and removes directories that become empty. It never reads, writes, or deletes sources, and it takes the same writer lock as `processImages()`/the integration, so it refuses to run while a build holds that lock.
136
+
137
+ ```js
138
+ import { pruneImages } from "@all-the.rest/astro-image-cdn";
139
+
140
+ const preview = await pruneImages({
141
+ rootDir: process.cwd(),
142
+ outputDir: ".imagedist",
143
+ cacheDir: ".astro-image-cdn",
144
+ dryRun: true,
145
+ });
146
+ console.log(preview);
147
+
148
+ const result = await pruneImages({
149
+ rootDir: process.cwd(),
150
+ outputDir: ".imagedist",
151
+ cacheDir: ".astro-image-cdn",
152
+ });
153
+ ```
154
+
155
+ Pruning is intended for the point after a successful pipeline run or build has written the manifest and outputs that should be kept, and before publishing `outputDir`. Run it only when the private manifest is current: variants referenced by the manifest are always kept, so a stale manifest can keep stale variants, while a manifest from a different configuration cannot protect variants it does not know about. Start with `dryRun: true` to inspect the counts. The operation is not a substitute for running `processImages()` first.
156
+
157
+ - The private manifest is mandatory and is the sole authority for what is kept. `pruneImages()` refuses to start when `cacheDir/manifest.json` is missing, malformed, or contains an entry whose variant file is missing, unsafe, symlinked, or outside `outputDir`; refusing is deliberate, so a bad manifest cannot cause an unbounded delete. Referenced variants are checked before anything is deleted.
158
+ - An **empty manifest is not a no-op**: when `images` is `{}`, every file under `outputDir` is unreferenced and will be deleted. This can happen after `processImages()` ran against an empty source tree or a `sources` setting that contains no images. Confirm that is intended before pruning.
159
+ - `outputDir` must be a dedicated variants directory. It must not equal or contain `rootDir`, and it must not overlap Astro's `publicDir`, any configured `sources` directory, or `cacheDir`. The `rootDir` check applies even when `sources: []`, so a misconfigured absolute `outputDir` cannot prune the project itself.
160
+ - Only regular files under `outputDir` are deleted. Symlinks are never followed or unlinked, other special files are left untouched, and the writer lock file at the output root is ignored (a nested file with the same name is ordinary output). Kept files are never modified.
161
+ - Empty directories below `outputDir` are removed; `outputDir` itself and `cacheDir` are kept.
162
+ - A legacy public `manifest.json` in `outputDir` is reported in `legacyPublicManifestPath` and kept by default. Set `removeLegacyPublicManifest: true` to delete it (it is then included in `removed`/`bytesFreed`). Verify ownership before enabling this, as with the warning emitted during processing.
163
+ - `removed` counts deleted variant files, `kept` counts regular files and symlinks left in `outputDir` (the writer lock is not counted), `bytesFreed` sums the deleted files' sizes, and `removedDirectories` counts removed empty directories. With `dryRun: true`, all four report what would happen while nothing is deleted; `legacyPublicManifestRemoved` then means it would be removed.
164
+
165
+ The writer lock serializes this package's writers, not arbitrary processes. Pruning re-checks each directory and file immediately before descending or unlinking and never follows symlinks, but path-based filesystem APIs cannot make `outputDir` immutable. If another process concurrently renames or replaces entries inside `outputDir`, behavior is outside the guarantee. Run pruning as a build step on a quiescent output directory, or against a snapshot where external mutation cannot occur.
130
166
 
131
167
  ## API
132
168
 
@@ -146,6 +182,8 @@ console.log(result);
146
182
 
147
183
  The returned counts distinguish newly processed images from warm-cache reuses. `manifestPath` points into the configured private `cacheDir`; `legacyPublicManifestPath` is set when a pre-existing public manifest was found. This API only generates files and a manifest; it performs no deployment.
148
184
 
185
+ The exported `pruneImages()` API complements `processImages()` by reclaiming space from variants the manifest no longer references (see [Pruning stale variants](#pruning-stale-variants)). It accepts the same directory options plus `dryRun` and `removeLegacyPublicManifest`, and returns `removed`, `kept`, `bytesFreed`, `removedDirectories`, `dryRun`, `manifestPath`, `legacyPublicManifestPath`, and `legacyPublicManifestRemoved`. It never deploys and never touches `dist/`.
186
+
149
187
  The standalone processor rejects `outputDir` or `cacheDir` inside Astro's `publicDir`, including symlink aliases. It assumes `rootDir/public` by default; pass `publicDir` when the Astro project customizes that directory. The integration supplies Astro's configured `publicDir` automatically.
150
188
 
151
189
  ## Development and verification
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.1",
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. */
@@ -57,6 +63,43 @@ export interface ProcessImagesResult {
57
63
  legacyPublicManifestPath?: string;
58
64
  }
59
65
 
66
+ export interface PruneImagesOptions {
67
+ rootDir: string;
68
+ /** Directories that contain image sources; used only to reject unsafe overlaps. Defaults to ["src"]. */
69
+ sources?: string[];
70
+ /** Astro's public directory, relative to rootDir. Defaults to "public". */
71
+ publicDir?: string;
72
+ /**
73
+ * Persistent generated image directory, relative to rootDir. Defaults to ".imagedist".
74
+ * Must not equal or contain rootDir, and must not overlap publicDir, sources, or cacheDir.
75
+ */
76
+ outputDir?: string;
77
+ /** Incremental state directory, relative to rootDir. Defaults to ".astro-image-cdn". */
78
+ cacheDir?: string;
79
+ /** Report what would be removed without deleting anything. Defaults to false. */
80
+ dryRun?: boolean;
81
+ /** Also remove a legacy public manifest.json in outputDir. Defaults to false. */
82
+ removeLegacyPublicManifest?: boolean;
83
+ }
84
+
85
+ export interface PruneImagesResult {
86
+ /** Variant files deleted; in a dry run, files that would be deleted. */
87
+ removed: number;
88
+ /** Regular files and symlinks left in outputDir. The writer lock is not counted. */
89
+ kept: number;
90
+ /** Sum of the deleted files' sizes in bytes; in a dry run, bytes that would be freed. */
91
+ bytesFreed: number;
92
+ /** Empty directories removed; in a dry run, directories that would be removed. */
93
+ removedDirectories: number;
94
+ dryRun: boolean;
95
+ /** Private manifest that was used as the reference, inside cacheDir. */
96
+ manifestPath: string;
97
+ /** Legacy public manifest found in outputDir, if any. */
98
+ legacyPublicManifestPath?: string;
99
+ /** Whether the legacy public manifest was removed; in a dry run, whether it would be removed. */
100
+ legacyPublicManifestRemoved: boolean;
101
+ }
102
+
60
103
  export interface AdoptImageVariant {
61
104
  /** Existing encoded output path; relative paths are resolved from rootDir. */
62
105
  path: string;
@@ -83,6 +126,7 @@ export interface AdoptImageVariantsResult {
83
126
  export default function astroImageCdn(options: AstroImageCdnOptions): AstroIntegration;
84
127
 
85
128
  export declare function processImages(options: ProcessImagesOptions): Promise<ProcessImagesResult>;
129
+ export declare function pruneImages(options: PruneImagesOptions): Promise<PruneImagesResult>;
86
130
  export declare function adoptImageVariants(
87
131
  options: ProcessImagesOptions,
88
132
  input: AdoptImageVariantsInput,
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,
@@ -156,4 +158,4 @@ export default function astroImageCdn(options) {
156
158
  };
157
159
  }
158
160
 
159
- export { adoptImageVariants, processImages } from "./processor.js";
161
+ export { adoptImageVariants, processImages, pruneImages } from "./processor.js";
package/src/processor.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { open, readdir, readFile, realpath, rename, mkdir, lstat, unlink, writeFile } from "node:fs/promises";
2
+ import { open, readdir, readFile, realpath, rename, mkdir, lstat, rmdir, unlink, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import sharp from "sharp";
5
5
 
@@ -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",
@@ -60,6 +61,44 @@ async function canonicalizePath(value) {
60
61
  }
61
62
  }
62
63
 
64
+ async function resolveCanonicalDirectories(options) {
65
+ const { rootDir, sourceDirectories, publicDir } = options;
66
+ const canonicalRoot = await canonicalizePath(rootDir);
67
+ const canonicalSources = [];
68
+ for (const sourceDirectory of sourceDirectories) {
69
+ const relative = path.relative(rootDir, sourceDirectory);
70
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
71
+ throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
72
+ }
73
+ const canonicalSource = await canonicalizePath(sourceDirectory);
74
+ if (!isInside(canonicalRoot, canonicalSource)) {
75
+ throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
76
+ }
77
+ canonicalSources.push(canonicalSource);
78
+ }
79
+
80
+ const canonicalOutputDir = await canonicalizePath(options.outputDir);
81
+ const canonicalCacheDir = await canonicalizePath(options.cacheDir);
82
+ const canonicalPublicDir = await canonicalizePath(publicDir);
83
+ if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
84
+ throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
85
+ }
86
+ for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
87
+ if (isInside(canonicalPublicDir, directory)) {
88
+ throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
89
+ }
90
+ }
91
+ for (const canonicalSource of canonicalSources) {
92
+ for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
93
+ if (pathsOverlap(canonicalSource, directory)) {
94
+ throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
95
+ }
96
+ }
97
+ }
98
+
99
+ return { canonicalRoot, canonicalSources, canonicalOutputDir, canonicalCacheDir, canonicalPublicDir };
100
+ }
101
+
63
102
  async function releaseWriterLocks(locks) {
64
103
  for (const { lockPath, token } of [...locks].reverse()) {
65
104
  try {
@@ -129,6 +168,14 @@ export function resolveEncoderEfforts(options) {
129
168
  return { webpEffort, avifEffort };
130
169
  }
131
170
 
171
+ export function resolveVerification(options) {
172
+ const verification = options.verification ?? DEFAULT_VERIFICATION;
173
+ if (verification !== "stat" && verification !== "digest") {
174
+ throw new TypeError(`verification must be "stat" or "digest"; received ${JSON.stringify(verification)}`);
175
+ }
176
+ return verification;
177
+ }
178
+
132
179
  function heightMatchesExpected(expected, actual) {
133
180
  return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
134
181
  }
@@ -147,6 +194,7 @@ function resolveOptions(options) {
147
194
  const formats = [...new Set((options.formats ?? DEFAULT_FORMATS).map(normalizeFormat))];
148
195
  const quality = options.quality ?? 75;
149
196
  const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
197
+ const verification = resolveVerification(options);
150
198
  const concurrency = options.concurrency ?? 4;
151
199
  const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
152
200
  const includeSourceFormat = options.includeSourceFormat ?? true;
@@ -181,6 +229,7 @@ function resolveOptions(options) {
181
229
  quality,
182
230
  webpEffort,
183
231
  avifEffort,
232
+ verification,
184
233
  concurrency,
185
234
  dangerouslyProcessSVG,
186
235
  includeSourceFormat,
@@ -189,6 +238,25 @@ function resolveOptions(options) {
189
238
  };
190
239
  }
191
240
 
241
+ function resolvePruneOptions(options) {
242
+ if (!options || typeof options.rootDir !== "string") {
243
+ throw new TypeError("pruneImages requires an absolute rootDir");
244
+ }
245
+
246
+ const rootDir = path.resolve(options.rootDir);
247
+ const sourceDirectories = (options.sources ?? ["src"]).map((source) => path.resolve(rootDir, source));
248
+ const publicDir = path.resolve(rootDir, options.publicDir ?? "public");
249
+ const outputDir = path.resolve(rootDir, options.outputDir ?? ".imagedist");
250
+ const cacheDir = path.resolve(rootDir, options.cacheDir ?? ".astro-image-cdn");
251
+ const dryRun = options.dryRun ?? false;
252
+ const removeLegacyPublicManifest = options.removeLegacyPublicManifest ?? false;
253
+ for (const [label, value] of Object.entries({ dryRun, removeLegacyPublicManifest })) {
254
+ if (typeof value !== "boolean") throw new TypeError(`${label} must be a boolean`);
255
+ }
256
+
257
+ return { rootDir, sourceDirectories, publicDir, outputDir, cacheDir, dryRun, removeLegacyPublicManifest };
258
+ }
259
+
192
260
  async function walk(directory, output, excludedPaths) {
193
261
  let entries;
194
262
  try {
@@ -335,9 +403,37 @@ function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
335
403
  })));
336
404
  }
337
405
 
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);
406
+ function hasValidVariantIdentity(variant) {
407
+ return Boolean(variant)
408
+ && typeof variant.file === "string"
409
+ && /^[a-f0-9]{64}$/.test(variant.digest ?? "");
410
+ }
411
+
412
+ async function fileStat(filePath) {
413
+ const info = await lstat(filePath, { bigint: true });
414
+ if (!info.isFile() || info.isSymbolicLink()) return undefined;
415
+ return { size: Number(info.size), mtimeNs: info.mtimeNs.toString() };
416
+ }
417
+
418
+ async function sourceFileStat(filePath) {
419
+ try {
420
+ return await fileStat(filePath);
421
+ } catch (error) {
422
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
423
+ throw error;
424
+ }
425
+ }
426
+
427
+ function matchesRecordedStat(variant, info) {
428
+ return Number.isSafeInteger(variant?.size)
429
+ && variant.size === info.size
430
+ && typeof variant?.mtimeNs === "string"
431
+ && variant.mtimeNs === info.mtimeNs;
432
+ }
433
+
434
+ async function inspectVariantFile(outputDir, file) {
435
+ if (typeof file !== "string") return undefined;
436
+ const filePath = path.resolve(outputDir, file);
341
437
  if (!isInside(outputDir, filePath) || filePath === outputDir) return undefined;
342
438
 
343
439
  try {
@@ -349,33 +445,49 @@ async function readMatchingVariant(outputDir, variant) {
349
445
  const directoryInfo = await lstat(directory);
350
446
  if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return undefined;
351
447
  }
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;
448
+ const info = await fileStat(filePath);
449
+ return info ? { filePath, ...info } : undefined;
356
450
  } catch (error) {
357
451
  if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
358
452
  throw error;
359
453
  }
360
454
  }
361
455
 
456
+ async function readMatchingVariant(outputDir, variant) {
457
+ if (!hasValidVariantIdentity(variant)) return undefined;
458
+ const inspected = await inspectVariantFile(outputDir, variant.file);
459
+ if (!inspected) return undefined;
460
+ const buffer = await readFile(inspected.filePath);
461
+ return digest(buffer) === variant.digest ? { buffer, ...inspected } : undefined;
462
+ }
463
+
362
464
  async function variantMatches(outputDir, variant) {
363
465
  return (await readMatchingVariant(outputDir, variant)) !== undefined;
364
466
  }
365
467
 
366
- async function verifiedVariantHeight(outputDir, variant, expectedVariant) {
367
- const buffer = await readMatchingVariant(outputDir, variant);
368
- if (!buffer) return undefined;
468
+ async function verifyVariant(outputDir, variant, expectedVariant, verification) {
469
+ if (!hasValidVariantIdentity(variant) || !expectedVariant) return undefined;
470
+ if (verification === "stat") {
471
+ const inspected = await inspectVariantFile(outputDir, variant.file);
472
+ if (inspected
473
+ && matchesRecordedStat(variant, inspected)
474
+ && heightMatchesExpected(expectedVariant.height, variant.height)) {
475
+ return { ...variant, size: inspected.size, mtimeNs: inspected.mtimeNs };
476
+ }
477
+ }
478
+
479
+ const matched = await readMatchingVariant(outputDir, variant);
480
+ if (!matched) return undefined;
369
481
  let metadata;
370
482
  try {
371
- metadata = await sharp(buffer, { failOn: "none" }).metadata();
483
+ metadata = await sharp(matched.buffer, { failOn: "none" }).metadata();
372
484
  } catch {
373
485
  return undefined;
374
486
  }
375
487
  if (normalizeVariantFormat(metadata) !== expectedVariant.format
376
488
  || metadata.width !== expectedVariant.width
377
489
  || !heightMatchesExpected(expectedVariant.height, metadata.height)) return undefined;
378
- return metadata.height;
490
+ return { ...variant, height: metadata.height, size: matched.size, mtimeNs: matched.mtimeNs };
379
491
  }
380
492
 
381
493
  function variantKey(variant) {
@@ -386,7 +498,7 @@ function hasCompleteVariantSet(actual, expected) {
386
498
  if (!Array.isArray(actual) || actual.length !== expected.length) return false;
387
499
  const byKey = new Map();
388
500
  for (const variant of actual) {
389
- if (!variant || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
501
+ if (!hasValidVariantIdentity(variant)) return false;
390
502
  const key = variantKey(variant);
391
503
  if (byKey.has(key)) return false;
392
504
  byKey.set(key, variant);
@@ -397,15 +509,15 @@ function hasCompleteVariantSet(actual, expected) {
397
509
  });
398
510
  }
399
511
 
400
- async function verifiedOutputVariants(outputDir, actual, expected) {
512
+ async function verifiedOutputVariants(outputDir, actual, expected, verification) {
401
513
  if (!hasCompleteVariantSet(actual, expected)) return undefined;
402
514
  const actualByKey = new Map(actual.map((variant) => [variantKey(variant), variant]));
403
515
  const verified = [];
404
516
  for (const expectedVariant of expected) {
405
517
  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 });
518
+ const verifiedVariant = await verifyVariant(outputDir, variant, expectedVariant, verification);
519
+ if (!verifiedVariant) return undefined;
520
+ verified.push(verifiedVariant);
409
521
  }
410
522
  return verified;
411
523
  }
@@ -414,7 +526,7 @@ function carryForwardVariantDigests(expected, previous) {
414
526
  const previousByKey = new Map();
415
527
  if (Array.isArray(previous)) {
416
528
  for (const variant of previous) {
417
- if (variant && /^[a-f0-9]{64}$/.test(variant.digest ?? "")) {
529
+ if (hasValidVariantIdentity(variant)) {
418
530
  previousByKey.set(variantKey(variant), variant);
419
531
  }
420
532
  }
@@ -423,7 +535,14 @@ function carryForwardVariantDigests(expected, previous) {
423
535
  return expected.map((variant) => {
424
536
  const previousVariant = previousByKey.get(variantKey(variant));
425
537
  if (previousVariant?.file === variant.file && heightMatchesExpected(variant.height, previousVariant.height)) {
426
- return { ...variant, height: previousVariant.height, digest: previousVariant.digest };
538
+ return {
539
+ ...variant,
540
+ height: previousVariant.height,
541
+ digest: previousVariant.digest,
542
+ ...(Number.isSafeInteger(previousVariant.size) && typeof previousVariant.mtimeNs === "string"
543
+ ? { size: previousVariant.size, mtimeNs: previousVariant.mtimeNs }
544
+ : {}),
545
+ };
427
546
  }
428
547
  return variant;
429
548
  });
@@ -459,7 +578,14 @@ async function ensureVariantDirectory(outputDir, file) {
459
578
  async function writeVariant(buffer, filePath, variant, options, expectedHeight) {
460
579
  if (variant.format === "svg") {
461
580
  await atomicWrite(filePath, buffer);
462
- return { digest: digest(buffer), width: variant.width, height: expectedHeight };
581
+ const fileInfo = await lstat(filePath, { bigint: true });
582
+ return {
583
+ digest: digest(buffer),
584
+ width: variant.width,
585
+ height: expectedHeight,
586
+ size: Number(fileInfo.size),
587
+ mtimeNs: fileInfo.mtimeNs.toString(),
588
+ };
463
589
  }
464
590
  const image = sharp(buffer, { failOn: "none" });
465
591
  if (options.autoRotate) image.rotate();
@@ -471,7 +597,14 @@ async function writeVariant(buffer, filePath, variant, options, expectedHeight)
471
597
 
472
598
  const { data, info } = await image.toBuffer({ resolveWithObject: true });
473
599
  await atomicWrite(filePath, data);
474
- return { digest: digest(data), width: info.width, height: info.height };
600
+ const fileInfo = await lstat(filePath, { bigint: true });
601
+ return {
602
+ digest: digest(data),
603
+ width: info.width,
604
+ height: info.height,
605
+ size: Number(fileInfo.size),
606
+ mtimeNs: fileInfo.mtimeNs.toString(),
607
+ };
475
608
  }
476
609
 
477
610
  async function mapConcurrent(items, concurrency, callback) {
@@ -491,41 +624,10 @@ async function mapConcurrent(items, concurrency, callback) {
491
624
 
492
625
  async function processImagesFromFiles(rawOptions, requestedFiles) {
493
626
  const options = resolveOptions(rawOptions);
494
- const { rootDir, sourceDirectories, publicDir, concurrency, autoRotate } = options;
627
+ const { rootDir, sourceDirectories, concurrency, autoRotate, verification } = options;
495
628
  let { outputDir, cacheDir } = options;
496
629
  const reportedManifestPath = path.join(cacheDir, "manifest.json");
497
- const canonicalRoot = await canonicalizePath(rootDir);
498
- const canonicalSources = [];
499
- for (const sourceDirectory of sourceDirectories) {
500
- const relative = path.relative(rootDir, sourceDirectory);
501
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
502
- throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
503
- }
504
- const canonicalSource = await canonicalizePath(sourceDirectory);
505
- if (!isInside(canonicalRoot, canonicalSource)) {
506
- throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
507
- }
508
- canonicalSources.push(canonicalSource);
509
- }
510
-
511
- const canonicalOutputDir = await canonicalizePath(outputDir);
512
- const canonicalCacheDir = await canonicalizePath(cacheDir);
513
- const canonicalPublicDir = await canonicalizePath(publicDir);
514
- if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
515
- throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
516
- }
517
- for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
518
- if (isInside(canonicalPublicDir, directory)) {
519
- throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
520
- }
521
- }
522
- for (const canonicalSource of canonicalSources) {
523
- for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
524
- if (pathsOverlap(canonicalSource, directory)) {
525
- throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
526
- }
527
- }
528
- }
630
+ const { canonicalRoot, canonicalSources } = await resolveCanonicalDirectories(options);
529
631
 
530
632
  await mkdir(outputDir, { recursive: true });
531
633
  await mkdir(cacheDir, { recursive: true });
@@ -592,15 +694,36 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
592
694
 
593
695
  const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
594
696
  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
697
  const cacheEntry = oldCache.sources?.[relativePath];
599
698
  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]));
699
+ let sourceInfo = await sourceFileStat(sourcePath);
700
+ const canTrustSourceStat = verification === "stat"
701
+ && sourceInfo
702
+ && cacheEntry?.sourceSize === sourceInfo.size
703
+ && cacheEntry?.sourceMtimeNs === sourceInfo.mtimeNs
704
+ && cacheEntry?.autoRotate === autoRotate
705
+ && previousEntry
706
+ && typeof previousEntry.sourceHash === "string"
707
+ && Number.isSafeInteger(previousEntry.width) && previousEntry.width > 0
708
+ && Number.isSafeInteger(previousEntry.height) && previousEntry.height > 0
709
+ && typeof previousEntry.sourceFormat === "string";
710
+
711
+ let sourceBuffer;
712
+ let sourceHash;
713
+ let dimensions;
714
+ if (canTrustSourceStat) {
715
+ sourceHash = previousEntry.sourceHash;
716
+ dimensions = { width: previousEntry.width, height: previousEntry.height, format: previousEntry.sourceFormat };
717
+ } else {
718
+ sourceBuffer = await readFile(sourcePath);
719
+ sourceHash = digest(sourceBuffer);
720
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
721
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
722
+ }
723
+
724
+ let fingerprint = digest(`${sourceHash}\0${pipeline}`);
725
+ let expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
726
+ let expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
604
727
 
605
728
  const canReuse = cacheEntry?.fingerprint === fingerprint
606
729
  && previousEntry?.fingerprint === fingerprint
@@ -608,9 +731,24 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
608
731
  && previousEntry.width === dimensions.width
609
732
  && previousEntry.height === dimensions.height
610
733
  && previousEntry.sourceFormat === dimensions.format;
611
- const verifiedVariants = canReuse
612
- ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected)
734
+ let verifiedVariants = canReuse
735
+ ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected, verification)
613
736
  : undefined;
737
+
738
+ if (verifiedVariants === undefined && sourceBuffer === undefined) {
739
+ sourceBuffer = await readFile(sourcePath);
740
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
741
+ const actualHash = digest(sourceBuffer);
742
+ if (actualHash !== sourceHash) {
743
+ sourceHash = actualHash;
744
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
745
+ fingerprint = digest(`${sourceHash}\0${pipeline}`);
746
+ expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
747
+ expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
748
+ verifiedVariants = undefined;
749
+ }
750
+ }
751
+
614
752
  const isWarm = verifiedVariants !== undefined;
615
753
  let variants;
616
754
  if (isWarm) {
@@ -620,9 +758,9 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
620
758
  variants = carryForwardVariantDigests(expected, previousEntry?.variants);
621
759
  const missingVariants = [];
622
760
  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;
761
+ const verified = await verifyVariant(outputDir, variant, expectedByKey.get(variantKey(variant)), "digest");
762
+ if (!verified) missingVariants.push(variant);
763
+ else Object.assign(variant, verified);
626
764
  }
627
765
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
628
766
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
@@ -631,14 +769,14 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
631
769
  if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
632
770
  throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
633
771
  }
634
- variant.height = output.height;
635
- variant.digest = output.digest;
772
+ Object.assign(variant, output);
636
773
  });
637
774
  processed++;
638
775
  }
639
776
 
640
777
  return {
641
778
  relativePath,
779
+ sourceInfo,
642
780
  entry: {
643
781
  source: relativePath,
644
782
  fingerprint,
@@ -651,9 +789,13 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
651
789
  };
652
790
  });
653
791
 
654
- for (const { relativePath, entry } of results) {
792
+ for (const { relativePath, entry, sourceInfo } of results) {
655
793
  manifest.images[relativePath] = entry;
656
- cache.sources[relativePath] = { fingerprint: entry.fingerprint };
794
+ cache.sources[relativePath] = {
795
+ fingerprint: entry.fingerprint,
796
+ ...(sourceInfo ? { sourceSize: sourceInfo.size, sourceMtimeNs: sourceInfo.mtimeNs } : {}),
797
+ autoRotate,
798
+ };
657
799
  }
658
800
 
659
801
  const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
@@ -681,26 +823,14 @@ export async function adoptImageVariants(rawOptions, adoption) {
681
823
  throw new TypeError("adoptImageVariants requires a variants array");
682
824
  }
683
825
 
684
- const { rootDir, sourceDirectories, publicDir } = options;
826
+ const { rootDir, verification, autoRotate } = options;
685
827
  const sourcePath = path.resolve(rootDir, adoption.sourcePath);
686
828
  const relativePath = path.relative(rootDir, sourcePath);
687
829
  if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
688
830
  throw new Error(`Adopted source must remain inside rootDir: ${sourcePath}`);
689
831
  }
690
832
 
691
- const canonicalRoot = await realpath(rootDir);
692
- const canonicalSources = [];
693
- for (const sourceDirectory of sourceDirectories) {
694
- const relative = path.relative(rootDir, sourceDirectory);
695
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
696
- throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
697
- }
698
- const canonicalSource = await canonicalizePath(sourceDirectory);
699
- if (!isInside(canonicalRoot, canonicalSource)) {
700
- throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
701
- }
702
- canonicalSources.push(canonicalSource);
703
- }
833
+ const { canonicalRoot, canonicalSources } = await resolveCanonicalDirectories(options);
704
834
 
705
835
  const sourceInfo = await lstat(sourcePath);
706
836
  if (!sourceInfo.isFile() || sourceInfo.isSymbolicLink()) {
@@ -711,21 +841,6 @@ export async function adoptImageVariants(rawOptions, adoption) {
711
841
  throw new Error(`Adopted source must be inside one of the configured image source directories: ${sourcePath}`);
712
842
  }
713
843
 
714
- const canonicalOutputDir = await canonicalizePath(options.outputDir);
715
- const canonicalCacheDir = await canonicalizePath(options.cacheDir);
716
- const canonicalPublicDir = await canonicalizePath(publicDir);
717
- if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
718
- throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
719
- }
720
- for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
721
- if (isInside(canonicalPublicDir, directory)) {
722
- throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
723
- }
724
- if (canonicalSources.some((sourceDirectory) => pathsOverlap(sourceDirectory, directory))) {
725
- throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
726
- }
727
- }
728
-
729
844
  for (const [index, variant] of adoption.variants.entries()) {
730
845
  if (!variant || typeof variant.path !== "string") {
731
846
  throw new TypeError(`Adopted variant ${index} requires a path`);
@@ -744,29 +859,107 @@ export async function adoptImageVariants(rawOptions, adoption) {
744
859
  const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
745
860
  const createdPaths = [];
746
861
  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}`);
862
+ const manifestPath = path.join(cacheDir, "manifest.json");
863
+ const cachePath = path.join(cacheDir, "cache.json");
864
+ const [oldManifest, oldCache] = await Promise.all([
865
+ readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
866
+ readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
867
+ ]);
868
+ const manifest = {
869
+ version: MANIFEST_VERSION,
870
+ images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
871
+ };
872
+ const cache = {
873
+ version: CACHE_VERSION,
874
+ sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
875
+ };
876
+ const key = normalizeRelativePath(relativePath);
877
+ const previousEntry = manifest.images[key];
878
+ const cacheEntry = cache.sources[key];
879
+ let sourceInfo = await sourceFileStat(sourcePath);
880
+ const canTrustPrevious = verification === "stat"
881
+ && sourceInfo
882
+ && cacheEntry?.sourceSize === sourceInfo.size
883
+ && cacheEntry?.sourceMtimeNs === sourceInfo.mtimeNs
884
+ && cacheEntry?.autoRotate === autoRotate
885
+ && previousEntry
886
+ && previousEntry.sourceHash === adoption.sourceHash
887
+ && Number.isSafeInteger(previousEntry.width) && previousEntry.width > 0
888
+ && Number.isSafeInteger(previousEntry.height) && previousEntry.height > 0
889
+ && typeof previousEntry.sourceFormat === "string";
890
+
891
+ let sourceHash;
892
+ let dimensions;
893
+ if (canTrustPrevious) {
894
+ sourceHash = adoption.sourceHash;
895
+ dimensions = { width: previousEntry.width, height: previousEntry.height, format: previousEntry.sourceFormat };
896
+ } else {
897
+ const sourceBuffer = await readFile(sourcePath);
898
+ sourceHash = digest(sourceBuffer);
899
+ if (sourceHash !== adoption.sourceHash) {
900
+ throw new Error(`Adopted source changed: expected SHA-256 ${adoption.sourceHash}, received ${sourceHash} for ${sourcePath}`);
901
+ }
902
+ dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
903
+ sourceInfo = await sourceFileStat(sourcePath) ?? sourceInfo;
751
904
  }
752
905
 
753
- const dimensions = await imageMetadata(sourceBuffer, sourcePath, options.autoRotate);
754
- const sourceFormat = normalizeFormat(dimensions.format);
755
906
  const fingerprint = digest(`${sourceHash}\0${pipelineSettings(options)}`);
756
- const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
907
+ const expected = expectedVariants(fingerprint, dimensions, normalizeFormat(dimensions.format), options);
757
908
  const supplied = new Map();
758
909
  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);
910
+ const variantKeyValue = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
911
+ if (supplied.has(variantKeyValue)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
912
+ supplied.set(variantKeyValue, variant);
913
+ }
914
+ for (const expectedVariant of expected) {
915
+ if (!supplied.has(variantKey(expectedVariant))) {
916
+ throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
917
+ }
918
+ }
919
+
920
+ const persistState = async () => {
921
+ const manifestChanged = JSON.stringify(manifest.images[key]) !== JSON.stringify(oldManifest.images?.[key]);
922
+ const cacheChanged = JSON.stringify(cache.sources[key]) !== JSON.stringify(oldCache.sources?.[key]);
923
+ if (!manifestChanged && !cacheChanged) return;
924
+
925
+ const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
926
+ const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
927
+ let oldCacheText;
928
+ if (cacheChanged) {
929
+ oldCacheText = await readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error));
930
+ await atomicWrite(cachePath, cacheJson);
931
+ }
932
+ try {
933
+ if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
934
+ } catch (error) {
935
+ if (cacheChanged) {
936
+ if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
937
+ else await atomicWrite(cachePath, oldCacheText).catch(() => {});
938
+ }
939
+ throw error;
940
+ }
941
+ };
942
+
943
+ if (canTrustPrevious
944
+ && previousEntry.fingerprint === fingerprint
945
+ && cacheEntry?.fingerprint === fingerprint) {
946
+ const verifiedVariants = await verifiedOutputVariants(outputDir, previousEntry.variants, expected, verification);
947
+ if (verifiedVariants) {
948
+ manifest.images[key] = { ...previousEntry, variants: verifiedVariants };
949
+ cache.sources[key] = {
950
+ fingerprint,
951
+ sourceSize: sourceInfo.size,
952
+ sourceMtimeNs: sourceInfo.mtimeNs,
953
+ autoRotate,
954
+ };
955
+ await persistState();
956
+ return { fingerprint, adopted: expected.length, reused: expected.length, manifestPath };
957
+ }
762
958
  }
763
959
 
764
960
  const validated = [];
765
961
  for (const expectedVariant of expected) {
766
962
  const suppliedVariant = supplied.get(variantKey(expectedVariant));
767
- if (!suppliedVariant) {
768
- throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
769
- }
770
963
  const inputPath = path.resolve(rootDir, suppliedVariant.path);
771
964
  const inputInfo = await lstat(inputPath);
772
965
  if (!inputInfo.isFile() || inputInfo.isSymbolicLink()) {
@@ -795,15 +988,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
795
988
  });
796
989
  }
797
990
 
798
- const outputVariants = validated.map(({ buffer, ...variant }) => variant);
799
991
  const writeTargets = [];
800
992
  for (const variant of validated) {
801
993
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
802
994
  try {
803
995
  const info = await lstat(targetPath);
804
- if (!info.isFile() || info.isSymbolicLink() || !await variantMatches(outputDir, variant)) {
996
+ if (!info.isFile() || info.isSymbolicLink()) {
997
+ throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
998
+ }
999
+ const matched = await readMatchingVariant(outputDir, variant);
1000
+ if (!matched) {
805
1001
  throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
806
1002
  }
1003
+ variant.size = matched.size;
1004
+ variant.mtimeNs = matched.mtimeNs;
807
1005
  } catch (error) {
808
1006
  if (error.code !== "ENOENT") throw error;
809
1007
  writeTargets.push({ targetPath, variant });
@@ -811,32 +1009,20 @@ export async function adoptImageVariants(rawOptions, adoption) {
811
1009
  }
812
1010
 
813
1011
  for (const { targetPath, variant } of writeTargets) {
814
- const sourceVariant = validated.find((candidate) => candidate.file === variant.file);
815
- await atomicWrite(targetPath, sourceVariant.buffer);
1012
+ await atomicWrite(targetPath, variant.buffer);
1013
+ const fileInfo = await lstat(targetPath, { bigint: true });
1014
+ variant.size = Number(fileInfo.size);
1015
+ variant.mtimeNs = fileInfo.mtimeNs.toString();
816
1016
  createdPaths.push({ targetPath, variant });
817
1017
  }
818
1018
 
819
- if (digest(await readFile(sourcePath)) !== sourceHash) {
1019
+ if ((!canTrustPrevious || writeTargets.length > 0) && digest(await readFile(sourcePath)) !== sourceHash) {
820
1020
  throw new Error(`Adopted source changed during migration: ${sourcePath}`);
821
1021
  }
822
1022
 
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),
1023
+ const outputVariants = validated.map(({ buffer, ...variant }) => variant);
1024
+ manifest.images[key] = {
1025
+ source: key,
840
1026
  fingerprint,
841
1027
  sourceHash,
842
1028
  sourceFormat: dimensions.format,
@@ -844,22 +1030,12 @@ export async function adoptImageVariants(rawOptions, adoption) {
844
1030
  height: dimensions.height,
845
1031
  variants: outputVariants,
846
1032
  };
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
- }
1033
+ cache.sources[key] = {
1034
+ fingerprint,
1035
+ ...(sourceInfo ? { sourceSize: sourceInfo.size, sourceMtimeNs: sourceInfo.mtimeNs } : {}),
1036
+ autoRotate,
1037
+ };
1038
+ await persistState();
863
1039
 
864
1040
  return {
865
1041
  fingerprint,
@@ -890,5 +1066,204 @@ export async function processImages(rawOptions) {
890
1066
  return processImagesFromFiles(rawOptions, undefined);
891
1067
  }
892
1068
 
1069
+ async function readManifestForPrune(manifestPath) {
1070
+ let contents;
1071
+ try {
1072
+ contents = await readFile(manifestPath, "utf8");
1073
+ } catch (error) {
1074
+ if (error.code === "ENOENT") {
1075
+ throw new Error(`Refusing to prune image variants: no manifest at ${manifestPath}. Run processImages() first.`, { cause: error });
1076
+ }
1077
+ throw new Error(`Could not read JSON file ${manifestPath}: ${error.message}`, { cause: error });
1078
+ }
1079
+
1080
+ let manifest;
1081
+ try {
1082
+ manifest = JSON.parse(contents);
1083
+ } catch (error) {
1084
+ throw new Error(`Could not read JSON file ${manifestPath}: ${error.message}`, { cause: error });
1085
+ }
1086
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)
1087
+ || !manifest.images || typeof manifest.images !== "object" || Array.isArray(manifest.images)) {
1088
+ throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has no images object.`);
1089
+ }
1090
+ return manifest;
1091
+ }
1092
+
1093
+ function assertPruneDirectories(canonicalOutputDir, canonicalRoot, canonicalPublicDir) {
1094
+ if (isInside(canonicalOutputDir, canonicalRoot)) {
1095
+ throw new Error(`Refusing to prune image variants: outputDir must not equal or contain rootDir: ${canonicalOutputDir}`);
1096
+ }
1097
+ if (pathsOverlap(canonicalOutputDir, canonicalPublicDir)) {
1098
+ throw new Error(`Refusing to prune image variants: outputDir must not overlap Astro's public directory: ${canonicalOutputDir}`);
1099
+ }
1100
+ }
1101
+
1102
+ function referencedOutputFiles(manifest, outputDir, manifestPath) {
1103
+ const referenced = new Set();
1104
+ for (const [source, entry] of Object.entries(manifest.images)) {
1105
+ if (!entry || typeof entry !== "object" || !Array.isArray(entry.variants)) {
1106
+ throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has an unexpected entry for ${source}.`);
1107
+ }
1108
+ for (const variant of entry.variants) {
1109
+ if (!variant || typeof variant.file !== "string" || variant.file === "") {
1110
+ throw new Error(`Refusing to prune image variants: manifest ${manifestPath} has an invalid variant file for ${source}.`);
1111
+ }
1112
+ const filePath = path.resolve(outputDir, variant.file);
1113
+ if (!isInside(outputDir, filePath) || filePath === outputDir) {
1114
+ throw new Error(`Refusing to prune image variants: manifest ${manifestPath} references ${JSON.stringify(variant.file)} for ${source}, which is outside outputDir.`);
1115
+ }
1116
+ referenced.add(normalizeRelativePath(path.relative(outputDir, filePath)));
1117
+ }
1118
+ }
1119
+ return referenced;
1120
+ }
1121
+
1122
+ async function assertReferencedVariantsExist(outputDir, referenced, manifestPath) {
1123
+ for (const file of referenced) {
1124
+ if (!(await inspectVariantFile(outputDir, file))) {
1125
+ throw new Error(`Refusing to prune image variants: manifest ${manifestPath} references missing or unsafe file ${file}. Run processImages() first.`);
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ async function pruneOutputDirectory(outputDir, referenced, options) {
1131
+ const lockPath = path.join(outputDir, ".astro-image-cdn.lock");
1132
+ const legacyManifestPath = path.join(outputDir, "manifest.json");
1133
+ let removed = 0;
1134
+ let kept = 0;
1135
+ let bytesFreed = 0;
1136
+ const removableDirectories = [];
1137
+
1138
+ async function visit(directory) {
1139
+ let entries;
1140
+ try {
1141
+ if (directory !== outputDir) {
1142
+ // Defense in depth against a directory being replaced by a symlink: never descend through it.
1143
+ const info = await lstat(directory);
1144
+ if (!info.isDirectory() || info.isSymbolicLink()) return true;
1145
+ }
1146
+ entries = await readdir(directory, { withFileTypes: true });
1147
+ } catch (error) {
1148
+ if (error.code === "ENOENT") return false;
1149
+ throw error;
1150
+ }
1151
+
1152
+ let retained = 0;
1153
+ for (const entry of entries) {
1154
+ const entryPath = path.join(directory, entry.name);
1155
+ if (entryPath === lockPath) {
1156
+ // The writer lock is ours and still held; it is not part of the output inventory.
1157
+ retained++;
1158
+ continue;
1159
+ }
1160
+ if (entryPath === legacyManifestPath) {
1161
+ // Handled separately so it can be kept or explicitly removed, even when it is a symlink.
1162
+ if (!options.removeLegacyPublicManifest) kept++;
1163
+ retained++;
1164
+ continue;
1165
+ }
1166
+ if (entry.isDirectory()) {
1167
+ if (await visit(entryPath)) retained++;
1168
+ else removableDirectories.push(entryPath);
1169
+ continue;
1170
+ }
1171
+ // Symlinks and special files are never followed, unlinked, or counted as freed bytes.
1172
+ if (!entry.isFile()) {
1173
+ kept++;
1174
+ retained++;
1175
+ continue;
1176
+ }
1177
+
1178
+ const relative = normalizeRelativePath(path.relative(outputDir, entryPath));
1179
+ if (referenced.has(relative)) {
1180
+ kept++;
1181
+ retained++;
1182
+ continue;
1183
+ }
1184
+
1185
+ const info = await lstat(entryPath);
1186
+ if (!info.isFile() || info.isSymbolicLink()) {
1187
+ kept++;
1188
+ retained++;
1189
+ continue;
1190
+ }
1191
+ if (!options.dryRun) await unlink(entryPath);
1192
+ removed++;
1193
+ bytesFreed += info.size;
1194
+ }
1195
+ return retained > 0;
1196
+ }
1197
+
1198
+ await visit(outputDir);
1199
+
1200
+ let removedDirectories = 0;
1201
+ for (const directory of removableDirectories) {
1202
+ if (options.dryRun) {
1203
+ removedDirectories++;
1204
+ continue;
1205
+ }
1206
+ try {
1207
+ await rmdir(directory);
1208
+ removedDirectories++;
1209
+ } catch (error) {
1210
+ if (error.code !== "ENOENT" && error.code !== "ENOTEMPTY") throw error;
1211
+ }
1212
+ }
1213
+
1214
+ return { removed, kept, bytesFreed, removedDirectories };
1215
+ }
1216
+
1217
+ /**
1218
+ * Delete generated variants under outputDir that the private manifest no longer references.
1219
+ * Never follows symlinks, never touches sources, and runs under the writer lock.
1220
+ */
1221
+ export async function pruneImages(rawOptions) {
1222
+ const options = resolvePruneOptions(rawOptions);
1223
+ const manifestPath = path.join(options.cacheDir, "manifest.json");
1224
+ const { canonicalRoot, canonicalOutputDir, canonicalPublicDir } = await resolveCanonicalDirectories(options);
1225
+ assertPruneDirectories(canonicalOutputDir, canonicalRoot, canonicalPublicDir);
1226
+
1227
+ await mkdir(options.outputDir, { recursive: true });
1228
+ await mkdir(options.cacheDir, { recursive: true });
1229
+ const outputDir = await realpath(options.outputDir);
1230
+ const cacheDir = await realpath(options.cacheDir);
1231
+ const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
1232
+ try {
1233
+ const lockedManifestPath = path.join(cacheDir, "manifest.json");
1234
+ const manifest = await readManifestForPrune(lockedManifestPath);
1235
+ const referenced = referencedOutputFiles(manifest, outputDir, lockedManifestPath);
1236
+ await assertReferencedVariantsExist(outputDir, referenced, lockedManifestPath);
1237
+ const legacyPublicManifestPath = await detectLegacyPublicManifest(outputDir);
1238
+ const legacyInfo = legacyPublicManifestPath ? await lstat(legacyPublicManifestPath) : undefined;
1239
+ if (legacyInfo && options.removeLegacyPublicManifest && !legacyInfo.isFile() && !legacyInfo.isSymbolicLink()) {
1240
+ throw new Error(`Refusing to prune image variants: legacy manifest path ${legacyPublicManifestPath} is not a file.`);
1241
+ }
1242
+ const stats = await pruneOutputDirectory(outputDir, referenced, options);
1243
+
1244
+ let { removed, kept, bytesFreed } = stats;
1245
+ let legacyPublicManifestRemoved = false;
1246
+ if (legacyInfo && options.removeLegacyPublicManifest) {
1247
+ if (legacyInfo.isFile() && !legacyInfo.isSymbolicLink()) bytesFreed += legacyInfo.size;
1248
+ if (!options.dryRun) await unlink(legacyPublicManifestPath);
1249
+ removed++;
1250
+ legacyPublicManifestRemoved = true;
1251
+ }
1252
+
1253
+ return {
1254
+ removed,
1255
+ kept,
1256
+ bytesFreed,
1257
+ removedDirectories: stats.removedDirectories,
1258
+ dryRun: options.dryRun,
1259
+ manifestPath,
1260
+ legacyPublicManifestPath,
1261
+ legacyPublicManifestRemoved,
1262
+ };
1263
+ } finally {
1264
+ await releaseLocks();
1265
+ }
1266
+ }
1267
+
893
1268
  export const DEFAULT_IMAGE_WIDTHS = DEFAULT_WIDTHS;
894
1269
  export const DEFAULT_IMAGE_FORMATS = DEFAULT_FORMATS;