@prunellejs/images 0.1.1 → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -11,7 +11,8 @@
11
11
 
12
12
  - `widths`: responsive widths in px (default `[320, 640, 960, 1280, 1920]`).
13
13
  - `formats`: `('avif' | 'webp')[]` (default `['avif', 'webp']`; uses ImageMagick `magick` on `PATH`, falls back to original file with parsed dimensions when unavailable). Each image is decoded once per format, one `magick` run writing all its widths; runs share one budget for the whole build (half the cores, at most 8 `magick` at once), each limited to one thread and 512 MiB and killed after 2 min; a failed run warns with the file, the widths and `magick`'s error and leaves those variants out until the next build retries them (the original ships when none succeeds).
14
- - `quality` (WebP, default `80`), `avifQuality` (default `55`), `cacheDir` (default `'.prunelle-cache/images'`), `pruneCache` (default `true`).
14
+ - Every image the build ships, original included, loses its EXIF (GPS position, camera serial), XMP, IPTC and text metadata; a JPEG keeps only its Orientation, and every variant keeps its ICC colour profile (`magick ... +profile "!icc,*"`, not `-strip`). `prunelle check` warns about each JPEG, PNG or WebP under `public/` still carrying EXIF, XMP or IPTC, since `public/` is copied as is.
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.
15
16
  - `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
16
17
  - `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
17
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/images",
3
- "version": "0.1.1",
3
+ "version": "0.7.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.1.1"
25
+ "prunelle": "^0.7.0"
26
26
  }
27
27
  }
package/src/cache.ts ADDED
@@ -0,0 +1,53 @@
1
+ // What a build leaves in the image cache, and how many images the runtime stores must be able to hold.
2
+
3
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
4
+ import { basename, join } from 'node:path'
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. */
7
+ export function unusedOgAndMdCacheFiles(cacheEntries: readonly string[], publicFiles: readonly string[]): string[] {
8
+ const kept = new Set<string>()
9
+ for (const rel of publicFiles) {
10
+ if (rel.startsWith('og/'))
11
+ kept.add(`og-${basename(rel)}`)
12
+ else if (rel.startsWith('img/')) {
13
+ const variant = `md-${basename(rel)}`
14
+ kept.add(variant)
15
+ // `md-<stem>-<hash>.json` describes the variants `md-<stem>-<hash>-<width>w.<format>`.
16
+ kept.add(variant.replace(/-\d+w\.\w+$/, '.json'))
17
+ }
18
+ }
19
+ return cacheEntries.filter(entry => (entry.startsWith('og-') || entry.startsWith('md-')) && !kept.has(entry))
20
+ }
21
+
22
+ export function removeUnusedOgAndMd(cacheRoot: string, publicFiles: readonly string[]): void {
23
+ if (!existsSync(cacheRoot))
24
+ return
25
+ for (const entry of unusedOgAndMdCacheFiles(readdirSync(cacheRoot), publicFiles))
26
+ rmSync(join(cacheRoot, entry), { force: true })
27
+ }
28
+
29
+ /** How many `og/` and `img/` files the build registered, kept in its plugin data: what the runtime stores must hold at least. */
30
+ export interface KnownImages {
31
+ knownOg?: number | undefined
32
+ knownImg?: number | undefined
33
+ }
34
+
35
+ export function knownImages(publicFiles: readonly string[]): Required<KnownImages> {
36
+ let knownOg = 0
37
+ let knownImg = 0
38
+ for (const rel of publicFiles) {
39
+ if (rel.startsWith('og/'))
40
+ knownOg++
41
+ else if (rel.startsWith('img/'))
42
+ knownImg++
43
+ }
44
+ return { knownOg, knownImg }
45
+ }
46
+
47
+ export const MIN_OG_ENTRIES = 256
48
+ export const MIN_IMG_ENTRIES = 4096
49
+
50
+ /** The size of the `/og/` and `/img/` stores: twice what the build knows, never under its floor, so an image the HTML references is served and a flood of unique URLs still cannot grow a store for ever. */
51
+ export function runtimeStoreLimits(known: KnownImages | undefined): [maxOg: number, maxImg: number] {
52
+ return [Math.max(MIN_OG_ENTRIES, (known?.knownOg ?? 0) * 2), Math.max(MIN_IMG_ENTRIES, (known?.knownImg ?? 0) * 2)]
53
+ }
package/src/card.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // (cached by content hash in `.prunelle-cache/images/` at build time, or served from memory at runtime for --compile).
4
4
 
