@all-the.rest/astro-image-cdn 0.1.1 → 0.2.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
@@ -65,13 +65,16 @@ With this option, `astro dev` installs the image service and local asset route,
65
65
  | `sources` | `["src"]` | Project-root-relative directories from which imported local images may be requested. No startup pre-scan is performed. |
66
66
  | `outputDir` | `".imagedist"` | Persistent generated variants, relative to the project root. |
67
67
  | `cacheDir` | `".astro-image-cdn"` | Private manifest and incremental fingerprints, relative to the project root. |
68
- | `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths; each source's native width is also generated. Values above the source width are omitted. |
68
+ | `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths. Values above the source width are omitted. |
69
69
  | `formats` | `["avif", "webp"]` | Output encodings generated for every selected width. Supported: `avif`, `webp`, `jpeg`, `png`. |
70
70
  | `quality` | `75` | Sharp encoder quality from 1 to 100. |
71
+ | `includeSourceFormat` | `true` | Also generate each supported source-native format. Set `false` for only the formats listed in `formats`. |
72
+ | `includeNativeWidth` | `true` | Also generate the source's native width when it is not already in `widths`. |
73
+ | `autoRotate` | `true` | Apply EXIF orientation before resizing. Set `false` to preserve the source's stored pixel orientation and dimensions. |
71
74
  | `concurrency` | `4` | Maximum number of source images processed at once. |
72
75
  | `devOnly` | `false` | Install the integration only for `astro dev`; other Astro commands retain their configured image service. |
73
76
 
74
- Configured formats are generated alongside the source's native raster format (when supported). Astro 7.4's default output for raster images is WebP, independent of the order in `formats`; include `webp` or request a configured format explicitly. If the default or an explicit format is unavailable, the service reports which format needs to be added. For a custom `widths` list, include the widths used by your native image components. For a requested width between generated sizes, the service selects the next available variant, capped at the source's native width.
77
+ Configured formats are generated alongside the source's native raster format when `includeSourceFormat` is enabled (the default). With it disabled, only `formats` are generated. Astro 7.4's default output for raster images is WebP, independent of the order in `formats`; include `webp` or request a configured format explicitly. If the default or an explicit format is unavailable, the service reports which format needs to be added. `widths` are emitted only when they are no wider than the source. The native width is additionally emitted only when `includeNativeWidth` is enabled; if it is already listed in `widths`, it is naturally generated once. For a requested width between generated sizes, the service selects the next available variant, capped at the source's native width.
75
78
 
76
79
  Animated or multi-page sources are rejected rather than silently flattened to a still frame, including GIF, WebP, AVIF sequences, and multi-page TIFF. Convert them to a static image or exclude them from the configured source directories.
77
80
 
@@ -91,6 +94,36 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
91
94
  - 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.
92
95
  - Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
93
96
 
97
+ ### Adopting existing variants
98
+
99
+ Migration scripts can use `adoptImageVariants()` to copy already-encoded files into the package's current fingerprint-based paths without running Sharp's encoders. Pass the current processor options and only technical source/output information; the helper does not read application metadata, YAML, or slugs:
100
+
101
+ ```js
102
+ import { createHash } from "node:crypto";
103
+ import { readFile } from "node:fs/promises";
104
+ import { adoptImageVariants } from "@all-the.rest/astro-image-cdn";
105
+
106
+ const sourcePath = "src/images/photo.jpg";
107
+ const sourceHash = createHash("sha256").update(await readFile(sourcePath)).digest("hex");
108
+ await adoptImageVariants({
109
+ rootDir: process.cwd(),
110
+ widths: [256, 640, 828, 1080, 1200, 1920, 2048],
111
+ formats: ["webp"],
112
+ includeSourceFormat: false,
113
+ includeNativeWidth: false,
114
+ autoRotate: false,
115
+ }, {
116
+ sourcePath,
117
+ sourceHash,
118
+ variants: [
119
+ { path: ".legacy-images/photo_256.webp", width: 256, format: "webp" },
120
+ { path: ".legacy-images/photo_640.webp", width: 640, format: "webp" },
121
+ ],
122
+ });
123
+ ```
124
+
125
+ The helper verifies the current source hash and each required output's actual format and dimensions before writing. It requires the complete variant set implied by the options; extras (such as legacy native-width files) are ignored. Outputs are atomically written under `outputDir`, and the private manifest/cache are updated only after validation. Repeated calls reuse matching targets; failures leave the prior manifest and existing outputs untouched, and old source variants are never removed. Supply the source hash recorded when the existing outputs were produced so a changed source cannot accidentally adopt stale files.
126
+
94
127
  ## API
