@jxsuite/compiler 8.7.0 → 9.1.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.
@@ -3,12 +3,16 @@
3
3
  *
4
4
  * Stores a manifest of previously processed images so that unchanged sources can skip re-encoding
5
5
  * on subsequent builds. Cache lives in the npm global cache directory under jxsuite-images/ so that
6
- * CI environments (e.g. Cloudflare Pages) can persist it via their npm cache layer.
6
+ * CI environments (e.g. Cloudflare Pages) can persist it via their npm cache layer. Each project
7
+ * has its own directory there, named for its directory and a digest of its absolute path: the name
8
+ * alone put two checkouts called `site` in one cache, where each one's pruning deleted the other's
9
+ * variants.
7
10
  */
8
11
 
9
12
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
13
  import { basename, extname, resolve } from "node:path";
11
14
  import { execSync } from "node:child_process";
15
+ import { createHash } from "node:crypto";
12
16
  import { tmpdir } from "node:os";
13
17
  import { configHash, contentHash } from "./image-optimizer.ts";
14
18
 
@@ -94,6 +98,11 @@ function npmCacheBase(): string | null {
94
98
  * Cloudflare Pages) automatically persist optimized images across builds. Falls back to
95
99
  * .cache/images inside the project root when npm is unavailable or does not answer in time.
96
100
  *
101
+ * Inside npm's cache the directory is `<project directory name>-<digest>`, the digest being 8 hex
102
+ * characters of the project root's absolute path, so two projects with one directory name never
103
+ * share a cache (site-architecture.md §9.2.5). A directory under the bare name, written by an older
104
+ * compiler, is left in place and never read: it may belong to a project still on that compiler.
105
+ *
97
106
  * Result is memoized — npm is asked at most once per process.
98
107
  *
99
108
  * @param {string} projectRoot
@@ -104,7 +113,9 @@ export function getImageCacheDir(projectRoot: string): string {
104
113
  _npmCacheBase = npmCacheBase();
105
114
  }
106
115
  if (_npmCacheBase) {
107
- return resolve(_npmCacheBase, "jxsuite-images", basename(projectRoot));
116
+ const root = resolve(projectRoot);
117
+ const digest = createHash("md5").update(root).digest("hex").slice(0, 8);
118
+ return resolve(_npmCacheBase, "jxsuite-images", `${basename(root)}-${digest}`);
108
119
  }
109
120
  return resolve(projectRoot, ".cache/images");
110
121
  }