5
5
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
6
+ import { extname, join, resolve } from 'node:path'
7
7
  import { isInside, serviceKey } from 'prunelle/config'
8
8
  import { getAppContext } from 'prunelle/internal/server'
9
9
  import { escAttr } from 'prunelle/server'
@@ -95,12 +95,12 @@ function readConfinedSvgImage(imageSpec: string): string {
95
95
  return imageSpec
96
96
  const rootDir = resolve(getAppContext()?.root ?? process.cwd())
97
97
  const absImg = resolve(rootDir, imageSpec)
98
- if (!isInside(rootDir, absImg) || !existsSync(absImg))
98
+ if (extname(absImg).toLowerCase() !== '.svg' || !isInside(rootDir, absImg) || !existsSync(absImg))
99
99
  return ''
100
100
  try {
101
101
  const realRoot = realpathSync(rootDir)
102
102
  const realImg = realpathSync(absImg)
103
- if (!isInside(realRoot, realImg))
103
+ if (extname(realImg).toLowerCase() !== '.svg' || !isInside(realRoot, realImg))
104
104
  return ''
105
105
  return readFileSync(realImg, 'utf8')
106
106
  }
@@ -116,7 +116,7 @@ function buildCardSvg(input: ShareCardInput, cfg: ShareCardDefaults): string {
116
116
  const fg = input.color ?? cfg.color ?? '#dbe0ea'
117
117
  const accent = input.accent ?? cfg.accent ?? '#f5b83d'
118
118
  const muted = cfg.mutedColor ?? '#8b95aa'
119
- const font = cfg.fontFamily ?? 'system-ui, -apple-system, sans-serif'
119
+ const font = cfg.fontFamily ?? '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", "Helvetica Neue", Arial, sans-serif'
120
120
 
121
121
  const hasGraphic = Boolean(input.image)
122
122
  const titleLines = wrapLines(input.title, hasGraphic ? 20 : 26, 3)
@@ -196,7 +196,7 @@ export function shareCard(input: ShareCardInput, overrides?: ShareCardDefaults):
196
196
  const png = await rasterizeSvgToPngBytesAsync(svg)
197
197
  if (png !== undefined)
198
198
  return { body: png, contentType: 'image/png', etag: computeEtag(png) }
199
- return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg) }
199
+ return { body: svg, contentType: 'image/svg+xml', etag: computeEtag(svg), fallback: true }
200
200
  })
201
201
  return `${site}${urlPath}`
202
202
  }
