@all-the.rest/astro-image-cdn 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,12 +68,16 @@ With this option, `astro dev` installs the image service and local asset route,
68
68
  | `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths. Values above the source width are omitted. |
69
69
  | `formats` | `["avif", "webp"]` | Output encodings generated for every selected width. Supported: `avif`, `webp`, `jpeg`, `png`. |
70
70
  | `quality` | `75` | Sharp encoder quality from 1 to 100. |
71
+ | `webpEffort` | `4` | Build-wide Sharp WebP encoder effort, an integer from 0 (fastest) to 6 (slowest). |
72
+ | `avifEffort` | `4` | Build-wide Sharp AVIF encoder effort, an integer from 0 (fastest) to 9 (slowest). |
71
73
  | `includeSourceFormat` | `true` | Also generate each supported source-native format. Set `false` for only the formats listed in `formats`. |
72
74
  | `includeNativeWidth` | `true` | Also generate the source's native width when it is not already in `widths`. |
73
75
  | `autoRotate` | `true` | Apply EXIF orientation before resizing. Set `false` to preserve the source's stored pixel orientation and dimensions. |
74
76
  | `concurrency` | `4` | Maximum number of source images processed at once. |
75
77
  | `devOnly` | `false` | Install the integration only for `astro dev`; other Astro commands retain their configured image service. |
76
78
 
79
+ `webpEffort` and `avifEffort` are build-wide encoder settings available to both `astroImageCdn()` and the standalone `processImages()` API. They apply to every generated output of that format and are not per-image Astro request settings. The defaults match Sharp's defaults (4); omitting either option therefore preserves the existing encoder behavior. Invalid or out-of-range values are rejected before image processing or persistent output/cache changes.
80
+
77
81
  Configured formats are generated alongside the source's native raster format when `includeSourceFormat` is enabled (the default). With it disabled, only `formats` are generated. Astro 7.4's default output for raster images is WebP, independent of the order in `formats`; include `webp` or request a configured format explicitly. If the default or an explicit format is unavailable, the service reports which format needs to be added. `widths` are emitted only when they are no wider than the source. The native width is additionally emitted only when `includeNativeWidth` is enabled; if it is already listed in `widths`, it is naturally generated once. For a requested width between generated sizes, the service selects the next available variant, capped at the source's native width.
78
82
 
79
83
  Animated or multi-page sources are rejected rather than silently flattened to a still frame, including GIF, WebP, AVIF sequences, and multi-page TIFF. Convert them to a static image or exclude them from the configured source directories.
@@ -86,7 +90,7 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
86
90
 
87
91
  ## Persistence and cache behavior
88
92
 
89
- - Source bytes, encoder settings, the transform implementation version, and the Sharp/libvips versions are fingerprinted with SHA-256.
93
+ - `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.
90
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.
91
95
  - Each manifest is checked against the complete set of variants expected for its source and current options, so empty or partial entries trigger repair rather than a false cache hit.
92
96
  - 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@all-the.rest/astro-image-cdn",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Persistent, incremental image variants for Astro's native image components",
5
5
  "type": "module",
6
6
  "license": "ISC",
