@prunellejs/images 0.8.0 → 0.9.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/llms.txt CHANGED
@@ -5,7 +5,7 @@
5
5
  ## Imports
6
6
 
7
7
  - `@prunellejs/images`: `images`, `image`, `Picture`, `shareCard`, `configureShareCard`, `optimizeImageFile`, `createMarkdownImageResolver`, `readImageDimensions`; types `ImagesPluginOptions`, `ImageAsset`, `ImageHelperOptions`, `ImgSpreadProps`, `PictureProps`, `ShareCardDefaults`, `ShareCardInput`, `OptimizeImageFileOptions`, `MarkdownImageResolverOptions`.
8
- - `@prunellejs/images/ambient`: ambient module declarations for `.png`, `.jpg`, `.jpeg`, `.webp`, `.avif`, `.gif` imports as `ImageAsset` (auto-referenced when importing `@prunellejs/images`).
8
+ - `@prunellejs/images/ambient`: ambient module declarations for `.png`, `.jpg`, `.jpeg`, `.webp`, `.avif`, `.gif` imports as `ImageAsset` (auto-referenced when importing `@prunellejs/images`; `.gif` imports pass through as-is with parsed dimensions to preserve animation).
9
9
 
10
10
  ## Plugin Setup (`images(options?)`)
11
11
 
@@ -15,10 +15,14 @@
15
15
  - `quality` (WebP, default `80`), `avifQuality` (default `55`), `cacheDir` (default `'.prunelle-cache/images'`), `pruneCache` (default `true`: after a build that prerendered pages, `og-` and `md-` cache files no page registered are deleted, together with the imported-image cache the build did not load). The runtime `/og/` and `/img/` stores are LRUs of twice the files the build registered, at least 256 and 4096.
16
16
  - `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
17
17
  - `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
18
+ - `remote`: `string[]` URL prefixes (`'https://cms.example.com/uploads/'`) `<Picture>` may resize from: same scheme, host and port, path under the prefix after `..` is resolved, and no query or fragment (refused, put cache-busting in the path); default none.
19
+ - `runtimeCacheBytes`: bytes the variants of uploads and remote images may take in `<cacheDir>/runtime/` (default 256 MiB); the least recently served are deleted past it.
18
20
 
19
21
  ## Components & Helpers
20
22
 
21
- - `<Picture src={hero} alt="..." sizes? priority? class? pictureClass? ...imgAttrs />`: renders `<picture>` with `<source type="image/avif">`, `<source type="image/webp">`, and `<img>`.
23
+ - `<Picture src={hero} alt="..." sizes? priority? class? pictureClass? ...imgAttrs />`: renders `<picture>` with `<source type="image/avif">`, `<source type="image/webp">`, and a fallback `<img>` (without duplicating `srcset`; fallback width capped at `<= 1280px` among generated widths).
24
+ - `<Picture src="/files/a.jpg" | "https://cms.example.com/uploads/a.jpg" ...>`: an image given by URL gets one `<source>` per `formats` with a srcset of `/_img?src=<url>&w=<width>&f=<format>` per `widths`, and an `<img>` at the largest width `<= 1280px` (or smallest available) in the last format; pass `width`/`height` to reserve its space. Throws while rendering without `images()` in the plugins, or for a remote URL off `remote`.
25
+ - `GET /_img?src=&w=&f=`: `w` and `f` must be a declared width and format (else 400). `src` is a public upload served by `@prunellejs/files` (through `PUBLIC_FILES_SERVICE`), JPEG, PNG, WebP, AVIF or GIF, or a URL under `remote` (else 404). A remote image is fetched with no redirect followed, 10 s and 25 MB at most (else 502), once. Bytes must sniff as JPEG, PNG, GIF, WebP or AVIF whatever the Content-Type says (else 502), and decode under 128 MP and 16 KP a side. At most 8 resizes run at once (else 503 with `Retry-After`), 600 requests a minute per client (else 429). Each variant is encoded once (`magick -resize <w>x>`, never upscaled; concurrent requests share the run), cached on disk, with an `etag` and `public, no-cache` for an upload (the etag changes with it) or `public, max-age=86400` for a remote image. Without `magick` it redirects to `src`.
22
26
  - `image(asset, { sizes?, priority? })`: returns `ImgSpreadProps` (`src`, `srcset`, `sizes`, `width`, `height`, `loading`, `decoding`, `fetchpriority`) for `<img {...image(hero)} alt="..." />`.
23
27
  - `shareCard({ title, subtitle?, badge?, image?, background?, color?, accent? })`: renders and caches a PNG card under `public/og/*.png` (via `rsvg-convert` or `magick`) and returns its URL (prefixed with `site` when configured). On a page rendered per request the card is served from memory and its SVG source is kept in the cache folder (`ogsrc-*.svg`), so the URL answers after a restart; replicas not sharing that folder answer it only after rendering the page.