@@ -0,0 +1,163 @@
1
+ /** Metadata a file can carry about the person or device behind it. */
2
+ export type ImageMetadataKind = 'exif' | 'xmp' | 'iptc' | 'comment' | 'text'
3
+
4
+ export interface StrippedImage {
5
+ /** The image without its metadata, the input itself when nothing was removed. */
6
+ bytes: Uint8Array<ArrayBuffer>
7
+ removed: ImageMetadataKind[]
8
+ }
9
+
10
+ const EXIF_HEADER = [0x45, 0x78, 0x69, 0x66, 0x00, 0x00]
11
+
12
+ function ascii(bytes: Uint8Array, at: number, length: number): string {
13
+ return String.fromCharCode(...bytes.subarray(at, at + length))
14
+ }
15
+
16
+ function concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
17
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
18
+ let at = 0
19
+ for (const part of parts) {
20
+ out.set(part, at)
21
+ at += part.length
22
+ }
23
+ return out
24
+ }
25
+
26
+ // The EXIF Orientation tag of IFD0, so a stripped photo still displays the right way up.
27
+ function exifOrientation(payload: Uint8Array): number | undefined {
28
+ const tiff = payload.subarray(EXIF_HEADER.length)
29
+ if (tiff.length < 8)
30
+ return undefined
31
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength)
32
+ const little = tiff[0] === 0x49
33
+ const ifd = view.getUint32(4, little)
34
+ if (ifd + 2 > tiff.length)
35
+ return undefined
36
+ const count = view.getUint16(ifd, little)
37
+ for (let i = 0; i < count; i++) {
38
+ const entry = ifd + 2 + i * 12
39
+ if (entry + 12 > tiff.length)
40
+ return undefined
41
+ if (view.getUint16(entry, little) === 0x0112)
42
+ return view.getUint16(entry + 8, little)
43
+ }
44
+ return undefined
45
+ }
46
+
47
+ // An APP1 segment holding only an Orientation tag.
48
+ function orientationSegment(orientation: number): Uint8Array {
49
+ return new Uint8Array([
50
+ 0xFF, 0xE1, 0x00, 0x22, ...EXIF_HEADER,
51
+ 0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08,
52
+ 0x00, 0x01, 0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, orientation >> 8, orientation & 0xFF, 0x00, 0x00,
53
+ 0x00, 0x00, 0x00, 0x00,
54
+ ])
55
+ }
56
+
57
+ function jpegSegmentKind(marker: number, payload: Uint8Array): ImageMetadataKind | undefined {
58
+ if (marker === 0xE1)
59
+ return EXIF_HEADER.every((b, i) => payload[i] === b) ? 'exif' : 'xmp'
60
+ if (marker === 0xED)
61
+ return 'iptc'
62
+ if (marker === 0xFE)
63
+ return 'comment'
64
+ return undefined
65
+ }
66
+
67
+ function stripJpeg(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
68
+ const kept: Uint8Array[] = [bytes.subarray(0, 2)]
69
+ const removed = new Set<ImageMetadataKind>()
70
+ let orientation: number | undefined
71
+ let at = 2
72
+ while (at + 4 <= bytes.length && bytes[at] === 0xFF) {
73
+ const marker = bytes[at + 1]!
74
+ if (marker === 0xDA) {
75
+ kept.push(bytes.subarray(at))
76
+ at = bytes.length
77
+ break
78
+ }
79
+ const length = (bytes[at + 2]! << 8) | bytes[at + 3]!
80
+ const end = at + 2 + length
81
+ const kind = jpegSegmentKind(marker, bytes.subarray(at + 4, end))
82
+ if (kind === undefined) {
83
+ kept.push(bytes.subarray(at, end))
84
+ }
85
+ else {
86
+ removed.add(kind)
87
+ if (kind === 'exif')
88
+ orientation ??= exifOrientation(bytes.subarray(at + 4, end))
89
+ }
90
+ at = end
91
+ }
92
+ if (at !== bytes.length || removed.size === 0)
93
+ return { bytes, removed: [] }
94
+ if (orientation !== undefined && orientation > 1 && orientation <= 8)
95
+ kept.splice(kept[1]?.[1] === 0xE0 ? 2 : 1, 0, orientationSegment(orientation))
96
+ return { bytes: concat(kept), removed: [...removed] }
97
+ }
98
+
99
+ const PNG_METADATA: Record<string, ImageMetadataKind> = { eXIf: 'exif', iTXt: 'text', tEXt: 'text', zTXt: 'text', tIME: 'text' }
100
+
101
+ function stripPng(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
102
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
103
+ const kept: Uint8Array[] = [bytes.subarray(0, 8)]
104
+ const removed = new Set<ImageMetadataKind>()
105
+ let at = 8
106
+ while (at + 12 <= bytes.length) {
107
+ const end = at + 12 + view.getUint32(at)
108
+ if (end > bytes.length)
109
+ return { bytes, removed: [] }
110
+ const type = ascii(bytes, at + 4, 4)
111
+ const kind = type === 'iTXt' && ascii(bytes, at + 8, 17) === 'XML:com.adobe.xmp' ? 'xmp' : PNG_METADATA[type]
112
+ if (kind === undefined)
113
+ kept.push(bytes.subarray(at, end))
114
+ else
115
+ removed.add(kind)
116
+ at = end
117
+ }
118
+ if (at !== bytes.length || removed.size === 0)
119
+ return { bytes, removed: [] }
120
+ return { bytes: concat(kept), removed: [...removed] }
121
+ }
122
+
123
+ const WEBP_METADATA: Record<string, ImageMetadataKind> = { 'EXIF': 'exif', 'XMP ': 'xmp' }
124
+
125
+ function stripWebp(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
126
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
127
+ const kept: Uint8Array[] = []
128
+ const removed = new Set<ImageMetadataKind>()
129
+ let at = 12
130
+ while (at + 8 <= bytes.length) {
131
+ const size = view.getUint32(at + 4, true)
132
+ const end = Math.min(at + 8 + size + (size & 1), bytes.length)
133
+ if (at + 8 + size > bytes.length)
134
+ return { bytes, removed: [] }
135
+ const kind = WEBP_METADATA[ascii(bytes, at, 4)]
136
+ if (kind === undefined)
137
+ kept.push(bytes.slice(at, end))
138
+ else
139
+ removed.add(kind)
140
+ at = end
141
+ }
142
+ if (removed.size === 0)
143
+ return { bytes, removed: [] }
144
+ const vp8x = kept.find(chunk => ascii(chunk, 0, 4) === 'VP8X')
145
+ if (vp8x !== undefined)
146
+ vp8x[8] = vp8x[8]! & ~0x0C
147
+ const body = concat(kept)
148
+ const header = new Uint8Array(12)
149
+ header.set(bytes.subarray(0, 12))
150
+ new DataView(header.buffer).setUint32(4, body.length + 4, true)
151
+ return { bytes: concat([header, body]), removed: [...removed] }
152
+ }
153
+
154
+ /** Removes EXIF (GPS position, device serial), XMP, IPTC and text metadata from a JPEG, PNG or WebP file; a JPEG keeps its orientation. Other formats and unreadable files come back unchanged. */
155
+ export function stripImageMetadata(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
156
+ if (bytes[0] === 0xFF && bytes[1] === 0xD8)
157
+ return stripJpeg(bytes)
158
+ if (ascii(bytes, 1, 3) === 'PNG')
159
+ return stripPng(bytes)
160
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP')
161
+ return stripWebp(bytes)
162
+ return { bytes, removed: [] }
163
+ }
package/src/pipeline.ts CHANGED
@@ -35,6 +35,9 @@ function magickBinary(): string {
35
35
  return magickBin.bin
36
36
  }