95
128
 
96
129
  The default export is the Astro integration. Its image processor runs only when a native Astro image API requests an imported local image. The exported `processImages()` API is a separate, explicit bulk operation for standalone build scripts; calling it scans every supported image under `sources`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@all-the.rest/astro-image-cdn",
3
- "version": "0.1.1",
3
+ "version": "0.2.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
@@ -7,12 +7,18 @@ interface AstroImageCdnBaseOptions {
7
7
  outputDir?: string;
8
8
  /** Incremental state directory, relative to the project root. Defaults to ".astro-image-cdn". */
9
9
  cacheDir?: string;
10
- /** Widths generated in addition to each source image's native width. */
10
+ /** Configured widths; values above the source width are omitted. */
11
11
  widths?: number[];
12
12
  /** Output formats generated for every source. Defaults to ["avif", "webp"]. */
13
13
  formats?: Array<"avif" | "webp" | "jpeg" | "png">;
14
14
  /** Encoder quality from 1 to 100. Defaults to 75. */
15
15
  quality?: number;
16
+ /** Also generate a supported source-native format. Defaults to true. */
17
+ includeSourceFormat?: boolean;
18
+ /** Also generate the source's native width when it is not configured. Defaults to true. */
19
+ includeNativeWidth?: boolean;
20
+ /** Apply EXIF orientation before resizing. Defaults to true. */
21
+ autoRotate?: boolean;
16
22
  /** Maximum number of images processed concurrently. Defaults to 4. */
17
23
  concurrency?: number;
18
24
  }
@@ -47,6 +53,33 @@ export interface ProcessImagesResult {
47
53
  legacyPublicManifestPath?: string;
48
54
  }
49
55
 
56
+ export interface AdoptImageVariant {
57
+ /** Existing encoded output path; relative paths are resolved from rootDir. */
58
+ path: string;
59
+ width: number;
60
+ format: "avif" | "webp" | "jpeg" | "png" | "svg";
61
+ }
62
+
63
+ export interface AdoptImageVariantsInput {
64
+ /** Existing source path, relative to rootDir or absolute. */
65
+ sourcePath: string;
66
+ /** SHA-256 of the source bytes when the existing variants were produced. */
67
+ sourceHash: string;
68
+ /** Existing variants to adopt; every output required by the options must be supplied. */
69
+ variants: AdoptImageVariant[];
70
+ }
71
+
72
+ export interface AdoptImageVariantsResult {
73
+ fingerprint: string;
74
+ adopted: number;
75
+ reused: number;
76
+ manifestPath: string;
77
+ }
78
+
50
79
  export default function astroImageCdn(options: AstroImageCdnOptions): AstroIntegration;
51
80
 
52
81
  export declare function processImages(options: ProcessImagesOptions): Promise<ProcessImagesResult>;
82
+ export declare function adoptImageVariants(
83
+ options: ProcessImagesOptions,
84
+ input: AdoptImageVariantsInput,
85
+ ): Promise<AdoptImageVariantsResult>;
package/src/index.js CHANGED
@@ -111,6 +111,9 @@ export default function astroImageCdn(options) {
111
111
  widths: options.widths ?? DEFAULT_IMAGE_WIDTHS,
112
112
  formats: options.formats ?? DEFAULT_IMAGE_FORMATS,
113
113
  quality: options.quality ?? 75,
114
+ includeSourceFormat: options.includeSourceFormat ?? true,
115
+ includeNativeWidth: options.includeNativeWidth ?? true,
116
+ autoRotate: options.autoRotate ?? true,
114
117
  concurrency: options.concurrency ?? 4,
115
118
  dangerouslyProcessSVG: config.image?.dangerouslyProcessSVG ?? false,
116
119
  devMode,
@@ -150,4 +153,4 @@ export default function astroImageCdn(options) {
150
153
  };
151
154
  }
152
155
 
153
- export { processImages } from "./processor.js";
156
+ export { adoptImageVariants, processImages } from "./processor.js";
package/src/processor.js CHANGED
@@ -19,6 +19,12 @@ function normalizeFormat(format) {
19
19
  return format === "jpg" ? "jpeg" : format;
20
20
  }
21
21
 
22
+ function normalizeVariantFormat(metadata) {
23
+ return metadata.format === "heif" && metadata.mediaType === "image/avif"
24
+ ? "avif"
25
+ : normalizeFormat(metadata.format);
26
+ }
27
+
22
28
  function normalizeRelativePath(value) {
23
29
  return value.split(path.sep).join("/");
24
30
  }
