@jxsuite/compiler 9.0.1 → 10.0.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.
@@ -6,7 +6,7 @@
6
6
  * discovered through their jx-extension.json manifests; see specs/extensions.md.
7
7
  */
8
8
 
9
- import { readFileSync } from "node:fs";
9
+ import { existsSync, readFileSync } from "node:fs";
10
10
  import { dirname, isAbsolute, resolve, sep } from "node:path";
11
11
  import { pathToFileURL } from "node:url";
12
12
  import { createRequire } from "node:module";
@@ -26,18 +26,14 @@ export type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
26
26
  export type { FormatRegistry, FormatEntry } from "@jxsuite/schema/format-registry";
27
27
 
28
28
  /**
29
- * Import a class $implementation module by absolute path, tolerating source-vs-built layouts. A
30
- * `.class.json` typically declares `"$implementation": "./markdown.js"` next to its TypeScript
31
- * source: under Bun the sibling `.ts` resolves directly, while under node the built module lives in
32
- * the package's `dist/` directory. Tries, in order: the literal path, src/ → dist/, that same file
33
- * with its `.ts` extension read as `.js` (a descriptor that names its TypeScript source, whose
34
- * built module is JavaScript), and .js → .ts.
29
+ * The files an `$implementation` path may mean, in the order they are tried: the literal path, its
30
+ * `src/` read as `dist/`, that built file with a `.ts` extension read as `.js`, and a `.js` read as
31
+ * the `.ts` beside it. See {@link importImplementation} for why each exists.
35
32
  *
36
33
  * @param {string} path - Absolute path to the implementation module
37
- * @returns {Promise<ImplementationExport>} The module's namespace object, whose named exports (and
38
- * `default`) are read by name
34
+ * @returns {string[]}
39
35
  */