37
37
 
38
+ /** Every profile goes (EXIF with its GPS position, XMP, IPTC) except the ICC one, which `-strip` also drops and which keeps a wide-gamut photo in its colours. */
39
+ export const DROP_METADATA_KEEP_ICC = ['+profile', '!icc,*']
40
+
38
41
  let activeSlots = 0
39
42
  const waitingForSlot: (() => void)[] = []
40
43
 
@@ -149,7 +152,7 @@ async function encodeFormatAsync(srcPath: string, jobs: readonly VariantEncodeJo
149
152
  const result = await runMagick([
150
153
  `${srcPath}[0]`,
151
154
  '-auto-orient',
152
- '-strip',
155
+ ...DROP_METADATA_KEEP_ICC,
153
156
  '-write',
154
157
  'mpr:src',
155
158
  '+delete',
@@ -196,8 +199,8 @@ export async function encodeVariants(srcPath: string, jobs: readonly VariantEnco
196
199
  return jobs.filter(job => existsSync(job.cachedFile))
197
200
  }
198
201
 
199
- // Bumped when the same source and options give other variants or sizes, so a cache from before is not reused: 2 sizes photos after their EXIF orientation (#3676).
200
- const VARIANT_CACHE_VERSION = 2
202
+ // Bumped when the same source and options give other variants or sizes, so a cache from before is not reused: 2 sizes photos after their EXIF orientation (#3676), 3 keeps their ICC profile (#257).
203
+ const VARIANT_CACHE_VERSION = 3
201
204
 
202
205
  export function computeImageKey(srcPath: string, rawBytes: Uint8Array, cfg: VariantPipelineConfig): { hash: string, stem: string, rawFileName: string } {
203
206
  const ext = extname(srcPath).toLowerCase()
package/src/plugin.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Built strictly on the public PrunellePlugin API (bunPlugins + build(ctx).emitAsset).
3
3
 
4
4
  import type { BunPlugin } from 'bun'
5
- import type { PrunellePlugin } from 'prunelle/config'
5
+ import type { CheckPluginContext, PrunellePlugin } from 'prunelle/config'
6
6
  import type { ShareCardDefaults } from './card'
7
7
  import type { ImageAsset } from './helpers'
8
8
  import type { CachedImageMeta, VariantPipelineConfig } from './pipeline'
@@ -11,8 +11,11 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync,
11
11
  import { dirname, extname, join, resolve } from 'node:path'
12
12
  import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle/config'
13
13
  import { getAppContext } from 'prunelle/internal/server'
14
+ import type { KnownImages } from './cache'
15
+ import { knownImages, removeUnusedOgAndMd, runtimeStoreLimits } from './cache'
14
16
  import { SHARE_CARD_CONFIG_SERVICE } from './card'
15
17
  import { readImageDimensions } from './dimensions'
18
+ import { stripImageMetadata } from './metadata'
16
19
  import {
17
20
  ALLOWED_IMAGE_EXTS,
18
21
  assembleImageAsset,
@@ -58,9 +61,34 @@ export interface ImagesPluginOptions {
58
61
 
59
62
  const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
60
63
  const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
64
+ const PUBLIC_IMAGE = /\.(?:png|jpe?g|webp)$/i
65
+ const PERSONAL_METADATA = new Set(['exif', 'xmp', 'iptc'])
66
+
67
+ // Files in public/ are served as they are, so a photo there hands its GPS position and camera serial to every visitor.
68
+ function publicImageMetadataWarnings(publicDir: string): string[] {
69
+ if (!existsSync(publicDir))
70
+ return []
71
+ const warnings: string[] = []
72
+ for (const rel of readdirSync(publicDir, { recursive: true, encoding: 'utf8' })) {
73
+ if (!PUBLIC_IMAGE.test(rel))
74
+ continue
75
+ const kinds = stripImageMetadata(new Uint8Array(readFileSync(join(publicDir, rel)))).removed.filter(kind => PERSONAL_METADATA.has(kind))
76
+ if (kinds.length > 0)
77
+ warnings.push(`@prunellejs/images: public/${rel} carries ${kinds.map(k => k.toUpperCase()).join(' and ')} metadata (GPS position, camera serial) that every visitor can download: import it from src/ so the build strips it, or strip it yourself (\`magick public/${rel} +profile "!icc,*" public/${rel}\`, which keeps the ICC colour profile).`)
78
+ }
79
+ return warnings
80
+ }
81
+
82
+ function checkImages(ctx: CheckPluginContext): void {
83
+ if (!hasMagick())
84
+ ctx.error(MISSING_MAGICK_MESSAGE)
85
+ for (const warning of publicImageMetadataWarnings(join(ctx.root, 'public')))
86
+ ctx.warn(warning)
87
+ }
88
+
61
89
  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.'
62
90
 
63
- interface PersistedImagesConfig {
91
+ interface PersistedImagesConfig extends KnownImages {
64
92
  cacheDirRel: string
65
93
  widths: number[]
66
94
  formats: ('avif' | 'webp')[]
@@ -92,10 +120,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
92
120
 
93
121
  return definePlugin({
94
122
  name: '@prunellejs/images',
95
- check(ctx) {
96
- if (!hasMagick())
97
- ctx.error(MISSING_MAGICK_MESSAGE)
98
- },
123
+ check: checkImages,
99
124
  bunPlugins: ({ root, assetPrefix }): BunPlugin[] => {
100
125
  const cacheRoot = resolve(root, cacheDirRel)
101
126
  lastCacheRoot = cacheRoot
@@ -112,7 +137,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
112
137
  if (args.path.includes('/node_modules/'))
113
138
  return undefined
114
139
 
115
- const rawBytes = new Uint8Array(readFileSync(args.path))
140
+ const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(args.path))).bytes
116
141
  const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
117
142
  const emitRaw = (width: number, height: number) => {
118
143
  const rel = `img/${rawFileName}`
@@ -202,12 +227,16 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
202
227
  },
203
228
  async afterPrerender(ctx) {
204
229
  await flushBuildPhase(ctx.outDir)
230
+ ctx.setData(knownImages(ctx.publicFiles))
231
+ // Only a build that rendered pages registered the cards and variants it uses: without one the runtime still reads those cache files.
232
+ if (pruneCache && lastCacheRoot !== undefined && ctx.routes.some(route => Object.keys(route.prerendered ?? {}).length > 0))
233
+ removeUnusedOgAndMd(lastCacheRoot, ctx.publicFiles)
205
234
  },
206
235
  server(api) {
207
236
  const persisted = api.getBuildData<PersistedImagesConfig>()
208
237
  const publicDir = join(api.outDir, 'public')
209
238
  const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
210
- const runtimeStore = createRuntimeImageStore()
239
+ const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted))
211
240
  api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
212
241
  registerRuntimeImageMiddleware(api, runtimeStore)
213
242
  api.onShutdown(() => {
@@ -270,7 +299,7 @@ function optimizeForRuntime(
270
299
  return { body: bytes, contentType: mime, etag: computeEtag(bytes) }
271
300
  }
272
301
  catch {
273
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
302
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
274
303
  }
275
304
  })
276
305
  })
@@ -289,7 +318,7 @@ function optimizeForRuntime(
289
318
  const encoded = await encodeVariantToBytesAsync(absPath, job.width, job.format, job.quality)
290
319
  if (encoded !== undefined)
291
320
  return { body: encoded, contentType: targetMime, etag: computeEtag(encoded) }
292
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
321
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
293
322
  })
294
323
  })
295
324
  }
@@ -308,7 +337,7 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
308
337
  cachePrefix: 'md-',
309
338
  }
310
339
  const appCtx = getAppContext()
311
- const rawBytes = new Uint8Array(readFileSync(absPath))
340
+ const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(absPath))).bytes
312
341
  const dims = readImageDimensions(rawBytes)