@@ -214,7 +225,27 @@ function pruneStale(cache: CacheManifest, touched: Set<string>) {
214
225
  // ─── Entry access ─────────────────────────────────────────────────────────────
215
226
 
216
227
  /**
217
- * Check if a cache entry exists and its output files are still present.
228
+ * The variant files of every entry this build resolved, each once: what the build copies into
229
+ * `dist/images/_optimized/`. A key that was looked up and never stored (its image failed) names no
230
+ * entry and contributes nothing.
231
+ *
232
+ * @param {CacheManifest} cache
233
+ * @returns {string[]} Absolute paths
234
+ */
235
+ export function usedVariantPaths(cache: CacheManifest): string[] {
236
+ const paths = new Set<string>();
237
+ const entries = new Map<string, PersistedEntry>(Object.entries(cache.entries));
238
+ for (const key of cache.touched ?? []) {
239
+ for (const variant of entries.get(key)?.manifest.variants ?? []) {
240
+ paths.add(variant.absolutePath);
241
+ }
242
+ }
243
+ return [...paths];
244
+ }
245
+
246
+ /**
247
+ * Look an entry up, and mark its key as resolved by this build. Whether the entry's variant files
248
+ * are still on disk is the caller's check (`resolveManifest` in image-transform.ts).
218
249
  *
219
250
  * @param {CacheManifest} cache
220
251
  * @param {string} key
@@ -1,17 +1,22 @@
1
1
  /**
2
- * Image-optimizer.js — Sharp wrapper for image resizing and format conversion.
2
+ * Image-optimizer — responsive image variants, encoded by the compiler's Rust core.
3
3
  *
4
- * Generates responsive image variants (WebP, AVIF) at configured breakpoint widths. Returns an
5
- * ImageManifest describing all generated variants with their output paths.
4
+ * Generates the variants of one source image (AVIF, JPEG, PNG, lossless WebP) at the configured
5
+ * breakpoint widths, and returns an ImageManifest describing them. The pixels never enter
6
+ * JavaScript: `@jxsuite/compiler-binding` decodes, orients, converts to sRGB, resizes and encodes
7
+ * in process, in parallel across a source's variants (compiler.md §7.2).
6
8
  */
7
9
 
8
10
  import { createHash } from "node:crypto";
9
- import { errorMessage } from "@jxsuite/schema/parse";
10
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
11
+ import { readFileSync } from "node:fs";
11
12
  import { basename, extname, resolve } from "node:path";
12
- import { createRequire } from "node:module";
13
- // Sharp 0.35 only has a default export (function merged with a types namespace).
14
- import type SharpNS from "sharp";
13
+ import {
14
+ DEFAULT_IMAGE_QUALITY,
15
+ imageMetadata,
16
+ processImage as encodeVariants,
17
+ } from "@jxsuite/compiler-binding";
18
+
19
+ import type { ImageQuality } from "@jxsuite/compiler-binding";
15
20
 
16
21
  export interface ImageVariant {
17
22
  width: number; // Pixel width of the variant
@@ -23,15 +28,21 @@ export interface ImageVariant {
23
28
  export interface ImageManifest {
24
29
  variants: ImageVariant[]; // Array of generated responsive variants
25
30
  contentHash: string; // 8-char content hash for cache busting
26
- original?: { width: number; height: number }; // Original image dimensions
31
+ original?: { width: number; height: number; format?: string }; // Original image dimensions
27
32
  }
28
33
 
29
34
  export interface ImageConfig {
30
35
  optimize: boolean;
31
36
  widths: number[];
32
37
  formats: string[];
38
+ /**
39
+ * Lossy quality per format, 1 to 100. The build service reads `avif` and `jpeg`: PNG is lossless,
40
+ * and so is WebP as this compiler writes it. `webp` is still read by the Cloudflare service, as
41
+ * the quality of its transform URLs; `png` is accepted so existing projects still validate.
42
+ */
33
43
  quality: { webp?: number; avif?: number; jpeg?: number; png?: number };
34
- sizes: string;
44
+ /** The project-wide fallback `sizes`. A site build always has one; a direct caller may not. */
45
+ sizes?: string;
35
46
  lazyLoad: boolean;
36
47
  /**
37
48
  * Wrap a multi-format image in a `<picture>` with one `<source>` per format. Default true.
@@ -49,74 +60,19 @@ export interface ImageConfig {
49
60
  remoteDomains?: string[];
50
61
  }
51
62
 
52
- type SharpModule = typeof SharpNS;
53
- /**
54
- * Accepted output-format type, derived from the Sharp instance's own toFormat signature. Reaching
55
- * into the `SharpNS.FormatEnum` namespace instead is fragile: sharp ships as `export = sharp`, so
56
- * whether a default type-import exposes the merged namespace depends on esModuleInterop resolution
57
- * (differs local vs CI).
58
- */
59
- type SharpFormat = Parameters<ReturnType<SharpModule>["toFormat"]>[0];
60
-
61
- let _sharp: SharpModule | null = null;
62
-
63
- async function getSharp() {
64
- if (_sharp) {
65
- return _sharp;
66
- }
67
- // Primary: dynamic import — works in tests (mock.module intercepts it) and in
68
- // Production installs where @img/sharp-* native packages are adjacent to cli.js.
69
- try {
70
- const sharpMod = await import("sharp");
71
- _sharp = sharpMod.default;
72
- return _sharp;
73
- } catch {
74
- // Fall through to CJS fallback below.
75
- }
76
- // Fallback: resolve from the project being compiled. This covers symlinked
77
- // Monorepo dev environments (e.g. NixOS) where Node.js resolves import.meta.url
78
- // To the compiler package's real path, making the @img/sharp-* packages
79
- // Unreachable via the primary import path.
80
- try {
81
- const req = createRequire(resolve(process.cwd(), "package.json"));
82
- // SAFETY: sharp's CommonJS entry is `module.exports = sharp`, the value its ESM default exports.
83
- _sharp = req("sharp") as SharpModule;
84
- return _sharp;
85
- } catch (error) {
86
- throw new Error(
87
- `Sharp is required for image optimization but failed to load: ${errorMessage(error)}`,
88
- { cause: error },
89
- );
90
- }
91
- }
92
-
93
63
  const OPTIMIZED_DIR = "images/_optimized";
94
64
 
95
65
  /**
96
- * The part of sharp's metadata this module reads, with every member optional. The sharp these types
97
- * describe always reports all three, but `getSharp` may load the project's own copy instead, and
98
- * sharp before 0.34 declared each of them optional.
99
- */
100
- interface ReportedMetadata {
101
- format?: string;
102
- height?: number;
103
- width?: number;
104
- }
105
-
106
- /**
107
- * Get image metadata (dimensions and format) via Sharp.
66
+ * Get an image's dimensions and format, reading only its header.
67
+ *
68
+ * The dimensions are the ones a viewer sees: an EXIF orientation that turns the image on its side
69
+ * has already exchanged them.
108
70
  *
109
71
  * @param {string} srcPath - Absolute path to source image
110
72
  * @returns {Promise<{ width: number; height: number; format: string }>}
111
73
  */
112
74
  export async function getImageMetadata(srcPath: string) {
113
- const sharp = await getSharp();
114
- const meta: ReportedMetadata = await sharp(srcPath).metadata();
115
- return {
116
- format: meta.format ?? "unknown",
117
- height: meta.height ?? 0,
118
- width: meta.width ?? 0,
119
- };
75
+ return imageMetadata(srcPath);
120
76
  }
121
77
 
122
78
  /**
@@ -131,24 +87,71 @@ export function contentHash(srcPath: string) {
131
87
  }
132
88
 
133
89
  /**
134
- * Compute a config hash from the image optimization settings.
90
+ * Bumped whenever the pipeline produces different output for the same source and settings.
135
91
  *
136
- * @param {ImageConfig} config
137
- * @returns {string}
92
+ * It is part of two things. The cache key is settings plus source bytes, which answers "would this
93
+ * produce the same output?" only while the code between them is fixed; capping variants at the
94
+ * largest configured width changed the answer for every image already cached, and without a version
95
+ * those images kept their stale manifests. And a variant's file name carries it (`variantHash`),
96
+ * because `/images/_optimized/*` is served as immutable: the same name must always be the same
97
+ * bytes, and a new encoder writes different bytes for an unchanged source.
98
+ *
99
+ * 1 → 2: variants stop at the largest configured width (site-architecture.md §9.2.2).
100
+ *
101
+ * 2 → 3: the Rust core encodes. EXIF orientation is applied, embedded colour profiles are converted
102
+ * to sRGB, WebP is lossless, and a transparent source asked for as JPEG is PNG.
103
+ *
104
+ * 3 → 4: a variant's filename digest covers its format and that format's quality
105
+ * (site-architecture.md §9.2.5).
138
106
  */
107
+ const PIPELINE_VERSION = 4;
108
+
109
+ /** The quality recorded for a format the encoder writes losslessly and the project gave none. */
110
+ const LOSSLESS_QUALITY = 100;
111
+
112
+ /**
113
+ * The quality one format is encoded at: the project's, else the encoder's default for it.
114
+ *
115
+ * @param {ImageConfig["quality"]} quality
116
+ * @param {string} format
117
+ * @returns {number}
118
+ */
119
+ export function qualityFor(quality: ImageConfig["quality"], format: string): number {
120
+ const configured = new Map<string, number | undefined>(Object.entries(quality)).get(format);
121
+ if (configured !== undefined) {
122
+ return configured;
123
+ }
124
+ const defaults = new Map<string, number>(Object.entries(DEFAULT_IMAGE_QUALITY));
125
+ return defaults.get(format) ?? LOSSLESS_QUALITY;
126
+ }
127
+
139
128
  /**
140
- * Bumped whenever the pipeline decides variants differently for the same settings.
129
+ * The hash in a variant's file name: the source's bytes, the pipeline that encoded them, and the
130
+ * format and quality they were encoded at.
141
131
  *
142
- * The cache key is settings plus source bytes, which answers "would this produce the same output?"
143
- * only while the code between them is fixed. It is not: capping variants at the largest configured
144
- * width changed the answer for every image already cached, and without a version here those images
145
- * keep their stale manifests — including the oversized variants the change exists to stop
146
- * emitting.
132
+ * The settings are in it because the encoder keeps a variant whose file already exists, and
133
+ * `/images/_optimized/*` is served as immutable. Named from the source alone, a changed quality
134
+ * found the old files under the same names and kept them, and a host with a cold cache shipped new
135
+ * bytes at a URL returning visitors held for a year.
147
136
  *
148
- * 1 → 2: variants stop at the largest configured width (compiler.md §7.2).
137
+ * @param {string} srcPath - Absolute path to source image
138
+ * @param {string} format - The format the variant was asked for in
139
+ * @param {number} quality - The quality that format is encoded at
140
+ * @returns {string} 8-character hex hash
149
141
  */
150
- const PIPELINE_VERSION = 2;
142
+ export function variantHash(srcPath: string, format: string, quality: number) {
143
+ return createHash("md5")
144
+ .update(`${contentHash(srcPath)}:${PIPELINE_VERSION}:${format}:${quality}`)
145
+ .digest("hex")
146
+ .slice(0, 8);
147
+ }
151
148
 
149
+ /**
150
+ * Compute a config hash from the image optimization settings.
151
+ *
152
+ * @param {ImageConfig} config
153
+ * @returns {string}
154
+ */
152
155
  export function configHash(config: ImageConfig) {
153
156
  const key = JSON.stringify({
154
157
  formats: config.formats,
@@ -159,98 +162,56 @@ export function configHash(config: ImageConfig) {
159
162
  return createHash("md5").update(key).digest("hex").slice(0, 8);
160
163
  }
161
164
 
162
- /**
163
- * Build the output filename for a variant.
164
- *
165
- * @param {string} stem - Original filename without extension
166
- * @param {number} width
167
- * @param {string} hash8 - 8-char content hash
168
- * @param {string} format - "webp", "avif", "jpeg", "png"
169
- * @returns {string}
170
- */
171
- export function variantFilename(stem: string, width: number, hash8: string, format: string) {
172
- return `${stem}-${width}-${hash8}.${format}`;
173
- }
174
-
175
165
  /**
176
166
  * Process a single source image: resize to each configured width, encode to each format. Writes
177
- * variants to cacheImgDir/_optimized/ (e.g. .cache/images/_optimized/).
167
+ * variants to cacheImgDir/_optimized/, the image cache (`getImageCacheDir`).
168
+ *
169
+ * The width ladder is the configured one capped at the source's own width, plus the source's native
170
+ * width when it is narrower than the top rung; a source wider than the top rung stops there. A
171
+ * variant whose file already exists is not encoded again, because its name carries a hash of the
172
+ * source's bytes, the pipeline version, and its format and quality (`variantHash`).
178
173
  *
179
174
  * @param {string} srcPath - Absolute path to source image
180
- * @param {string} cacheImgDir - Absolute path to the image cache directory (.cache/images/)
175
+ * @param {string} cacheImgDir - Absolute path to the image cache directory
181
176
  * @param {ImageConfig} config
182
177
  * @returns {Promise<ImageManifest>}
183
178
  */
184
- export async function processImage(srcPath: string, cacheImgDir: string, config: ImageConfig) {
185
- const sharp = await getSharp();
186
- const meta = await getImageMetadata(srcPath);
187
- const hash8 = contentHash(srcPath);
188
- const stem = basename(srcPath, extname(srcPath));
189
-
179
+ export async function processImage(
180
+ srcPath: string,
181
+ cacheImgDir: string,
182
+ config: ImageConfig,
183
+ ): Promise<ImageManifest> {
190
184
  const optimizedDir = resolve(cacheImgDir, "_optimized");
191
- mkdirSync(optimizedDir, { recursive: true });
192
-
193
- const variants: ImageVariant[] = [];
194
-
195
- /*
196
- * The configured ladder, capped at the source's own width — upscaling only wastes bytes.
197
- *
198
- * A source SMALLER than every rung would otherwise produce no variants at all, and one that falls
199
- * between rungs would never be offered at its native resolution, so both get their own width
200
- * added. A source LARGER than the top rung does not: the largest configured width is the ceiling
201
- * the project chose, and honouring it is the point of configuring it.
202
- *
203
- * This used to add the native width unconditionally, so a 3840 px screenshot shipped a 3840 px
204
- * AVIF *and* WebP — encoded on every cold build, copied into dist, and offered as a `3840w`
205
- * candidate that no `sizes` on any real viewport would pick.
206
- */
207
- const ceiling = config.widths.length > 0 ? Math.max(...config.widths) : meta.width;
208
- const widths = config.widths.filter((w) => w <= meta.width);
209
- if (meta.width < ceiling && !widths.includes(meta.width)) {
210
- widths.push(meta.width);
211
- }
212
- if (widths.length === 0) {
213
- widths.push(meta.width);
214
- }
215
- widths.sort((a, b) => a - b);
216
-
217
- const tasks: Promise<void>[] = [];
218
-
219
- for (const width of widths) {
220
- for (const format of config.formats) {
221
- const filename = variantFilename(stem, width, hash8, format);
222
- const outputPath = `/${OPTIMIZED_DIR}/${filename}`;
223
- const absolutePath = resolve(optimizedDir, filename);
224
-
225
- variants.push({ absolutePath, format, outputPath, width });
226
-
227
- if (existsSync(absolutePath)) {
228
- continue;
229
- }
230
-
231
- /* SAFETY: `format` is a free string from project config; a name outside the four keyed
232
- qualities reads `undefined` from the lookup and takes the default of 80. */
233
- const quality = config.quality[format as keyof ImageConfig["quality"]] ?? 80;
234
- // SAFETY: toFormat checks the name itself and throws for a format sharp cannot encode.
235
- const task = sharp(srcPath)
236
- .resize(width)
237
- .toFormat(format as SharpFormat, { quality })
238
- .toFile(absolutePath)
239
- .then(() => {});
240
-
241
- tasks.push(task);
242
- }
185
+ const quality: ImageQuality = {};
186
+ if (config.quality.avif !== undefined) {
187
+ quality.avif = config.quality.avif;
243
188
  }
244
-
245
- const CONCURRENCY = 4;
246
- for (let i = 0; i < tasks.length; i += CONCURRENCY) {
247
- await Promise.all(tasks.slice(i, i + CONCURRENCY));
189
+ if (config.quality.jpeg !== undefined) {
190
+ quality.jpeg = config.quality.jpeg;
248
191
  }
249
-
192
+ const encoded = await encodeVariants({
193
+ formats: config.formats,
194
+ hashes: Object.fromEntries(
195
+ config.formats.map((format) => [
196
+ format,
197
+ variantHash(srcPath, format, qualityFor(config.quality, format)),
198
+ ]),
199
+ ),
200
+ outDir: optimizedDir,
201
+ quality,
202
+ source: srcPath,
203
+ stem: basename(srcPath, extname(srcPath)),
204
+ widths: config.widths,
205
+ });
250
206
  return {
251
- contentHash: hash8,
252
- original: { format: meta.format, height: meta.height, width: meta.width },
253
- variants,
207
+ contentHash: contentHash(srcPath),
208
+ original: encoded.original,
209
+ variants: encoded.variants.map((variant) => ({
210
+ absolutePath: resolve(optimizedDir, variant.fileName),
211
+ format: variant.format,
212
+ outputPath: `/${OPTIMIZED_DIR}/${variant.fileName}`,
213
+ width: variant.width,
214
+ })),
254
215
  };
255
216
  }
256
217