@@ -104,6 +110,10 @@ function validatePositiveInteger(value, label) {
104
110
  }
105
111
  }
106
112
 
113
+ function heightMatchesExpected(expected, actual) {
114
+ return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
115
+ }
116
+
107
117
  function resolveOptions(options) {
108
118
  if (!options || typeof options.rootDir !== "string") {
109
119
  throw new TypeError("processImages requires an absolute rootDir");
@@ -119,6 +129,9 @@ function resolveOptions(options) {
119
129
  const quality = options.quality ?? 75;
120
130
  const concurrency = options.concurrency ?? 4;
121
131
  const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
132
+ const includeSourceFormat = options.includeSourceFormat ?? true;
133
+ const includeNativeWidth = options.includeNativeWidth ?? true;
134
+ const autoRotate = options.autoRotate ?? true;
122
135
 
123
136
  for (const width of widths) validatePositiveInteger(width, "widths");
124
137
  for (const format of formats) {
@@ -131,10 +144,27 @@ function resolveOptions(options) {
131
144
  if (typeof dangerouslyProcessSVG !== "boolean") {
132
145
  throw new TypeError("dangerouslyProcessSVG must be a boolean");
133
146
  }
147
+ for (const [label, value] of Object.entries({ includeSourceFormat, includeNativeWidth, autoRotate })) {
148
+ if (typeof value !== "boolean") throw new TypeError(`${label} must be a boolean`);
149
+ }
134
150
  if (quality > 100) throw new RangeError("quality must be between 1 and 100");
135
151
  if (formats.length === 0) throw new TypeError("formats must contain at least one image format");
136
152
 
137
- return { rootDir, sourceDirectories, publicDir, outputDir, cacheDir, widths, formats, quality, concurrency, dangerouslyProcessSVG };
153
+ return {
154
+ rootDir,
155
+ sourceDirectories,
156
+ publicDir,
157
+ outputDir,
158
+ cacheDir,
159
+ widths,
160
+ formats,
161
+ quality,
162
+ concurrency,
163
+ dangerouslyProcessSVG,
164
+ includeSourceFormat,
165
+ includeNativeWidth,
166
+ autoRotate,
167
+ };
138
168
  }
139
169
 
140
170
  async function walk(directory, output, excludedPaths) {
@@ -215,7 +245,7 @@ function hasAvifSequenceBrand(buffer) {
215
245
  return false;
216
246
  }
217
247
 
218
- async function imageMetadata(buffer, filePath) {
248
+ async function imageMetadata(buffer, filePath, autoRotate = true) {
219
249
  if (hasAvifSequenceBrand(buffer)) {
220
250
  throw new Error(`Animated or multi-page image sources are not supported: ${filePath} is an AVIF image sequence.`);
221
251
  }
@@ -233,7 +263,7 @@ async function imageMetadata(buffer, filePath) {
233
263
  if ((metadata.pages ?? 1) > 1) {
234
264
  throw new Error(`Animated or multi-page image sources are not supported: ${filePath} (${metadata.mediaType ?? metadata.format}, ${metadata.pages} pages).`);
235
265
  }
236
- const rotated = metadata.orientation >= 5 && metadata.orientation <= 8;
266
+ const rotated = autoRotate && metadata.orientation >= 5 && metadata.orientation <= 8;
237
267
  return {
238
268
  width: rotated ? metadata.height : metadata.width,
239
269
  height: rotated ? metadata.width : metadata.height,
@@ -245,10 +275,46 @@ function getVariants(width, formats) {
245
275
  return formats.map((format) => ({ width, format }));
246
276
  }
247
277
 
248
- async function variantMatches(outputDir, variant) {
249
- if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
278
+ function pipelineSettings(options) {
279
+ return JSON.stringify({
280
+ widths: options.widths,
281
+ formats: options.formats,
282
+ quality: options.quality,
283
+ transformVersion: TRANSFORM_VERSION,
284
+ sharpVersion: sharp.versions.sharp,
285
+ libvipsVersion: sharp.versions.vips,
286
+ dangerouslyProcessSVG: options.dangerouslyProcessSVG,
287
+ includeSourceFormat: options.includeSourceFormat,
288
+ includeNativeWidth: options.includeNativeWidth,
289
+ autoRotate: options.autoRotate,
290
+ });
291
+ }
292
+
293
+ function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
294
+ const targetWidths = options.widths.filter((width) => width <= dimensions.width);
295
+ if (options.includeNativeWidth || (sourceFormat === "svg" && (!options.dangerouslyProcessSVG || options.includeSourceFormat))) {
296
+ targetWidths.push(dimensions.width);
297
+ }
298
+ const uniqueWidths = [...new Set(targetWidths)].sort((a, b) => a - b);
299
+ const generatedFormats = sourceFormat === "svg" && !options.dangerouslyProcessSVG
300
+ ? ["svg"]
301
+ : options.includeSourceFormat && SUPPORTED_FORMATS.has(sourceFormat)
302
+ ? [...new Set([...options.formats, sourceFormat])]
303
+ : options.formats;
304
+
305
+ return uniqueWidths.flatMap((width) => getVariants(width, generatedFormats)
306
+ .filter((variant) => variant.format !== "svg" || width === dimensions.width)
307
+ .map((variant) => ({
308
+ ...variant,
309
+ height: Math.max(1, Math.round(width * dimensions.height / dimensions.width)),
310
+ file: `${fingerprint.slice(0, 2)}/${fingerprint}_${width}.${variant.format}`,
311
+ })));
312
+ }
313
+
314
+ async function readMatchingVariant(outputDir, variant) {
315
+ if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return undefined;
250
316
  const filePath = path.resolve(outputDir, variant.file);
251
- if (!isInside(outputDir, filePath) || filePath === outputDir) return false;
317
+ if (!isInside(outputDir, filePath) || filePath === outputDir) return undefined;
252
318
 
253
319
  try {
254
320
  const relative = path.relative(outputDir, filePath);
@@ -257,20 +323,35 @@ async function variantMatches(outputDir, variant) {
257
323
  for (const segment of segments.slice(0, -1)) {
258
324
  directory = path.join(directory, segment);
259
325
  const directoryInfo = await lstat(directory);
260
- if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return false;
326
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) return undefined;
261
327
  }
262
328
  const fileInfo = await lstat(filePath);
263
- if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return false;
264
- return digest(await readFile(filePath)) === variant.digest;
329
+ if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) return undefined;
330
+ const buffer = await readFile(filePath);
331
+ return digest(buffer) === variant.digest ? buffer : undefined;
265
332
  } catch (error) {
266
- if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
333
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
267
334
  throw error;
268
335
  }
269
336
  }
270
337
 
271
- async function outputExists(outputDir, variants) {
272
- const matches = await Promise.all(variants.map((variant) => variantMatches(outputDir, variant)));
273
- return matches.every(Boolean);
338
+ async function variantMatches(outputDir, variant) {
339
+ return (await readMatchingVariant(outputDir, variant)) !== undefined;
340
+ }
341
+
342
+ async function verifiedVariantHeight(outputDir, variant, expectedVariant) {
343
+ const buffer = await readMatchingVariant(outputDir, variant);
344
+ if (!buffer) return undefined;
345
+ let metadata;
346
+ try {
347
+ metadata = await sharp(buffer, { failOn: "none" }).metadata();
348
+ } catch {
349
+ return undefined;
350
+ }
351
+ if (normalizeVariantFormat(metadata) !== expectedVariant.format
352
+ || metadata.width !== expectedVariant.width
353
+ || !heightMatchesExpected(expectedVariant.height, metadata.height)) return undefined;
354
+ return metadata.height;
274
355
  }
275
356
 
276
357
  function variantKey(variant) {
@@ -288,10 +369,23 @@ function hasCompleteVariantSet(actual, expected) {
288
369
  }
289
370
  return expected.every((variant) => {
290
371
  const actualVariant = byKey.get(variantKey(variant));
291
- return actualVariant?.file === variant.file && actualVariant.height === variant.height;
372
+ return actualVariant?.file === variant.file && heightMatchesExpected(variant.height, actualVariant.height);
292
373
  });
293
374
  }
294
375
 
376
+ async function verifiedOutputVariants(outputDir, actual, expected) {
377
+ if (!hasCompleteVariantSet(actual, expected)) return undefined;
378
+ const actualByKey = new Map(actual.map((variant) => [variantKey(variant), variant]));
379
+ const verified = [];
380
+ for (const expectedVariant of expected) {
381
+ const variant = actualByKey.get(variantKey(expectedVariant));
382
+ const height = await verifiedVariantHeight(outputDir, variant, expectedVariant);
383
+ if (height === undefined) return undefined;
384
+ verified.push({ ...variant, height });
385
+ }
386
+ return verified;
387
+ }
388
+
295
389
  function carryForwardVariantDigests(expected, previous) {
296
390
  const previousByKey = new Map();
297
391
  if (Array.isArray(previous)) {
@@ -304,8 +398,8 @@ function carryForwardVariantDigests(expected, previous) {
304
398
 
305
399
  return expected.map((variant) => {
306
400
  const previousVariant = previousByKey.get(variantKey(variant));
307
- if (previousVariant?.file === variant.file && previousVariant.height === variant.height) {
308
- return { ...variant, digest: previousVariant.digest };
401
+ if (previousVariant?.file === variant.file && heightMatchesExpected(variant.height, previousVariant.height)) {
402
+ return { ...variant, height: previousVariant.height, digest: previousVariant.digest };
309
403
  }
310
404
  return variant;
311
405
  });
@@ -338,20 +432,22 @@ async function ensureVariantDirectory(outputDir, file) {
338
432
  return filePath;
339
433
  }
340
434
 
341
- async function writeVariant(buffer, filePath, width, format, quality) {
435
+ async function writeVariant(buffer, filePath, width, format, quality, autoRotate, expectedHeight) {
342
436
  if (format === "svg") {
343
437
  await atomicWrite(filePath, buffer);
344
- return digest(buffer);
438
+ return { digest: digest(buffer), width, height: expectedHeight };
345
439
  }
346
- const image = sharp(buffer, { failOn: "none" }).rotate().resize({ width, withoutEnlargement: true });
440
+ const image = sharp(buffer, { failOn: "none" });
441
+ if (autoRotate) image.rotate();
442
+ image.resize({ width, withoutEnlargement: true });
347
443
  if (format === "avif") image.avif({ quality });
348
444
  else if (format === "webp") image.webp({ quality });
349
445
  else if (format === "jpeg") image.jpeg({ quality });
350
446
  else image.png({ quality });
351
447
 
352
- const result = await image.toBuffer();
353
- await atomicWrite(filePath, result);
354
- return digest(result);
448
+ const { data, info } = await image.toBuffer({ resolveWithObject: true });
449
+ await atomicWrite(filePath, data);
450
+ return { digest: digest(data), width: info.width, height: info.height };
355
451
  }
356
452
 
357
453
  async function mapConcurrent(items, concurrency, callback) {
@@ -371,7 +467,7 @@ async function mapConcurrent(items, concurrency, callback) {
371
467
 
372
468
  async function processImagesFromFiles(rawOptions, requestedFiles) {
373
469
  const options = resolveOptions(rawOptions);
374
- const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG } = options;
470
+ const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG, autoRotate } = options;
375
471
  let { outputDir, cacheDir } = options;
376
472
  const reportedManifestPath = path.join(cacheDir, "manifest.json");
377
473
  const canonicalRoot = await canonicalizePath(rootDir);
@@ -468,15 +564,7 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
468
564
  let processed = 0;
469
565
  let skipped = 0;
470
566
 
471
- const pipeline = JSON.stringify({
472
- widths,
473
- formats,
474
- quality,
475
- transformVersion: TRANSFORM_VERSION,
476
- sharpVersion: sharp.versions.sharp,
477
- libvipsVersion: sharp.versions.vips,
478
- dangerouslyProcessSVG,
479
- });
567
+ const pipeline = pipelineSettings(options);
480
568
 
481
569
  const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
482
570
  const relativePath = normalizeRelativePath(path.relative(rootDir, sourcePath));
@@ -485,40 +573,42 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
485
573
  const fingerprint = digest(`${sourceHash}\0${pipeline}`);
486
574
  const cacheEntry = oldCache.sources?.[relativePath];
487
575
  const previousEntry = oldManifest.images?.[relativePath];
488
- const dimensions = await imageMetadata(sourceBuffer, sourcePath);
576
+ const dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
489
577
  const sourceFormat = normalizeFormat(dimensions.format);
490
- const targetWidths = [...new Set([...widths.filter((width) => width < dimensions.width), dimensions.width])].sort((a, b) => a - b);
491
- const generatedFormats = sourceFormat === "svg" && !dangerouslyProcessSVG
492
- ? ["svg"]
493
- : SUPPORTED_FORMATS.has(sourceFormat) ? [...new Set([...formats, sourceFormat])] : formats;
494
- const expectedVariants = targetWidths.flatMap((width) => getVariants(width, generatedFormats)
495
- .filter((variant) => variant.format !== "svg" || width === dimensions.width)
496
- .map((variant) => {
497
- const file = `${fingerprint.slice(0, 2)}/${fingerprint}_${width}.${variant.format}`;
498
- return { ...variant, height: Math.max(1, Math.round(width * dimensions.height / dimensions.width)), file };
499
- }));
500
-
501
- const isWarm = cacheEntry?.fingerprint === fingerprint
578
+ const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
579
+ const expectedByKey = new Map(expected.map((variant) => [variantKey(variant), variant]));
580
+
581
+ const canReuse = cacheEntry?.fingerprint === fingerprint
502
582
  && previousEntry?.fingerprint === fingerprint
503
583
  && previousEntry.sourceHash === sourceHash
504
584
  && previousEntry.width === dimensions.width
505
585
  && previousEntry.height === dimensions.height
506
- && previousEntry.sourceFormat === dimensions.format
507
- && hasCompleteVariantSet(previousEntry.variants, expectedVariants)
508
- && await outputExists(outputDir, previousEntry.variants);
586
+ && previousEntry.sourceFormat === dimensions.format;
587
+ const verifiedVariants = canReuse
588
+ ? await verifiedOutputVariants(outputDir, previousEntry.variants, expected)
589
+ : undefined;
590
+ const isWarm = verifiedVariants !== undefined;
509
591
  let variants;
510
592
  if (isWarm) {
511
- variants = previousEntry.variants;
593
+ variants = verifiedVariants;
512
594
  skipped++;
513
595
  } else {
514
- variants = carryForwardVariantDigests(expectedVariants, previousEntry?.variants);
596
+ variants = carryForwardVariantDigests(expected, previousEntry?.variants);
515
597
  const missingVariants = [];
516
598
  for (const variant of variants) {
517
- if (!await variantMatches(outputDir, variant)) missingVariants.push(variant);
599
+ const height = await verifiedVariantHeight(outputDir, variant, expectedByKey.get(variantKey(variant)));
600
+ if (height === undefined) missingVariants.push(variant);
601
+ else variant.height = height;
518
602
  }
519
603
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
520
604
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
521
- variant.digest = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality);
605
+ const expectedVariant = expectedByKey.get(variantKey(variant));
606
+ const output = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate, expectedVariant.height);
607
+ if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
608
+ throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
609
+ }
610
+ variant.height = output.height;
611
+ variant.digest = output.digest;
522
612
  });
523
613
  processed++;
524
614
  }
@@ -554,6 +644,215 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
554
644
  }
555
645
  }
556
646
 
647
+ /** Adopt existing image outputs into the current content-addressed layout without re-encoding. */
648
+ export async function adoptImageVariants(rawOptions, adoption) {
649
+ const options = resolveOptions(rawOptions);
650
+ if (!adoption || typeof adoption.sourcePath !== "string") {
651
+ throw new TypeError("adoptImageVariants requires a sourcePath");
652
+ }
653
+ if (!/^[a-f0-9]{64}$/.test(adoption.sourceHash ?? "")) {
654
+ throw new TypeError("adoptImageVariants requires a lowercase SHA-256 sourceHash");
655
+ }
656
+ if (!Array.isArray(adoption.variants)) {
657
+ throw new TypeError("adoptImageVariants requires a variants array");
658
+ }
659
+
660
+ const { rootDir, sourceDirectories, publicDir } = options;
661
+ const sourcePath = path.resolve(rootDir, adoption.sourcePath);
662
+ const relativePath = path.relative(rootDir, sourcePath);
663
+ if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
664
+ throw new Error(`Adopted source must remain inside rootDir: ${sourcePath}`);
665
+ }
666
+
667
+ const canonicalRoot = await realpath(rootDir);
668
+ const canonicalSources = [];
669
+ for (const sourceDirectory of sourceDirectories) {
670
+ const relative = path.relative(rootDir, sourceDirectory);
671
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
672
+ throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
673
+ }
674
+ const canonicalSource = await canonicalizePath(sourceDirectory);
675
+ if (!isInside(canonicalRoot, canonicalSource)) {
676
+ throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
677
+ }
678
+ canonicalSources.push(canonicalSource);
679
+ }
680
+
681
+ const sourceInfo = await lstat(sourcePath);
682
+ if (!sourceInfo.isFile() || sourceInfo.isSymbolicLink()) {
683
+ throw new Error(`Adopted source must be a regular file, not a symlink: ${sourcePath}`);
684
+ }
685
+ const canonicalSourcePath = await realpath(sourcePath);
686
+ if (!isInside(canonicalRoot, canonicalSourcePath) || !canonicalSources.some((directory) => isInside(directory, canonicalSourcePath))) {
687
+ throw new Error(`Adopted source must be inside one of the configured image source directories: ${sourcePath}`);
688
+ }
689
+
690
+ const canonicalOutputDir = await canonicalizePath(options.outputDir);
691
+ const canonicalCacheDir = await canonicalizePath(options.cacheDir);
692
+ const canonicalPublicDir = await canonicalizePath(publicDir);
693
+ if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
694
+ throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
695
+ }
696
+ for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
697
+ if (isInside(canonicalPublicDir, directory)) {
698
+ throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
699
+ }
700
+ if (canonicalSources.some((sourceDirectory) => pathsOverlap(sourceDirectory, directory))) {
701
+ throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
702
+ }
703
+ }
704
+
705
+ for (const [index, variant] of adoption.variants.entries()) {
706
+ if (!variant || typeof variant.path !== "string") {
707
+ throw new TypeError(`Adopted variant ${index} requires a path`);
708
+ }
709
+ validatePositiveInteger(variant.width, "variant width");
710
+ const format = normalizeFormat(variant.format);
711
+ if (!SUPPORTED_FORMATS.has(format)) {
712
+ throw new TypeError(`Unsupported adopted variant format "${variant.format}"`);
713
+ }
714
+ }
715
+
716
+ await mkdir(options.outputDir, { recursive: true });
717
+ await mkdir(options.cacheDir, { recursive: true });
718
+ const outputDir = await realpath(options.outputDir);
719
+ const cacheDir = await realpath(options.cacheDir);
720
+ const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
721
+ const createdPaths = [];
722
+ try {
723
+ const sourceBuffer = await readFile(sourcePath);
724
+ const sourceHash = digest(sourceBuffer);
725
+ if (sourceHash !== adoption.sourceHash) {
726
+ throw new Error(`Adopted source changed: expected SHA-256 ${adoption.sourceHash}, received ${sourceHash} for ${sourcePath}`);
727
+ }
728
+
729
+ const dimensions = await imageMetadata(sourceBuffer, sourcePath, options.autoRotate);
730
+ const sourceFormat = normalizeFormat(dimensions.format);
731
+ const fingerprint = digest(`${sourceHash}\0${pipelineSettings(options)}`);
732
+ const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
733
+ const supplied = new Map();
734
+ for (const variant of adoption.variants) {
735
+ const key = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
736
+ if (supplied.has(key)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
737
+ supplied.set(key, variant);
738
+ }
739
+
740
+ const validated = [];
741
+ for (const expectedVariant of expected) {
742
+ const suppliedVariant = supplied.get(variantKey(expectedVariant));
743
+ if (!suppliedVariant) {
744
+ throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
745
+ }
746
+ const inputPath = path.resolve(rootDir, suppliedVariant.path);
747
+ const inputInfo = await lstat(inputPath);
748
+ if (!inputInfo.isFile() || inputInfo.isSymbolicLink()) {
749
+ throw new Error(`Adopted variant must be a regular file, not a symlink: ${inputPath}`);
750
+ }
751
+ const buffer = await readFile(inputPath);
752
+ let metadata;
753
+ try {
754
+ metadata = await sharp(buffer, { failOn: "none" }).metadata();
755
+ } catch (error) {
756
+ throw new Error(`Unable to read adopted variant ${inputPath}: ${error.message}`, { cause: error });
757
+ }
758
+ const actualFormat = normalizeVariantFormat(metadata);
759
+ const expectedHeight = expectedVariant.height;
760
+ if (actualFormat !== expectedVariant.format || metadata.width !== expectedVariant.width || !heightMatchesExpected(expectedHeight, metadata.height)) {
761
+ throw new Error(
762
+ `Adopted variant ${inputPath} does not match expected ${expectedVariant.width}x${expectedHeight}±1 ${expectedVariant.format}; ` +
763
+ `received ${metadata.width}x${metadata.height} ${actualFormat}.`,
764
+ );
765
+ }
766
+ validated.push({
767
+ ...expectedVariant,
768
+ height: metadata.height,
769
+ digest: digest(buffer),
770
+ buffer,
771
+ });
772
+ }
773
+
774
+ const outputVariants = validated.map(({ buffer, ...variant }) => variant);
775
+ const writeTargets = [];
776
+ for (const variant of validated) {
777
+ const targetPath = await ensureVariantDirectory(outputDir, variant.file);
778
+ try {
779
+ const info = await lstat(targetPath);
780
+ if (!info.isFile() || info.isSymbolicLink() || !await variantMatches(outputDir, variant)) {
781
+ throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
782
+ }
783
+ } catch (error) {
784
+ if (error.code !== "ENOENT") throw error;
785
+ writeTargets.push({ targetPath, variant });
786
+ }
787
+ }
788
+
789
+ for (const { targetPath, variant } of writeTargets) {
790
+ const sourceVariant = validated.find((candidate) => candidate.file === variant.file);
791
+ await atomicWrite(targetPath, sourceVariant.buffer);
792
+ createdPaths.push({ targetPath, variant });
793
+ }
794
+
795
+ if (digest(await readFile(sourcePath)) !== sourceHash) {
796
+ throw new Error(`Adopted source changed during migration: ${sourcePath}`);
797
+ }
798
+
799
+ const manifestPath = path.join(cacheDir, "manifest.json");
800
+ const cachePath = path.join(cacheDir, "cache.json");
801
+ const [oldManifest, oldCache, oldCacheText] = await Promise.all([
802
+ readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
803
+ readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
804
+ readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error)),
805
+ ]);
806
+ const manifest = {
807
+ version: MANIFEST_VERSION,
808
+ images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
809
+ };
810
+ const cache = {
811
+ version: CACHE_VERSION,
812
+ sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
813
+ };
814
+ manifest.images[normalizeRelativePath(relativePath)] = {
815
+ source: normalizeRelativePath(relativePath),
816
+ fingerprint,
817
+ sourceHash,
818
+ sourceFormat: dimensions.format,
819
+ width: dimensions.width,
820
+ height: dimensions.height,
821
+ variants: outputVariants,
822
+ };
823
+ cache.sources[normalizeRelativePath(relativePath)] = { fingerprint };
824
+ const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
825
+ const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
826
+ const manifestChanged = manifestJson !== `${JSON.stringify(oldManifest, null, 2)}\n`;
827
+ const cacheChanged = cacheJson !== `${JSON.stringify(oldCache, null, 2)}\n`;
828
+
829
+ if (cacheChanged) await atomicWrite(cachePath, cacheJson);
830
+ try {
831
+ if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
832
+ } catch (error) {
833
+ if (cacheChanged) {
834
+ if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
835
+ else await atomicWrite(cachePath, oldCacheText).catch(() => {});
836
+ }
837
+ throw error;
838
+ }
839
+
840
+ return {
841
+ fingerprint,
842
+ adopted: outputVariants.length,
843
+ reused: outputVariants.length - writeTargets.length,
844
+ manifestPath,
845
+ };
846
+ } catch (error) {
847
+ for (const { targetPath, variant } of createdPaths.reverse()) {
848
+ if (await variantMatches(outputDir, variant).catch(() => false)) await unlink(targetPath).catch(() => {});
849
+ }
850
+ throw error;
851
+ } finally {
852
+ await releaseLocks();
853
+ }
854
+ }
855
+
557
856
  /** Generate variants for exactly the requested source files, preserving unrelated manifest/cache entries. */
558
857
  export async function processRequestedImages(rawOptions, requestedFiles) {
559
858
  if (!Array.isArray(requestedFiles)) {
package/src/service.js CHANGED
@@ -375,8 +375,11 @@ const service = {
375
375
  throw new Error(`astro-image-cdn has unsupported configured output format(s): ${invalidFormats.join(", ")}. Supported output formats are avif, webp, jpeg, or png.`);
376
376
  }
377
377
  const format = normalizeFormat(options.format ?? defaultOutputFormat(options));
378
- const isSourceFormat = sourceFormat === format && ["avif", "webp", "jpeg", "png", "svg"].includes(format);
379
- if (typeof options.src !== "string" && !configuredFormats.includes(format) && !isSourceFormat) {
378
+ const isSafeSvgPassThrough = sourceFormat === "svg" && format === "svg" && !config.dangerouslyProcessSVG;
379
+ const isSourceFormat = sourceFormat === format
380
+ && ["avif", "webp", "jpeg", "png", "svg"].includes(format)
381
+ && config.includeSourceFormat !== false;
382
+ if (typeof options.src !== "string" && !configuredFormats.includes(format) && !isSourceFormat && !isSafeSvgPassThrough) {
380
383
  if (format === "webp" && options.format == null) {
381
384
  throw new Error('Astro 7.4 defaults raster images to "webp", but "webp" is not configured. Add "webp" to astroImageCdn({ formats }) or set an explicit configured format on the image.');
382
385
  }