313
342
  if (dims === undefined)
314
343
  throw new Error(`@prunellejs/images: could not determine dimensions for "${absPath}"`)
@@ -423,7 +452,6 @@ export function createMarkdownImageResolver(options: MarkdownImageResolverOption
423
452
  ...(srcset !== undefined ? { sizes } : {}),
424
453
  width: asset.width,
425
454
  height: asset.height,
426
- loading: 'lazy' as const,
427
455
  }
428
456
  }
429
457
  }
package/src/runtime.ts CHANGED
@@ -2,12 +2,15 @@
2
2
 
3
3
  import type { ServerPluginAPI } from 'prunelle/config'
4
4
  import { serviceKey } from 'prunelle/config'
5
- import { runMagick } from './pipeline'
5
+ import { MIN_IMG_ENTRIES, MIN_OG_ENTRIES } from './cache'
6
+ import { DROP_METADATA_KEEP_ICC, runMagick } from './pipeline'
6
7
 
7
8
  export interface RuntimeImagePayload {
8
9
  body: Uint8Array<ArrayBuffer> | string
9
10
  contentType: string
10
11
  etag: string
12
+ /** Marks a transient fallback payload: served with `Cache-Control: no-store` and never pinned to `entry.resolved`. */
13
+ fallback?: boolean | undefined
11
14
  }