24
28
  - `optimizeImageFile(absPath, options?)`: synchronously optimizes a local file into `dist/public/img/`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/images",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Build-time responsive AVIF/WebP image optimization plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,6 @@
22
22
  "directory": "packages/plugin-images"
23
23
  },
24
24
  "peerDependencies": {
25
- "prunelle": "^0.8.0"
25
+ "prunelle": "^0.9.0"
26
26
  }
27
27
  }
package/src/Picture.tsx CHANGED
@@ -1,9 +1,15 @@
1
1
  /** @jsxImportSource prunelle */
2
2
  import type { ImageAsset } from './helpers'
3
- import { image } from './helpers'
3
+ import type { RuntimeImageConfig } from './remote'
4
+ import { getAppContext } from 'prunelle/internal/server'
5
+ import { image, pickFallbackWidth } from './helpers'
6
+ import { isAllowedRemote, runtimeImageUrl, runtimeSrcset, RUNTIME_IMAGE_CONFIG_SERVICE } from './remote'
4
7
 
8
+ // The srcsets are the files this plugin wrote into the app's own build or serves itself, never another site's.
9
+ // prunelle-ignore-file rgpd/third-party-url
5
10
  export interface PictureProps {
6
- src: ImageAsset
11
+ /** An imported image, or the URL of an upload (`files.url(key)`) or of an image on an allowed remote (`images({ remote })`), resized when first asked for. */
12
+ src: ImageAsset | string
7
13
  alt: string
8
14
  sizes?: string | undefined
9
15
  priority?: boolean | undefined
@@ -12,8 +18,30 @@ export interface PictureProps {
12
18
  [attr: string]: unknown
13
19
  }
14
20
 
21
+ function runtimeConfig(src: string): RuntimeImageConfig {
22
+ const config = getAppContext()?.inject(RUNTIME_IMAGE_CONFIG_SERVICE)
23
+ if (config === undefined)
24
+ throw new Error(`@prunellejs/images: <Picture src="${src}"> resizes an image given by URL through the images() plugin: add images() to the plugins of prunelle.config.ts.`)
25
+ const remote = !src.startsWith('/') || src.startsWith('//')
26
+ if (remote && !isAllowedRemote(src, config.remote))
27
+ throw new Error(`@prunellejs/images: <Picture src="${src}"> is not under an allowed remote: add its prefix, such as "${URL.parse(src)?.origin ?? src}/", to images({ remote }) in prunelle.config.ts.`)
28
+ return config
29
+ }
30
+
15
31
  export function Picture({ src, alt, sizes, priority, class: cls, pictureClass, ...rest }: PictureProps) {
16
- const imgProps = image(src, { sizes, priority })
32
+ if (typeof src === 'string') {
33
+ const { widths, formats } = runtimeConfig(src)
34
+ // A browser too old for <source> gets a bounded fallback width (<= 1280px) in the last format, served from this site like the rest.
35
+ const fallbackWidth = pickFallbackWidth(widths) ?? widths[widths.length - 1]!
36
+ const fallback = runtimeImageUrl(src, fallbackWidth, formats[formats.length - 1]!)
37
+ return (
38
+ <picture class={pictureClass}>
39
+ {formats.map(format => <source type={`image/${format}`} srcset={runtimeSrcset(src, widths, format)} sizes={sizes} />)}
40
+ <img {...image(fallback, { priority })} {...rest} class={cls} alt={alt} />
41
+ </picture>
42
+ )
43
+ }
44
+ const { srcset: _srcset, ...imgProps } = image(src, { priority })
17
45
  return (
18
46
  <picture class={pictureClass}>
19
47
  {src.avifSrcset && <source type="image/avif" srcset={src.avifSrcset} sizes={sizes} />}
package/src/ambient.d.ts CHANGED
@@ -23,3 +23,8 @@ declare module '*.avif' {
23
23
  const asset: ImageAsset
24
24
  export default asset
25
25
  }
26
+ declare module '*.gif' {
27
+ import type { ImageAsset } from '@prunellejs/images'
28
+ const asset: ImageAsset
29
+ export default asset
30
+ }
package/src/cache.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  import { existsSync, readdirSync, rmSync } from 'node:fs'
4
4
  import { basename, join } from 'node:path'
5
5
 
6
- /** Cache files a prerendering build did not register: `og-<n>` is the cache of public `og/<n>`, `md-<n>` that of public `img/<n>`, and `md-<stem>-<hash>.json` the meta of a kept variant. */
6
+ /** Cache files a prerendering build did not register: `og-<n>` is the cache of public `og/<n>`, `md-<n>` that of public `img/<n>`, and `md-<stem>-<hash>.json` the meta of a kept variant. Runtime restart-survival `ogsrc-*.svg` files belong to dynamic routes and are never pruned here. */
7
7
  export function unusedOgAndMdCacheFiles(cacheEntries: readonly string[], publicFiles: readonly string[]): string[] {
8
8
  const kept = new Set<string>()
9
9
  for (const rel of publicFiles) {
package/src/card.ts CHANGED
@@ -326,7 +326,7 @@ export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults):
326
326
  queueBuildTask(appCtx.outDir, (async () => {
327
327
  const png = await rasterizeSvgToPngBytesAsync(svg)
328
328
  if (png === undefined)
329
- return
329
+ throw new Error(`@prunellejs/images: shareCard("${input.title}") failed to rasterize "og/${fileName}" to PNG (rsvg-convert and ImageMagick failed); refusing to leave a broken 404 URL in the build.`)
330
330
  mkdirSync(cacheDir, { recursive: true })
331
331
  writePngAtomic(cachedPng, png)
332
332
  mkdirSync(ogDir, { recursive: true })
package/src/helpers.ts CHANGED
@@ -22,6 +22,21 @@ export interface ImgSpreadProps {
22
22
  fetchpriority?: 'high' | 'low' | 'auto' | undefined
23
23
  }
24
24
 
25
+ export const MAX_FALLBACK_WIDTH = 1280
26
+
27
+ /** Picks the largest width `<= MAX_FALLBACK_WIDTH`, or the smallest available width when all exceed it. */
28
+ export function pickFallbackWidth(widths: readonly number[]): number | undefined {
29
+ let best: number | undefined
30
+ let smallest: number | undefined
31
+ for (const w of widths) {
32
+ if (smallest === undefined || w < smallest)
33
+ smallest = w
34
+ if (w <= MAX_FALLBACK_WIDTH && (best === undefined || w > best))
35
+ best = w
36
+ }
37
+ return best ?? smallest
38
+ }
39
+
25
40
  /** Returns responsive <img> props for spreading: `<img {...image(hero, { sizes: '50vw' })} alt="..." />`. */
26
41
  export function image(asset: ImageAsset | string, options: ImageHelperOptions = {}): ImgSpreadProps {
27
42
  if (typeof asset === 'string') {
package/src/pipeline.ts CHANGED
@@ -4,6 +4,7 @@ import type { ImageAsset } from './helpers'
4
4
  import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
5
5
  import { availableParallelism } from 'node:os'
6
6
  import { basename, extname, join } from 'node:path'
7
+ import { pickFallbackWidth } from './helpers'
7
8
 
8
9
  export const ALLOWED_IMAGE_EXTS = new Set([
9
10
  '.png',
@@ -257,7 +258,8 @@ export function assembleImageAsset(
257
258
  ): ImageAsset {
258
259
  const webpEntries: string[] = []
259
260
  const avifEntries: string[] = []
260
- let fallbackSrc = ''
261
+ const webpUrls: { width: number, url: string }[] = []
262
+ const avifUrls: { width: number, url: string }[] = []
261
263
 
262
264
  for (const f of meta.files) {
263
265
  const fileName = basename(f.rel)
@@ -266,15 +268,18 @@ export function assembleImageAsset(
266
268
  const url = `${urlPrefix}/${f.rel}`
267
269
  if (f.format === 'webp') {
268
270
  webpEntries.push(`${url} ${f.width}w`)
269
- fallbackSrc = url
271
+ webpUrls.push({ width: f.width, url })
270
272
  }
271
273
  else if (f.format === 'avif') {
272
274
  avifEntries.push(`${url} ${f.width}w`)
273
- if (fallbackSrc === '')
274
- fallbackSrc = url
275
+ avifUrls.push({ width: f.width, url })
275
276
  }
276
277
  }
277
278
 
279
+ const candidates = webpUrls.length > 0 ? webpUrls : avifUrls
280
+ const fallbackWidth = pickFallbackWidth(candidates.map(c => c.width))
281
+ const fallbackSrc = candidates.find(c => c.width === fallbackWidth)?.url ?? ''
282
+
278
283
  return {
279
284
  src: fallbackSrc,
280
285
  width: meta.width,
package/src/plugin.ts CHANGED
@@ -14,6 +14,7 @@ import { getAppContext } from 'prunelle/internal/server'
14
14
  import type { KnownImages } from './cache'
15
15
  import { knownImages, removeUnusedOgAndMd, runtimeStoreLimits } from './cache'
16
16
  import { persistedCardResolver, SHARE_CARD_CONFIG_SERVICE } from './card'
17
+ import { DEFAULT_RUNTIME_CACHE_BYTES, registerRuntimeImages } from './remote'
17
18
  import { readImageDimensions } from './dimensions'
18
19
  import { stripImageMetadata } from './metadata'
19
20
  import {
@@ -57,14 +58,18 @@ export interface ImagesPluginOptions {
57
58
  card?: ShareCardDefaults | undefined
58
59
  /** Default `sizes` attribute for relative images auto-optimized inside `@prunellejs/content` Markdown. */
59
60
  markdownSizes?: string | undefined
61
+ /** URL prefixes `<Picture src="https://...">` may resize from, such as `'https://cms.example.com/uploads/'`; any other remote image is refused. */
62
+ remote?: string[] | undefined
63
+ /** Bytes the variants of uploaded and remote images may take on disk, the least recently served removed past it (default 256 MiB). */
64
+ runtimeCacheBytes?: number | undefined
60
65
  }
61
66
 
62
67
  const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
63
68
  const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
64
69
  const PUBLIC_IMAGE = /\.(?:png|jpe?g|webp)$/i
65
70
  const PERSONAL_METADATA = new Set(['exif', 'xmp', 'iptc'])
66
- // Formats shipped as-is rather than rasterized to AVIF/WebP variants.
67
- const RAW_ONLY_IMAGE_EXTS = new Set(['.svg', '.ico'])
71
+ // Formats shipped as-is rather than rasterized to AVIF/WebP variants (GIFs keep animations intact).
72
+ const RAW_ONLY_IMAGE_EXTS = new Set(['.svg', '.ico', '.gif'])
68
73
  // Non-core Markdown image formats that fall back to the original <img> when their header cannot be parsed.
69
74
  const FALLBACK_MARKDOWN_EXTS = new Set(['.ico', '.bmp', '.tif', '.tiff'])
70
75
 
@@ -103,6 +108,43 @@ function checkImages(ctx: CheckPluginContext): void {
103
108
 
104
109
  const MISSING_MAGICK_MESSAGE = '@prunellejs/images: ImageMagick ("magick") was not found on PATH; AVIF/WebP optimization is disabled. Install ImageMagick to enable responsive image optimization.'
105
110
 
111
+ function recordSourceAssets(
112
+ sourceAssets: Map<string, Set<string>>,
113
+ emittedAssets: Map<string, Uint8Array>,
114
+ srcPath: string,
115
+ nextRels: Set<string>,
116
+ ): void {
117
+ const prevRels = sourceAssets.get(srcPath)
118
+ sourceAssets.set(srcPath, nextRels)
119
+ if (prevRels === undefined)
120
+ return
121
+ for (const oldRel of prevRels) {
122
+ if (nextRels.has(oldRel))
123
+ continue
124
+ let shared = false
125
+ for (const rels of sourceAssets.values()) {
126
+ if (rels.has(oldRel)) {
127
+ shared = true
128
+ break
129
+ }
130
+ }
131
+ if (!shared)
132
+ emittedAssets.delete(oldRel)
133
+ }
134
+ }
135
+
136
+ function pruneImportedCache(cacheRoot: string, activeCacheFiles: ReadonlySet<string>): void {
137
+ if (activeCacheFiles.size === 0 || !existsSync(cacheRoot))
138
+ return
139
+ for (const entry of readdirSync(cacheRoot, { withFileTypes: true })) {
140
+ if (!entry.isFile())
141
+ continue
142
+ const { name } = entry
143
+ if (!name.startsWith('og-') && !name.startsWith('ogsrc-') && !name.startsWith('md-') && !activeCacheFiles.has(name))
144
+ rmSync(join(cacheRoot, name), { force: true })
145
+ }
146
+ }
147
+
106
148
  interface PersistedImagesConfig extends KnownImages {
107
149
  cacheDirRel: string
108
150
  widths: number[]
@@ -122,6 +164,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
122
164
  const pruneCache = options.pruneCache ?? true
123
165
 
124
166
  const emittedAssets = new Map<string, Uint8Array>()
167
+ const sourceAssets = new Map<string, Set<string>>()
125
168
  const activeCacheFiles = new Set<string>()
126
169
  let lastCacheRoot: string | undefined
127
170
  let warnedMissingMagick = false
@@ -148,23 +191,25 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
148
191
  return [{
149
192
  name: 'prunelle-images',
150
193
  setup(b) {
151
- b.onLoad({ filter: /\.(?:png|jpe?g|webp|avif)$/i }, async (args) => {
194
+ b.onLoad({ filter: /\.(?:png|jpe?g|webp|avif|gif)$/i }, async (args) => {
152
195
  if (args.path.includes('/node_modules/'))
153
196
  return undefined
154
197
 
198
+ const ext = extname(args.path).toLowerCase()
155
199
  const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(args.path))).bytes
156
200
  const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
157
201
  const emitRaw = (width: number, height: number) => {
158
202
  const rel = `img/${rawFileName}`
159
203
  emittedAssets.set(rel, rawBytes)
204
+ recordSourceAssets(sourceAssets, emittedAssets, args.path, new Set([rel]))
160
205
  const asset: ImageAsset = { src: `${prefix}/${rel}`, width, height }
161
206
  return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' as const }
162
207
  }
163
208
 
164
- if (!magickAvailable) {
165
- const dims = readImageDimensions(rawBytes)
209
+ if (ext === '.gif' || !magickAvailable) {
210
+ const dims = readImageDimensions(rawBytes) ?? (magickAvailable ? await identifyImageAsync(args.path) : undefined)
166
211
  if (dims === undefined)
167
- throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}" (ImageMagick is unavailable and binary header could not be parsed)`)
212
+ throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}"${magickAvailable ? '' : ' (ImageMagick is unavailable and binary header could not be parsed)'}`)
168
213
  return emitRaw(dims.width, dims.height)
169
214
  }
170
215
 
@@ -191,11 +236,14 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
191
236
  writeFileAtomic(metaPath, JSON.stringify(meta))
192
237
  }
193
238
 
239
+ const nextRels = new Set<string>()
194
240
  const asset = assembleImageAsset(meta, cacheRoot, '', prefix, (rel, fileName, cachedFile) => {
195
241
  activeCacheFiles.add(fileName)
242
+ nextRels.add(rel)
196
243
  if (!emittedAssets.has(rel))
197
244
  emittedAssets.set(rel, new Uint8Array(readFileSync(cachedFile)))
198
245
  })
246
+ recordSourceAssets(sourceAssets, emittedAssets, args.path, nextRels)
199
247
  return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' }
200
248
  })
201
249
  },
@@ -231,13 +279,12 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
231
279
  }))
232
280
  for (const [rel, bytes] of emittedAssets)
233
281
  ctx.emitAsset(rel, bytes)
234
- if (pruneCache && !ctx.dev && lastCacheRoot !== undefined && activeCacheFiles.size > 0 && existsSync(lastCacheRoot)) {
235
- for (const entry of readdirSync(lastCacheRoot)) {
236
- if (!entry.startsWith('og-') && !entry.startsWith('md-') && !activeCacheFiles.has(entry))
237
- rmSync(join(lastCacheRoot, entry), { force: true })
238
- }
282
+ if (pruneCache && !ctx.dev && lastCacheRoot !== undefined)
283
+ pruneImportedCache(lastCacheRoot, activeCacheFiles)
284
+ if (!ctx.dev) {
285
+ emittedAssets.clear()
286
+ sourceAssets.clear()
239
287
  }
240
- emittedAssets.clear()
241
288
  activeCacheFiles.clear()
242
289
  },
243
290
  async afterPrerender(ctx) {
@@ -254,6 +301,8 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
254
301
  const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted), persistedCardResolver(cacheDir))
255
302
  api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
256
303
  registerRuntimeImageMiddleware(api, runtimeStore)
304
+ const variants = { cacheDir, widths: persisted?.widths ?? widths, formats: persisted?.formats ?? formats, quality: persisted?.quality ?? quality, avifQuality: persisted?.avifQuality ?? avifQuality }
305
+ registerRuntimeImages(api, { ...variants, remote: options.remote ?? [], maxBytes: options.runtimeCacheBytes ?? DEFAULT_RUNTIME_CACHE_BYTES })
257
306
  api.onShutdown(() => {
258
307
  if (isBuildPhase(api.outDir))
259
308
  leaveBuildPhase(api.outDir)
@@ -264,15 +313,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
264
313
  publicDir,
265
314
  cacheDir,
266
315
  } satisfies ShareCardDefaults)
267
- api.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({
268
- root: resolve(api.root),
269
- cacheDir,
270
- widths: persisted?.widths ?? widths,
271
- formats: persisted?.formats ?? formats,
272
- quality: persisted?.quality ?? quality,
273
- avifQuality: persisted?.avifQuality ?? avifQuality,
274
- sizes: persisted?.markdownSizes ?? options.markdownSizes,
275
- }))
316
+ api.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({ ...variants, root: resolve(api.root), sizes: persisted?.markdownSizes ?? options.markdownSizes }))
276
317
  },
277
318
  })
278
319
  }
@@ -409,9 +450,13 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
409
450
  const encoded = await encodeVariants(absPath, jobs)
410
451
  for (const job of encoded)
411
452
  writeFileSync(join(imgOutDir, job.fileName), readFileSync(job.cachedFile))
453
+ if (encoded.length < jobs.length) {
454
+ const encodedFiles = new Set(encoded.map(job => job.fileName))
455
+ const missing = jobs.filter(job => !encodedFiles.has(job.fileName)).map(job => `${job.width}w.${job.format}`)
456
+ throw new Error(`@prunellejs/images: failed to encode ${missing.join(', ')} for "${absPath}"; refusing to leave broken 404 URLs in the build.`)
457
+ }
412
458
  const files = encoded.map(job => ({ rel: `img/${job.fileName}`, width: job.width, format: job.format }))
413
- if (files.length === jobs.length)
414
- writeFileAtomic(metaPath, JSON.stringify({ width: dims.width, height: dims.height, files }))
459
+ writeFileAtomic(metaPath, JSON.stringify({ width: dims.width, height: dims.height, files }))
415
460
  })())
416
461
  return assembleImageAsset(plannedMeta, cacheRoot, 'md-', '', (_rel, fileName) => {
417
462
  appCtx.registerPublicFile(`img/${fileName}`)
package/src/remote.ts ADDED
@@ -0,0 +1,239 @@
1
+ // Images known only once the app runs, an upload or a CMS's: resized and re-encoded on first request, at the widths and in the formats the app declared, each variant kept once in a bounded disk cache.
2
+
3
+ import type { PublicFilesService, ServerPluginAPI } from 'prunelle/config'
4
+ import { createHash } from 'node:crypto'
5
+ import { mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
6
+ import { rename } from 'node:fs/promises'
7
+ import { join } from 'node:path'
8
+ import { PUBLIC_FILES_SERVICE, serviceKey } from 'prunelle/config'
9
+ import { DROP_METADATA_KEEP_ICC, runMagick } from './pipeline'
10
+ import { etagMatchesHeader, hasMagick } from './runtime'
11
+
12
+ export const RUNTIME_IMAGE_PATH = '/_img'
13
+ export const DEFAULT_RUNTIME_CACHE_BYTES = 256 * 1024 * 1024
14
+
15
+ export type ImageFormat = 'avif' | 'webp'
16
+
17
+ export interface RuntimeImageConfig {
18
+ readonly widths: readonly number[]
19
+ readonly formats: readonly ImageFormat[]
20
+ readonly remote: readonly string[]
21
+ }
22
+
23
+ /** What `<Picture>` needs to write the srcsets of an image given by URL. */
24
+ export const RUNTIME_IMAGE_CONFIG_SERVICE = serviceKey<RuntimeImageConfig>('prunelle.images.runtimeConfig')
25
+
26
+ const FETCH_TIMEOUT_MS = 10_000
27
+ const MAX_SOURCE_BYTES = 25 * 1024 * 1024
28
+ // Raster formats only: ImageMagick reading an SVG or a PDF from someone else can be made to read local files.
29
+ const SOURCE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif'])
30
+
31
+ const MAX_IN_FLIGHT = 8
32
+ // Decoded size, not file size: a 25 MB file can hold gigapixels.
33
+ const DECODE_LIMITS = ['-limit', 'area', '128MP', '-limit', 'width', '16KP', '-limit', 'height', '16KP', '-limit', 'disk', '1GiB']
34
+ const REQUESTS_PER_MINUTE = 600
35
+
36
+ const SIGNATURES: readonly { coder: string, matches: (b: Uint8Array) => boolean }[] = [
37
+ { coder: 'jpeg', matches: b => b[0] === 0xFF && b[1] === 0xD8 && b[2] === 0xFF },
38
+ { coder: 'png', matches: b => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47 },
39
+ { coder: 'gif', matches: b => b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38 },
40
+ { coder: 'webp', matches: b => ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 12) === 'WEBP' },
41
+ { coder: 'avif', matches: b => ascii(b, 4, 8) === 'ftyp' && (ascii(b, 8, 12) === 'avif' || ascii(b, 8, 12) === 'avis') },
42
+ ]
43
+
44
+ function ascii(bytes: Uint8Array, from: number, to: number): string {
45
+ return String.fromCharCode(...bytes.subarray(from, to))
46
+ }
47
+
48
+ /** The coder magick must read `bytes` with, from their first bytes, or `undefined` when they are not a raster format prunelle resizes (an SVG or MVG magick would sniff and follow to local files). */
49
+ export function sniffCoder(bytes: Uint8Array): string | undefined {
50
+ return SIGNATURES.find(signature => signature.matches(bytes))?.coder
51
+ }
52
+
53
+ /** Whether `src` lies under one of the allowed prefixes: same scheme, host and port, and a path starting with the prefix's, read after `..` is resolved. A query or a fragment is refused: each would be one more image to fetch and cache. */
54
+ export function isAllowedRemote(src: string, allow: readonly string[]): boolean {
55
+ const url = URL.parse(src)
56
+ if (url === null || (url.protocol !== 'https:' && url.protocol !== 'http:') || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '')
57
+ return false
58
+ return allow.some((prefix) => {
59
+ const allowed = URL.parse(prefix)
60
+ return allowed !== null && allowed.origin === url.origin && url.pathname.startsWith(allowed.pathname)
61
+ })
62
+ }
63
+
64
+ export function runtimeImageUrl(src: string, width: number, format: ImageFormat): string {
65
+ return `${RUNTIME_IMAGE_PATH}?${new URLSearchParams({ src, w: String(width), f: format })}`
66
+ }
67
+
68
+ export function runtimeSrcset(src: string, widths: readonly number[], format: ImageFormat): string {
69
+ return widths.map(width => `${runtimeImageUrl(src, width, format)} ${width}w`).join(', ')
70
+ }
71
+
72
+ interface VariantCache {
73
+ get: (name: string) => Promise<Uint8Array<ArrayBuffer> | undefined>
74
+ put: (name: string, bytes: Uint8Array<ArrayBuffer>) => Promise<void>
75
+ }
76
+
77
+ /** Variants on disk, the least recently served removed once they pass `maxBytes`. The order is this process's; one restarted starts from the files' ages. */
78
+ export function createVariantCache(dir: string, maxBytes: number): VariantCache {
79
+ let entries: Map<string, number> | undefined
80
+ let total = 0
81
+ const load = (): Map<string, number> => {
82
+ if (entries !== undefined)
83
+ return entries
84
+ mkdirSync(dir, { recursive: true })
85
+ const found = readdirSync(dir).filter(name => !name.endsWith('.tmp')).map(name => ({ name, stat: statSync(join(dir, name)) }))
86
+ entries = new Map(found.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs).map(({ name, stat }) => [name, stat.size]))
87
+ for (const size of entries.values())
88
+ total += size
89
+ return entries
90
+ }
91
+ const forget = (map: Map<string, number>, name: string): void => {
92
+ total -= map.get(name) ?? 0
93
+ map.delete(name)
94
+ }
95
+ return {
96
+ async get(name) {
97
+ const map = load()
98
+ const size = map.get(name)
99
+ if (size === undefined)
100
+ return undefined
101
+ const file = Bun.file(join(dir, name))
102
+ if (!(await file.exists())) {
103
+ forget(map, name)
104
+ return undefined
105
+ }
106
+ map.delete(name)
107
+ map.set(name, size)
108
+ return await file.bytes()
109
+ },
110
+ async put(name, bytes) {
111
+ const map = load()
112
+ const tmp = join(dir, `${name}.${process.pid}.tmp`)
113
+ await Bun.write(tmp, bytes)
114
+ await rename(tmp, join(dir, name))
115
+ forget(map, name)
116
+ map.set(name, bytes.byteLength)
117
+ total += bytes.byteLength
118
+ for (const oldest of map.keys()) {
119
+ if (total <= maxBytes || oldest === name)
120
+ break
121
+ forget(map, oldest)
122
+ rmSync(join(dir, oldest), { force: true })
123
+ }
124
+ },
125
+ }
126
+ }
127
+
128
+ async function readCapped(res: Response): Promise<Uint8Array<ArrayBuffer> | undefined> {
129
+ if (Number(res.headers.get('content-length') ?? 0) > MAX_SOURCE_BYTES || res.body === null) {
130
+ await res.body?.cancel()
131
+ return undefined
132
+ }
133
+ const chunks: Uint8Array<ArrayBuffer>[] = []
134
+ let size = 0
135
+ for await (const chunk of res.body) {
136
+ size += chunk.byteLength
137
+ if (size > MAX_SOURCE_BYTES) {
138
+ await res.body.cancel()
139
+ return undefined
140
+ }
141
+ chunks.push(chunk)
142
+ }
143
+ return new Uint8Array(await new Blob(chunks).arrayBuffer())
144
+ }
145
+
146
+ async function fetchRemote(src: string): Promise<Uint8Array<ArrayBuffer> | undefined> {
147
+ try {
148
+ // A redirect could leave the allow list, so none is followed.
149
+ const res = await fetch(src, { redirect: 'error', signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
150
+ if (!res.ok || !SOURCE_TYPES.has((res.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase())) {
151
+ await res.body?.cancel()
152
+ return undefined
153
+ }
154
+ return await readCapped(res)
155
+ }
156
+ catch (error) {
157
+ console.error(`@prunellejs/images: ${src} could not be fetched:`, error)
158
+ return undefined
159
+ }
160
+ }
161
+
162
+ interface Source {
163
+ /** Part of the cache key: an upload replaced at the same path gets new variants. */
164
+ version: string
165
+ cacheControl: string
166
+ bytes: () => Promise<Uint8Array<ArrayBuffer> | undefined>
167
+ }
168
+
169
+ async function findSource(src: string, remote: readonly string[], files: PublicFilesService | undefined): Promise<Source | undefined> {
170
+ if (src.startsWith('/') && !src.startsWith('//') && !src.startsWith('/\\')) {
171
+ const file = await files?.find(src)
172
+ if (file === undefined || !SOURCE_TYPES.has(file.contentType.toLowerCase()))
173
+ return undefined
174
+ return { version: file.etag, cacheControl: 'public, no-cache', bytes: file.bytes }
175
+ }
176
+ if (!isAllowedRemote(src, remote))
177
+ return undefined
178
+ return { version: '', cacheControl: 'public, max-age=86400', bytes: () => fetchRemote(src) }
179
+ }
180
+
181
+ export interface RuntimeImageRouteOptions extends RuntimeImageConfig {
182
+ cacheDir: string
183
+ maxBytes: number
184
+ quality: number
185
+ avifQuality: number
186
+ }
187
+
188
+ /** `GET /_img?src=&w=&f=`: a declared width and format of a public upload or an allowed remote image; anything else is refused before any work. */
189
+ export function registerRuntimeImages(api: ServerPluginAPI, options: RuntimeImageRouteOptions): void {
190
+ api.provide(RUNTIME_IMAGE_CONFIG_SERVICE, { widths: options.widths, formats: options.formats, remote: options.remote })
191
+ const cache = createVariantCache(join(options.cacheDir, 'runtime'), options.maxBytes)
192
+ const pending = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
193
+
194
+ const encode = async (name: string, source: Source, width: number, format: ImageFormat): Promise<Uint8Array<ArrayBuffer> | undefined> => {
195
+ const bytes = await source.bytes()
196
+ const coder = bytes === undefined ? undefined : sniffCoder(bytes)
197
+ if (bytes === undefined || coder === undefined)
198
+ return undefined
199
+ const quality = format === 'avif' ? options.avifQuality : options.quality
200
+ const result = await runMagick([...DECODE_LIMITS, `${coder}:-[0]`, '-auto-orient', ...DROP_METADATA_KEEP_ICC, '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`], new Response(bytes))
201
+ if (!result.ok || result.stdout.byteLength === 0)
202
+ return undefined
203
+ await cache.put(name, result.stdout)
204
+ return result.stdout
205
+ }
206
+
207
+ api.route('GET', RUNTIME_IMAGE_PATH, async (ctx) => {
208
+ const params = ctx.url.searchParams
209
+ const width = Number(params.get('w'))
210
+ const format = options.formats.find(f => f === params.get('f'))
211
+ const src = params.get('src')
212
+ if (!options.widths.includes(width) || format === undefined || src === null)
213
+ return new Response(`w must be one of ${options.widths.join(', ')} and f one of ${options.formats.join(', ')}, with a src`, { status: 400, headers: { 'cache-control': 'no-store' } })
214
+ const source = await findSource(src, options.remote, api.inject(PUBLIC_FILES_SERVICE))
215
+ if (source === undefined)
216
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
217
+ if (!hasMagick())
218
+ return ctx.redirect(src, 302, { external: true })
219
+
220
+ const name = `${createHash('sha256').update(`${src}\n${source.version}`).digest('hex').slice(0, 32)}-${width}.${format}`
221
+ const headers = { 'content-type': `image/${format}`, 'cache-control': source.cacheControl, 'etag': `"${name}"`, 'x-content-type-options': 'nosniff' }
222
+ if (etagMatchesHeader(ctx.request.headers.get('if-none-match'), headers.etag))
223
+ return new Response(null, { status: 304, headers })
224
+ let body = await cache.get(name)
225
+ if (body === undefined) {
226
+ let job = pending.get(name)
227
+ if (job === undefined) {
228
+ if (pending.size >= MAX_IN_FLIGHT)
229
+ return new Response('Too many images are being resized, retry shortly', { status: 503, headers: { 'cache-control': 'no-store', 'retry-after': '2' } })
230
+ job = encode(name, source, width, format).finally(() => pending.delete(name))
231
+ pending.set(name, job)
232
+ }
233
+ body = await job
234
+ }
235
+ if (body === undefined)
236
+ return new Response('The source could not be read as an image', { status: 502, headers: { 'cache-control': 'no-store' } })
237
+ return new Response(body, { status: 200, headers })
238
+ }, { rateLimit: { max: REQUESTS_PER_MINUTE, windowMs: 60_000 } })
239
+ }
package/src/runtime.ts CHANGED
@@ -50,7 +50,7 @@ export function computeEtag(body: Uint8Array | string): string {
50
50
  return `W/"${Bun.hash(body).toString(36)}"`
51
51
  }
52
52
 
53
- function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
53
+ export function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
54
54
  if (!ifNoneMatch)
55
55
  return false
56
56
  const trimmed = ifNoneMatch.trim()