40
- export async function importImplementation(path: string): Promise<ImplementationExport> {
36
+ export function implementationCandidates(path: string): string[] {
41
37
  const candidates = [path];
42
38
  const srcSeg = `${sep}src${sep}`;
43
39
  const distSeg = `${sep}dist${sep}`;
@@ -51,6 +47,49 @@ export async function importImplementation(path: string): Promise<Implementation
51
47
  if (path.endsWith(".js")) {
52
48
  candidates.push(`${path.slice(0, -3)}.ts`);
53
49
  }
50
+ return candidates;
51
+ }
52
+
53
+ /**
54
+ * The file an `$implementation` path names, for a bundler, which needs the file itself where
55
+ * {@link importImplementation} can simply try each import.
56
+ *
57
+ * The candidates are {@link implementationCandidates}', with the source beside the literal path
58
+ * ahead of a built copy: that is the file a Bun import of the literal path loads, so the class a
59
+ * build ran and the class it ships are one source, and a stale `dist/` beside a newer `src/` is not
60
+ * what reaches the browser. A published package has no `src/`, and its built module is found.
61
+ *
62
+ * @param {string} path - Absolute path to the implementation module
63
+ * @returns {string}
64
+ */
65
+ export function implementationFile(path: string): string {
66
+ const candidates = implementationCandidates(path);
67
+ const beside = dirname(path);
68
+ const ordered = [
69
+ ...candidates.filter((candidate) => dirname(candidate) === beside),
70
+ ...candidates.filter((candidate) => dirname(candidate) !== beside),
71
+ ];
72
+ const found = ordered.find((candidate) => existsSync(candidate));
73
+ if (found === undefined) {
74
+ throw new Error(`no module at ${path} (tried ${ordered.join(", ")})`);
75
+ }
76
+ return found;
77
+ }
78
+
79
+ /**
80
+ * Import a class $implementation module by absolute path, tolerating source-vs-built layouts. A
81
+ * `.class.json` typically declares `"$implementation": "./markdown.js"` next to its TypeScript
82
+ * source: under Bun the sibling `.ts` resolves directly, while under node the built module lives in
83
+ * the package's `dist/` directory. Tries, in order: the literal path, src/ → dist/, that same file
84
+ * with its `.ts` extension read as `.js` (a descriptor that names its TypeScript source, whose
85
+ * built module is JavaScript), and .js → .ts.
86
+ *
87
+ * @param {string} path - Absolute path to the implementation module
88
+ * @returns {Promise<ImplementationExport>} The module's namespace object, whose named exports (and
89
+ * `default`) are read by name
90
+ */
91
+ export async function importImplementation(path: string): Promise<ImplementationExport> {
92
+ const candidates = implementationCandidates(path);
54
93
 
55
94
  let lastError: unknown;
56
95
  for (const candidate of candidates) {
@@ -32,8 +32,8 @@ export interface HeaderRuleSet {
32
32
 
33
33
  /**
34
34
  * The only content-addressed output the build produces. A variant's file name embeds an 8-character
35
- * digest of the source bytes, so a changed image is a changed URL and the old one can be cached
36
- * forever (RFC 8246).
35
+ * digest of the source bytes and the settings they were encoded with, so a changed image or a
36
+ * changed quality is a changed URL and the old one can be cached forever (RFC 8246).
37
37
  */
38
38
  export const IMMUTABLE_PATTERN = "/images/_optimized/*";
39
39
 
@@ -241,9 +241,10 @@ export function writeHeaders(outDir: string, rules: readonly HeaderRule[]): numb
241
241
  /**
242
242
  * Write `dist/.nojekyll`.
243
243
  *
244
- * GitHub Pages runs Jekyll, which excludes every `_`-prefixed path — which is `_headers`,
245
- * `_redirects`, `_worker.js`, `_routes.json` and `_islands/`. One empty file closes the whole class
246
- * of "works locally, half-broken on Pages", so it is unconditional rather than an adapter option.
244
+ * GitHub Pages runs Jekyll, which leaves every `_`-prefixed path out of the published site, at any
245
+ * depth. The one the build writes that a page needs is `images/_optimized/`, and a project may ship
246
+ * its own from `public/`. One empty file closes the whole class of "works locally, half-broken on
247
+ * Pages", so it is unconditional rather than an adapter option.
247
248
  */
248
249
  export function writeNoJekyll(outDir: string): number {
249
250
  const path = join(outDir, ".nojekyll");
@@ -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
@@ -10,7 +10,11 @@
10
10
  import { createHash } from "node:crypto";
11
11
  import { readFileSync } from "node:fs";
12
12
  import { basename, extname, resolve } from "node:path";
13
- import { imageMetadata, processImage as encodeVariants } from "@jxsuite/compiler-binding";
13
+ import {
14
+ DEFAULT_IMAGE_QUALITY,
15
+ imageMetadata,
16
+ processImage as encodeVariants,
17
+ } from "@jxsuite/compiler-binding";
14
18
 
15
19
  import type { ImageQuality } from "@jxsuite/compiler-binding";
16
20
 
@@ -37,7 +41,8 @@ export interface ImageConfig {
37
41
  * the quality of its transform URLs; `png` is accepted so existing projects still validate.
38
42
  */
39
43
  quality: { webp?: number; avif?: number; jpeg?: number; png?: number };
40
- sizes: string;
44
+ /** The project-wide fallback `sizes`. A site build always has one; a direct caller may not. */
45
+ sizes?: string;
41
46
  lazyLoad: boolean;
42
47
  /**
43
48
  * Wrap a multi-format image in a `<picture>` with one `<source>` per format. Default true.
@@ -91,22 +96,52 @@ export function contentHash(srcPath: string) {
91
96
  * because `/images/_optimized/*` is served as immutable: the same name must always be the same
92
97
  * bytes, and a new encoder writes different bytes for an unchanged source.
93
98
  *
94
- * 1 → 2: variants stop at the largest configured width (compiler.md §7.2).
99
+ * 1 → 2: variants stop at the largest configured width (site-architecture.md §9.2.2).
95
100
  *
96
101
  * 2 → 3: the Rust core encodes. EXIF orientation is applied, embedded colour profiles are converted
97
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).
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}
98
118
  */
99
- const PIPELINE_VERSION = 3;
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
+ }
100
127
 
101
128
  /**
102
- * The hash in a variant's file name: the source's bytes and the pipeline that encoded them.
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.
131
+ *
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.
103
136
  *
104
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
105
140
  * @returns {string} 8-character hex hash
106
141
  */
107
- export function variantHash(srcPath: string) {
142
+ export function variantHash(srcPath: string, format: string, quality: number) {
108
143
  return createHash("md5")
109
- .update(`${contentHash(srcPath)}:${PIPELINE_VERSION}`)
144
+ .update(`${contentHash(srcPath)}:${PIPELINE_VERSION}:${format}:${quality}`)
110
145
  .digest("hex")
111
146
  .slice(0, 8);
112
147
  }
@@ -129,15 +164,15 @@ export function configHash(config: ImageConfig) {
129
164
 
130
165
  /**
131
166
  * Process a single source image: resize to each configured width, encode to each format. Writes
132
- * variants to cacheImgDir/_optimized/ (e.g. .cache/images/_optimized/).
167
+ * variants to cacheImgDir/_optimized/, the image cache (`getImageCacheDir`).
133
168
  *
134
169
  * The width ladder is the configured one capped at the source's own width, plus the source's native
135
170
  * width when it is narrower than the top rung; a source wider than the top rung stops there. A
136
171
  * variant whose file already exists is not encoded again, because its name carries a hash of the
137
- * source's bytes and the pipeline version.
172
+ * source's bytes, the pipeline version, and its format and quality (`variantHash`).
138
173
  *
139
174
  * @param {string} srcPath - Absolute path to source image
140
- * @param {string} cacheImgDir - Absolute path to the image cache directory (.cache/images/)
175
+ * @param {string} cacheImgDir - Absolute path to the image cache directory
141
176
  * @param {ImageConfig} config
142
177
  * @returns {Promise<ImageManifest>}
143
178
  */
@@ -156,7 +191,12 @@ export async function processImage(
156
191
  }
157
192
  const encoded = await encodeVariants({
158
193
  formats: config.formats,
159
- hash: variantHash(srcPath),
194
+ hashes: Object.fromEntries(
195
+ config.formats.map((format) => [
196
+ format,
197
+ variantHash(srcPath, format, qualityFor(config.quality, format)),
198
+ ]),
199
+ ),
160
200
  outDir: optimizedDir,
161
201
  quality,
162
202
  source: srcPath,