12
15
 
13
16
  interface LazyEntry {
@@ -58,16 +61,25 @@ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
58
61
  return trimmed.split(',').some(part => strip(part.trim()) === target)
59
62
  }
60
63
 
61
- export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
62
- const entries = new Map<string, LazyEntry>()
64
+ export function createRuntimeImageStore(maxOgEntries = MIN_OG_ENTRIES, maxImgEntries = MIN_IMG_ENTRIES): RuntimeImageStore {
65
+ // `/og/` share cards and `/img/` variants each sit in their own LRU, so flooding unique `/og/` URLs can never evict live `/img/` entries to 404.
66
+ const ogEntries = new Map<string, LazyEntry>()
67
+ const imgEntries = new Map<string, LazyEntry>()
68
+
69
+ function bucketFor(pathname: string): { map: Map<string, LazyEntry>, limit: number } {
70
+ return pathname.startsWith('/og/')
71
+ ? { map: ogEntries, limit: maxOgEntries }
72
+ : { map: imgEntries, limit: maxImgEntries }
73
+ }
63
74
 
64
75
  function put(pathname: string, entry: LazyEntry): void {
65
- entries.delete(pathname)
66
- entries.set(pathname, entry)
67
- if (entries.size > maxEntries) {
68
- const oldest = entries.keys().next()
76
+ const { map, limit } = bucketFor(pathname)
77
+ map.delete(pathname)
78
+ map.set(pathname, entry)
79
+ if (map.size > limit) {
80
+ const oldest = map.keys().next()
69
81
  if (!oldest.done)
70
- entries.delete(oldest.value)
82
+ map.delete(oldest.value)
71
83
  }
72
84
  }
73
85
 
@@ -76,25 +88,27 @@ export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
76
88
  put(pathname, { resolved: { body, contentType, etag: computeEtag(body) } })
77
89
  },
78
90
  setLazy(pathname, load) {
79
- if (entries.has(pathname))
91
+ const { map } = bucketFor(pathname)
92
+ if (map.has(pathname))
80
93
  return
81
94
  put(pathname, { load })
82
95
  },
83
96
  has(pathname) {
84
- return entries.has(pathname)
97
+ return bucketFor(pathname).map.has(pathname)
85
98
  },
86
99
  async serve(pathname, request) {
87
- const entry = entries.get(pathname)
100
+ const { map } = bucketFor(pathname)
101
+ const entry = map.get(pathname)
88
102
  if (entry === undefined)
89
103
  return undefined
90
104
  // Refresh LRU position
91
- entries.delete(pathname)
92
- entries.set(pathname, entry)
105
+ map.delete(pathname)
106
+ map.set(pathname, entry)
93
107
 
94
108
  let payload = entry.resolved
95
109
  if (payload === undefined && entry.load !== undefined) {
96
110
  entry.pending ??= entry.load().then((res) => {
97
- if (res !== undefined) {
111
+ if (res !== undefined && !res.fallback) {
98
112
  entry.resolved = res
99
113
  entry.load = undefined
100
114
  }
@@ -109,12 +123,17 @@ export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
109
123
  if (payload === undefined)
110
124
  return undefined
111
125
 
112
- const headers: Record<string, string> = {
113
- 'content-type': payload.contentType,
114
- 'cache-control': 'public, max-age=31536000, immutable',
115
- 'etag': payload.etag,
116
- }
117
- if (etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
126
+ const headers: Record<string, string> = payload.fallback
127
+ ? {
128
+ 'content-type': payload.contentType,
129
+ 'cache-control': 'no-store',
130
+ }
131
+ : {
132
+ 'content-type': payload.contentType,
133
+ 'cache-control': 'public, max-age=31536000, immutable',
134
+ 'etag': payload.etag,
135
+ }
136
+ if (!payload.fallback && etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
118
137
  return new Response(null, { status: 304, headers })
119
138
  if (request.method === 'HEAD')
120
139
  return new Response(null, { status: 200, headers })
@@ -190,8 +209,30 @@ export async function flushBuildPhase(outDir: string): Promise<void> {
190
209
  }
191
210
  }
192
211
 
212
+ export const RSVG_SLOTS = 4
213
+ export const RSVG_TIMEOUT_MS = 15_000
214
+
215
+ let activeRsvgSlots = 0
216
+ const waitingForRsvgSlot: (() => void)[] = []
217
+
218
+ async function takeRsvgSlot(): Promise<void> {
219
+ if (activeRsvgSlots < RSVG_SLOTS) {
220
+ activeRsvgSlots++
221
+ return
222
+ }
223
+ await new Promise<void>(resolve => waitingForRsvgSlot.push(resolve))
224
+ }
225
+
226
+ function releaseRsvgSlot(): void {
227
+ const next = waitingForRsvgSlot.shift()
228
+ if (next !== undefined)
229
+ next()
230
+ else
231
+ activeRsvgSlots--
232
+ }
233
+
193
234
  let magickCache: { path: string | undefined, available: boolean } | undefined
194
- let rsvgCache: { path: string | undefined, available: boolean } | undefined
235
+ let rsvgCache: { path: string | undefined, available: boolean, bin: string } | undefined
195
236
 
196
237
  export function hasMagick(): boolean {
197
238
  const envPath = process.env.PATH
@@ -202,18 +243,74 @@ export function hasMagick(): boolean {
202
243
 
203
244
  export function hasRsvgConvert(): boolean {
204
245
  const envPath = process.env.PATH
205
- if (rsvgCache === undefined || rsvgCache.path !== envPath)
206
- rsvgCache = { path: envPath, available: (envPath ?? '') !== '' && Bun.which('rsvg-convert', { PATH: envPath! }) !== null }
246
+ if (rsvgCache === undefined || rsvgCache.path !== envPath) {
247
+ const resolved = (envPath ?? '') !== '' ? Bun.which('rsvg-convert', { PATH: envPath! }) : null
248
+ rsvgCache = { path: envPath, available: resolved !== null, bin: resolved ?? 'rsvg-convert' }
249
+ }
207
250
  return rsvgCache.available
208
251
  }
209
252
 
210
- /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, works on read-only FS). */
211
- export async function rasterizeSvgToPngBytesAsync(svg: string): Promise<Uint8Array<ArrayBuffer> | undefined> {
253
+ async function readStreamChunks(reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer>> {
254
+ const chunks: Uint8Array<ArrayBuffer>[] = []
255
+ let total = 0
256
+ while (true) {
257
+ const { done, value } = await reader.read()
258
+ if (done)
259
+ break
260
+ chunks.push(value)
261
+ total += value.byteLength
262
+ }
263
+ if (chunks.length === 1)
264
+ return chunks[0]!
265
+ const out = new Uint8Array(total)
266
+ let offset = 0
267
+ for (const chunk of chunks) {
268
+ out.set(chunk, offset)
269
+ offset += chunk.byteLength
270
+ }
271
+ return out
272
+ }
273
+
274
+ async function runRsvgConvert(svg: string, timeoutMs: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
275
+ const bin = rsvgCache?.bin ?? 'rsvg-convert'
276
+ await takeRsvgSlot()
277
+ try {
278
+ const proc = Bun.spawn([bin], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore', timeout: timeoutMs, killSignal: 'SIGKILL' })
279
+ const reader = proc.stdout.getReader()
280
+ let timedOut = false
281
+ const timer = setTimeout(() => {
282
+ timedOut = true
283
+ if (!proc.killed)
284
+ proc.kill('SIGKILL')
285
+ void reader.cancel()
286
+ }, timeoutMs)
287
+ try {
288
+ const [exitCode, bytes] = await Promise.all([
289
+ proc.exited,
290
+ readStreamChunks(reader).catch(() => new Uint8Array(0)),
291
+ ])
292
+ if (!timedOut && proc.signalCode !== 'SIGKILL' && exitCode === 0 && bytes.byteLength > 8)
293
+ return bytes
294
+ return undefined
295
+ }
296
+ finally {
297
+ clearTimeout(timer)
298
+ }
299
+ }
300
+ finally {
301
+ releaseRsvgSlot()
302
+ }
303
+ }
304
+
305
+ /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, bounded concurrency & timeout). */
306
+ export async function rasterizeSvgToPngBytesAsync(
307
+ svg: string,
308
+ options?: { timeoutMs?: number | undefined },
309
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
212
310
  if (hasRsvgConvert()) {
213
- const proc = Bun.spawn(['rsvg-convert'], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore' })
214
- const [exitCode, buf] = await Promise.all([proc.exited, new Response(proc.stdout).arrayBuffer()])
215
- if (exitCode === 0 && buf.byteLength > 8)
216
- return new Uint8Array(buf)
311
+ const png = await runRsvgConvert(svg, options?.timeoutMs ?? RSVG_TIMEOUT_MS)
312
+ if (png !== undefined)
313
+ return png
217
314
  }
218
315
  if (hasMagick()) {
219
316
  const result = await runMagick(['svg:-', 'png:-'], new Response(svg))
@@ -232,7 +329,7 @@ export async function encodeVariantToBytesAsync(
232
329
  ): Promise<Uint8Array<ArrayBuffer> | undefined> {
233
330
  if (!hasMagick())
234
331
  return undefined
235
- const result = await runMagick([`${srcPath}[0]`, '-auto-orient', '-strip', '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
332
+ const result = await runMagick([`${srcPath}[0]`, '-auto-orient', ...DROP_METADATA_KEEP_ICC, '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
236
333
  if (result.ok && result.stdout.byteLength > 0)
237
334
  return result.stdout
238
335
  return undefined