package/src/index.d.ts CHANGED
@@ -13,6 +13,10 @@ interface AstroImageCdnBaseOptions {
13
13
  formats?: Array<"avif" | "webp" | "jpeg" | "png">;
14
14
  /** Encoder quality from 1 to 100. Defaults to 75. */
15
15
  quality?: number;
16
+ /** WebP encoder effort, integer from 0 (fastest) to 6 (slowest). Defaults to Sharp's default, 4. */
17
+ webpEffort?: number;
18
+ /** AVIF encoder effort, integer from 0 (fastest) to 9 (slowest). Defaults to Sharp's default, 4. */
19
+ avifEffort?: number;
16
20
  /** Also generate a supported source-native format. Defaults to true. */
17
21
  includeSourceFormat?: boolean;
18
22
  /** Also generate the source's native width when it is not configured. Defaults to true. */
package/src/index.js CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { realpathSync } from "node:fs";
4
4
  import path from "node:path";
5
- import { DEFAULT_IMAGE_FORMATS, DEFAULT_IMAGE_WIDTHS } from "./processor.js";
5
+ import { DEFAULT_IMAGE_FORMATS, DEFAULT_IMAGE_WIDTHS, resolveEncoderEfforts } from "./processor.js";
6
6
  import { installDevAssetMiddleware } from "./dev-server.js";
7
7
 
8
8
  const serviceEntrypoint = fileURLToPath(new URL("./service.js", import.meta.url));
@@ -82,6 +82,7 @@ export default function astroImageCdn(options) {
82
82
  throw new TypeError("astroImageCdn requires a baseUrl unless devOnly is true");
83
83
  }
84
84
  const baseUrl = typeof options.baseUrl === "string" ? normalizeBaseUrl(options.baseUrl) : "";
85
+ const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
85
86
  let projectRoot;
86
87
  let outputDir;
87
88
  let cacheDir;
@@ -111,6 +112,8 @@ export default function astroImageCdn(options) {
111
112
  widths: options.widths ?? DEFAULT_IMAGE_WIDTHS,
112
113
  formats: options.formats ?? DEFAULT_IMAGE_FORMATS,
113
114
  quality: options.quality ?? 75,
115
+ webpEffort,
116
+ avifEffort,
114
117
  includeSourceFormat: options.includeSourceFormat ?? true,
115
118
  includeNativeWidth: options.includeNativeWidth ?? true,
116
119
  autoRotate: options.autoRotate ?? true,
package/src/processor.js CHANGED
@@ -8,6 +8,8 @@ const CACHE_VERSION = 1;
8
8
  const TRANSFORM_VERSION = 3;
9
9
  const DEFAULT_WIDTHS = [256, 640, 828, 1080, 1200, 1920, 2048];
10
10
  const DEFAULT_FORMATS = ["avif", "webp"];
11
+ const DEFAULT_WEBP_EFFORT = 4;
12
+ const DEFAULT_AVIF_EFFORT = 4;
11
13
  const SUPPORTED_FORMATS = new Set(["avif", "webp", "jpeg", "png", "svg"]);
12
14
  const IMAGE_EXTENSIONS = new Set([
13
15
  ".avif", ".gif", ".heic", ".heif", ".jpeg", ".jpg", ".png", ".svg", ".tif", ".tiff", ".webp",
@@ -110,6 +112,23 @@ function validatePositiveInteger(value, label) {
110
112
  }
111
113
  }
112
114
 
115
+ function validateEffort(value, label, maximum) {
116
+ if (!Number.isSafeInteger(value)) {
117
+ throw new TypeError(`${label} must be an integer between 0 and ${maximum}; received ${value}`);
118
+ }
119
+ if (value < 0 || value > maximum) {
120
+ throw new RangeError(`${label} must be between 0 and ${maximum}; received ${value}`);
121
+ }
122
+ }
123
+
124
+ export function resolveEncoderEfforts(options) {
125
+ const webpEffort = options.webpEffort === undefined ? DEFAULT_WEBP_EFFORT : options.webpEffort;
126
+ const avifEffort = options.avifEffort === undefined ? DEFAULT_AVIF_EFFORT : options.avifEffort;
127
+ validateEffort(webpEffort, "webpEffort", 6);
128
+ validateEffort(avifEffort, "avifEffort", 9);
129
+ return { webpEffort, avifEffort };
130
+ }
131
+
113
132
  function heightMatchesExpected(expected, actual) {
114
133
  return Number.isSafeInteger(actual) && Math.abs(actual - expected) <= 1;
115
134
  }
@@ -127,6 +146,7 @@ function resolveOptions(options) {
127
146
  const widths = [...new Set(options.widths ?? DEFAULT_WIDTHS)].sort((a, b) => a - b);
128
147
  const formats = [...new Set((options.formats ?? DEFAULT_FORMATS).map(normalizeFormat))];
129
148
  const quality = options.quality ?? 75;
149
+ const { webpEffort, avifEffort } = resolveEncoderEfforts(options);
130
150
  const concurrency = options.concurrency ?? 4;
131
151
  const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
132
152
  const includeSourceFormat = options.includeSourceFormat ?? true;
@@ -159,6 +179,8 @@ function resolveOptions(options) {
159
179
  widths,
160
180
  formats,
161
181
  quality,
182
+ webpEffort,
183
+ avifEffort,
162
184
  concurrency,
163
185
  dangerouslyProcessSVG,
164
186
  includeSourceFormat,
@@ -280,6 +302,8 @@ function pipelineSettings(options) {
280
302
  widths: options.widths,
281
303
  formats: options.formats,
282
304
  quality: options.quality,
305
+ webpEffort: options.webpEffort,
306
+ avifEffort: options.avifEffort,
283
307
  transformVersion: TRANSFORM_VERSION,
284
308
  sharpVersion: sharp.versions.sharp,
285
309
  libvipsVersion: sharp.versions.vips,
@@ -432,18 +456,18 @@ async function ensureVariantDirectory(outputDir, file) {
432
456
  return filePath;
433
457
  }
434
458
 
435
- async function writeVariant(buffer, filePath, width, format, quality, autoRotate, expectedHeight) {
436
- if (format === "svg") {
459
+ async function writeVariant(buffer, filePath, variant, options, expectedHeight) {
460
+ if (variant.format === "svg") {
437
461
  await atomicWrite(filePath, buffer);
438
- return { digest: digest(buffer), width, height: expectedHeight };
462
+ return { digest: digest(buffer), width: variant.width, height: expectedHeight };
439
463
  }
440
464
  const image = sharp(buffer, { failOn: "none" });
441
- if (autoRotate) image.rotate();
442
- image.resize({ width, withoutEnlargement: true });
443
- if (format === "avif") image.avif({ quality });
444
- else if (format === "webp") image.webp({ quality });
445
- else if (format === "jpeg") image.jpeg({ quality });
446
- else image.png({ quality });
465
+ if (options.autoRotate) image.rotate();
466
+ image.resize({ width: variant.width, withoutEnlargement: true });
467
+ if (variant.format === "avif") image.avif({ quality: options.quality, effort: options.avifEffort });
468
+ else if (variant.format === "webp") image.webp({ quality: options.quality, effort: options.webpEffort });
469
+ else if (variant.format === "jpeg") image.jpeg({ quality: options.quality });
470
+ else image.png({ quality: options.quality });
447
471
 
448
472
  const { data, info } = await image.toBuffer({ resolveWithObject: true });
449
473
  await atomicWrite(filePath, data);
@@ -467,7 +491,7 @@ async function mapConcurrent(items, concurrency, callback) {
467
491
 
468
492
  async function processImagesFromFiles(rawOptions, requestedFiles) {
469
493
  const options = resolveOptions(rawOptions);
470
- const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG, autoRotate } = options;
494
+ const { rootDir, sourceDirectories, publicDir, concurrency, autoRotate } = options;
471
495
  let { outputDir, cacheDir } = options;
472
496
  const reportedManifestPath = path.join(cacheDir, "manifest.json");
473
497
  const canonicalRoot = await canonicalizePath(rootDir);
@@ -603,7 +627,7 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
603
627
  await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
604
628
  const targetPath = await ensureVariantDirectory(outputDir, variant.file);
605
629
  const expectedVariant = expectedByKey.get(variantKey(variant));
606
- const output = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate, expectedVariant.height);
630
+ const output = await writeVariant(sourceBuffer, targetPath, variant, options, expectedVariant.height);
607
631
  if (output.width !== expectedVariant.width || !heightMatchesExpected(expectedVariant.height, output.height)) {
608
632
  throw new Error(`Generated ${variant.width}.${variant.format} has unexpected dimensions ${output.width}x${output.height}`);
609
633
  }
package/src/service.js CHANGED
@@ -176,6 +176,10 @@ function sourceCandidates(value, rootDir) {
176
176
  return [...candidates];
177
177
  }
178
178
 
179
+ function sourcePathWithoutQuery(value) {
180
+ return typeof value === "string" ? value.split(/[?#]/, 1)[0] : undefined;
181
+ }
182
+
179
183
  function isInside(parent, candidate) {
180
184
  const relative = path.relative(parent, candidate);
181
185
  return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
@@ -210,11 +214,10 @@ async function findFilesByName(directory, fileName, matches) {
210
214
  async function requestedSourcePath(source, config) {
211
215
  if (typeof source?.fsPath === "string") return path.resolve(source.fsPath);
212
216
 
213
- const sourceName = typeof source?.src === "string" ? source.src : undefined;
217
+ const sourceName = sourcePathWithoutQuery(source?.src);
214
218
  if (!sourceName) return undefined;
215
219
  const rootDir = path.resolve(config.rootDir);
216
- const sourceNameWithoutQuery = sourceName.split(/[?#]/, 1)[0];
217
- for (const candidate of sourceCandidates(sourceNameWithoutQuery, rootDir)) {
220
+ for (const candidate of sourceCandidates(sourceName, rootDir)) {
218
221
  const absoluteCandidate = path.resolve(rootDir, candidate);
219
222
  if (!isConfiguredSourcePath(absoluteCandidate, config)) continue;
220
223
  try {
@@ -226,7 +229,7 @@ async function requestedSourcePath(source, config) {
226
229
 
227
230
  // Astro's SVG component wrapper serializes image metadata without its private fsPath.
228
231
  // Resolve that requested import by its emitted basename, but reject ambiguous matches.
229
- const basename = path.posix.basename(sourceNameWithoutQuery)
232
+ const basename = path.posix.basename(sourceName)
230
233
  .replace(/\.[a-z0-9_-]{8,}(?=\.[^.]+$)/i, "");
231
234
  const matches = [];
232
235
  for (const directory of (config.sources ?? ["src"]).map((sourceDirectory) => path.resolve(rootDir, sourceDirectory))) {
@@ -271,12 +274,14 @@ function resolveImage(options, imageConfig) {
271
274
  const manifest = readManifest(imageConfig);
272
275
  const rootDir = path.resolve(imageConfig.service.config.rootDir);
273
276
  const source = options.src;
277
+ const sourceName = typeof source === "string" ? source : source?.src;
278
+ const sourcePath = sourcePathWithoutQuery(sourceName);
274
279
  const possibleSources = [];
275
280
  if (isImportedImage(source)) {
276
281
  if (typeof source.fsPath === "string") possibleSources.push(...sourceCandidates(source.fsPath, rootDir));
277
- possibleSources.push(...sourceCandidates(source.src, rootDir));
282
+ possibleSources.push(...sourceCandidates(sourcePath, rootDir));
278
283
  } else {
279
- possibleSources.push(...sourceCandidates(source, rootDir));
284
+ possibleSources.push(...sourceCandidates(sourcePath, rootDir));
280
285
  }
281
286
 
282
287
  for (const candidate of possibleSources) {
@@ -284,9 +289,8 @@ function resolveImage(options, imageConfig) {
284
289
  if (entry) return entry;
285
290
  }
286
291
 
287
- const sourceName = typeof source === "string" ? source : source?.src;
288
- if (typeof sourceName === "string") {
289
- const builtAssetName = path.basename(sourceName).replace(/\.[a-z0-9_-]{8,}(?=\.[^.]+$)/i, "");
292
+ if (typeof sourcePath === "string") {
293
+ const builtAssetName = path.basename(sourcePath).replace(/\.[a-z0-9_-]{8,}(?=\.[^.]+$)/i, "");
290
294
  const sameName = Object.values(manifest.images).filter((entry) => path.posix.basename(entry.source) === builtAssetName);
291
295
  const sameDimensions = sameName.filter((entry) => entry.width === source?.width && entry.height === source?.height);
292
296
  const candidates = sameDimensions.length > 0 ? sameDimensions : sameName;