@prunellejs/images 0.0.0-stage → 0.5.3

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/src/plugin.ts ADDED
@@ -0,0 +1,429 @@
1
+ // @prunellejs/images — Build-time AVIF/WebP responsive image optimization with content-hashed disk cache.
2
+ // Built strictly on the public PrunellePlugin API (bunPlugins + build(ctx).emitAsset).
3
+
4
+ import type { BunPlugin } from 'bun'
5
+ import type { PrunellePlugin } from 'prunelle/config'
6
+ import type { ShareCardDefaults } from './card'
7
+ import type { ImageAsset } from './helpers'
8
+ import type { CachedImageMeta, VariantPipelineConfig } from './pipeline'
9
+ import type { RuntimeImageStore } from './runtime'
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { dirname, extname, join, resolve } from 'node:path'
12
+ import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle/config'
13
+ import { getAppContext } from 'prunelle/internal/server'
14
+ import { SHARE_CARD_CONFIG_SERVICE } from './card'
15
+ import { readImageDimensions } from './dimensions'
16
+ import {
17
+ ALLOWED_IMAGE_EXTS,
18
+ assembleImageAsset,
19
+ computeImageKey,
20
+ encodeVariants,
21
+ identifyImageAsync,
22
+
23
+
24
+ planVariantJobs,
25
+ readCachedMeta,
26
+ writeFileAtomic,
27
+ } from './pipeline'
28
+ import {
29
+ computeEtag,
30
+ createRuntimeImageStore,
31
+ encodeVariantToBytesAsync,
32
+ enterBuildPhase,
33
+ flushBuildPhase,
34
+ hasMagick,
35
+ isBuildPhase,
36
+ leaveBuildPhase,
37
+ mimeForImageExt,
38
+ queueBuildTask,
39
+ registerRuntimeImageMiddleware,
40
+ RUNTIME_IMAGE_STORE_SERVICE,
41
+ } from './runtime'
42
+
43
+ export { CONTENT_IMAGE_RESOLVER_SERVICE }
44
+
45
+ export interface ImagesPluginOptions {
46
+ widths?: number[] | undefined
47
+ formats?: ('avif' | 'webp')[] | undefined
48
+ quality?: number | undefined
49
+ avifQuality?: number | undefined
50
+ cacheDir?: string | undefined
51
+ /** Remove stale cache files unused by the current build (default: true). */
52
+ pruneCache?: boolean | undefined
53
+ /** Optional defaults for build-time `shareCard()` OG image generation. */
54
+ card?: ShareCardDefaults | undefined
55
+ /** Default `sizes` attribute for relative images auto-optimized inside `@prunellejs/content` Markdown. */
56
+ markdownSizes?: string | undefined
57
+ }
58
+
59
+ const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
60
+ const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
61
+ 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
+
63
+ interface PersistedImagesConfig {
64
+ cacheDirRel: string
65
+ widths: number[]
66
+ formats: ('avif' | 'webp')[]
67
+ quality: number
68
+ avifQuality: number
69
+ markdownSizes?: string | undefined
70
+ card?: ShareCardDefaults | undefined
71
+ }
72
+
73
+ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
74
+ const widths = (options.widths ?? DEFAULT_WIDTHS).slice().sort((a, b) => a - b)
75
+ const formats = options.formats ?? DEFAULT_FORMATS
76
+ const quality = options.quality ?? 80
77
+ const avifQuality = options.avifQuality ?? 55
78
+ const cacheDirRel = options.cacheDir ?? '.prunelle-cache/images'
79
+ const pruneCache = options.pruneCache ?? true
80
+
81
+ const emittedAssets = new Map<string, Uint8Array>()
82
+ const activeCacheFiles = new Set<string>()
83
+ let lastCacheRoot: string | undefined
84
+ let warnedMissingMagick = false
85
+
86
+ function warnMissingMagickOnce(): void {
87
+ if (!warnedMissingMagick) {
88
+ warnedMissingMagick = true
89
+ console.warn(MISSING_MAGICK_MESSAGE)
90
+ }
91
+ }
92
+
93
+ return definePlugin({
94
+ name: '@prunellejs/images',
95
+ check(ctx) {
96
+ if (!hasMagick())
97
+ ctx.error(MISSING_MAGICK_MESSAGE)
98
+ },
99
+ bunPlugins: ({ root, assetPrefix }): BunPlugin[] => {
100
+ const cacheRoot = resolve(root, cacheDirRel)
101
+ lastCacheRoot = cacheRoot
102
+ const prefix = assetPrefix.replace(/\/$/, '')
103
+ const pipelineCfg: VariantPipelineConfig = { widths, formats, quality, avifQuality, cachePrefix: '' }
104
+ const magickAvailable = hasMagick()
105
+ if (!magickAvailable)
106
+ warnMissingMagickOnce()
107
+
108
+ return [{
109
+ name: 'prunelle-images',
110
+ setup(b) {
111
+ b.onLoad({ filter: /\.(?:png|jpe?g|webp|avif)$/i }, async (args) => {
112
+ if (args.path.includes('/node_modules/'))
113
+ return undefined
114
+
115
+ const rawBytes = new Uint8Array(readFileSync(args.path))
116
+ const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
117
+ const emitRaw = (width: number, height: number) => {
118
+ const rel = `img/${rawFileName}`
119
+ emittedAssets.set(rel, rawBytes)
120
+ const asset: ImageAsset = { src: `${prefix}/${rel}`, width, height }
121
+ return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' as const }
122
+ }
123
+
124
+ if (!magickAvailable) {
125
+ const dims = readImageDimensions(rawBytes)
126
+ if (dims === undefined)
127
+ throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}" (ImageMagick is unavailable and binary header could not be parsed)`)
128
+ return emitRaw(dims.width, dims.height)
129
+ }
130
+
131
+ mkdirSync(cacheRoot, { recursive: true })
132
+ const metaName = `${stem}-${hash}.json`
133
+ const metaPath = join(cacheRoot, metaName)
134
+ activeCacheFiles.add(metaName)
135
+ let meta = readCachedMeta(metaPath, cacheRoot, '')
136
+
137
+ if (meta === undefined) {
138
+ const dims = readImageDimensions(rawBytes) ?? await identifyImageAsync(args.path)
139
+ if (dims === undefined)
140
+ throw new Error(`@prunellejs/images: could not determine dimensions for "${args.path}"`)
141
+
142
+ const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
143
+ const encoded = await encodeVariants(args.path, jobs)
144
+ const files: CachedImageMeta['files'] = encoded.map(job => ({ rel: `img/${job.fileName}`, width: job.width, format: job.format }))
145
+ if (files.length === 0)
146
+ return emitRaw(dims.width, dims.height)
147
+
148
+ meta = { width: dims.width, height: dims.height, files }
149
+ // Kept only once every variant is in: a variant left out by a failed run is tried again by the next build.
150
+ if (files.length === jobs.length)
151
+ writeFileAtomic(metaPath, JSON.stringify(meta))
152
+ }
153
+
154
+ const asset = assembleImageAsset(meta, cacheRoot, '', prefix, (rel, fileName, cachedFile) => {
155
+ activeCacheFiles.add(fileName)
156
+ if (!emittedAssets.has(rel))
157
+ emittedAssets.set(rel, new Uint8Array(readFileSync(cachedFile)))
158
+ })
159
+ return { contents: `export default ${JSON.stringify(asset)};\n`, loader: 'js' }
160
+ })
161
+ },
162
+ }]
163
+ },
164
+ build(ctx) {
165
+ enterBuildPhase(ctx.outDir)
166
+ const publicDir = join(ctx.outDir, 'public')
167
+ const cacheDir = resolve(ctx.root, cacheDirRel)
168
+ const cardWithSite: ShareCardDefaults | undefined = options.card !== undefined || ctx.site !== undefined
169
+ ? { ...(ctx.site !== undefined ? { site: ctx.site } : {}), ...options.card }
170
+ : undefined
171
+ const persisted: PersistedImagesConfig = {
172
+ cacheDirRel,
173
+ widths,
174
+ formats,
175
+ quality,
176
+ avifQuality,
177
+ markdownSizes: options.markdownSizes,
178
+ card: cardWithSite,
179
+ }
180
+ ctx.setData(persisted as unknown as Record<string, unknown>)
181
+ ctx.provide(SHARE_CARD_CONFIG_SERVICE, { ...cardWithSite, publicDir, cacheDir } satisfies ShareCardDefaults)
182
+ ctx.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({
183
+ root: resolve(ctx.root),
184
+ outPublicDir: publicDir,
185
+ cacheDir,
186
+ widths,
187
+ formats,
188
+ quality,
189
+ avifQuality,
190
+ sizes: options.markdownSizes,
191
+ }))
192
+ for (const [rel, bytes] of emittedAssets)
193
+ ctx.emitAsset(rel, bytes)
194
+ if (pruneCache && !ctx.dev && lastCacheRoot !== undefined && activeCacheFiles.size > 0 && existsSync(lastCacheRoot)) {
195
+ for (const entry of readdirSync(lastCacheRoot)) {
196
+ if (!entry.startsWith('og-') && !entry.startsWith('md-') && !activeCacheFiles.has(entry))
197
+ rmSync(join(lastCacheRoot, entry), { force: true })
198
+ }
199
+ }
200
+ emittedAssets.clear()
201
+ activeCacheFiles.clear()
202
+ },
203
+ async afterPrerender(ctx) {
204
+ await flushBuildPhase(ctx.outDir)
205
+ },
206
+ server(api) {
207
+ const persisted = api.getBuildData<PersistedImagesConfig>()
208
+ const publicDir = join(api.outDir, 'public')
209
+ const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
210
+ const runtimeStore = createRuntimeImageStore()
211
+ api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
212
+ registerRuntimeImageMiddleware(api, runtimeStore)
213
+ api.onShutdown(() => {
214
+ if (isBuildPhase(api.outDir))
215
+ leaveBuildPhase(api.outDir)
216
+ })
217
+ api.provide(SHARE_CARD_CONFIG_SERVICE, {
218
+ ...(api.site !== undefined ? { site: api.site } : {}),
219
+ ...(persisted?.card ?? options.card),
220
+ publicDir,
221
+ cacheDir,
222
+ } satisfies ShareCardDefaults)
223
+ api.provide(CONTENT_IMAGE_RESOLVER_SERVICE, createMarkdownImageResolver({
224
+ root: resolve(api.root),
225
+ cacheDir,
226
+ widths: persisted?.widths ?? widths,
227
+ formats: persisted?.formats ?? formats,
228
+ quality: persisted?.quality ?? quality,
229
+ avifQuality: persisted?.avifQuality ?? avifQuality,
230
+ sizes: persisted?.markdownSizes ?? options.markdownSizes,
231
+ }))
232
+ },
233
+ })
234
+ }
235
+
236
+ export interface OptimizeImageFileOptions {
237
+ outPublicDir?: string | undefined
238
+ cacheDir?: string | undefined
239
+ widths?: number[] | undefined
240
+ formats?: ('avif' | 'webp')[] | undefined
241
+ quality?: number | undefined
242
+ avifQuality?: number | undefined
243
+ }
244
+
245
+ function optimizeForRuntime(
246
+ absPath: string,
247
+ ext: string,
248
+ rawBytes: Uint8Array<ArrayBuffer>,
249
+ dims: { width: number, height: number },
250
+ stem: string,
251
+ hash: string,
252
+ rawFileName: string,
253
+ cacheRoot: string,
254
+ pipelineCfg: VariantPipelineConfig,
255
+ runtimeStore: RuntimeImageStore,
256
+ ): ImageAsset {
257
+ const rawMime = mimeForImageExt(ext)
258
+ if (!hasMagick()) {
259
+ runtimeStore.setStatic(`/img/${rawFileName}`, rawBytes, rawMime)
260
+ return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
261
+ }
262
+ const metaPath = join(cacheRoot, `md-${stem}-${hash}.json`)
263
+ const cachedMeta = readCachedMeta(metaPath, cacheRoot, 'md-')
264
+ if (cachedMeta !== undefined) {
265
+ return assembleImageAsset(cachedMeta, cacheRoot, 'md-', '', (_rel, fileName, cachedFile) => {
266
+ const mime = mimeForImageExt(extname(fileName))
267
+ runtimeStore.setLazy(`/img/${fileName}`, async () => {
268
+ try {
269
+ const bytes = new Uint8Array(await Bun.file(cachedFile).arrayBuffer())
270
+ return { body: bytes, contentType: mime, etag: computeEtag(bytes) }
271
+ }
272
+ catch {
273
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
274
+ }
275
+ })
276
+ })
277
+ }
278
+ const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
279
+ const plannedMeta: CachedImageMeta = {
280
+ width: dims.width,
281
+ height: dims.height,
282
+ files: jobs.map(j => ({ rel: `img/${j.fileName}`, width: j.width, format: j.format })),
283
+ }
284
+ const jobByFile = new Map(jobs.map(j => [j.fileName, j]))
285
+ return assembleImageAsset(plannedMeta, cacheRoot, 'md-', '', (_rel, fileName) => {
286
+ const job = jobByFile.get(fileName)!
287
+ const targetMime = mimeForImageExt(`.${job.format}`)
288
+ runtimeStore.setLazy(`/img/${fileName}`, async () => {
289
+ const encoded = await encodeVariantToBytesAsync(absPath, job.width, job.format, job.quality)
290
+ if (encoded !== undefined)
291
+ return { body: encoded, contentType: targetMime, etag: computeEtag(encoded) }
292
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
293
+ })
294
+ })
295
+ }
296
+
297
+ /** Optimize a local image file (e.g. from Markdown) with non-blocking encoding and runtime in-memory serving for --compile. */
298
+ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOptions = {}): ImageAsset {
299
+ const ext = extname(absPath).toLowerCase()
300
+ if (!ALLOWED_IMAGE_EXTS.has(ext))
301
+ throw new Error(`@prunellejs/images: unsupported image extension "${ext || '(none)'}" for "${absPath}"`)
302
+
303
+ const pipelineCfg: VariantPipelineConfig = {
304
+ widths: (options.widths ?? [640, 1280]).slice().sort((a, b) => a - b),
305
+ formats: options.formats ?? ['webp'],
306
+ quality: options.quality ?? 80,
307
+ avifQuality: options.avifQuality ?? 55,
308
+ cachePrefix: 'md-',
309
+ }
310
+ const appCtx = getAppContext()
311
+ const rawBytes = new Uint8Array(readFileSync(absPath))
312
+ const dims = readImageDimensions(rawBytes)
313
+ if (dims === undefined)
314
+ throw new Error(`@prunellejs/images: could not determine dimensions for "${absPath}"`)
315
+
316
+ const { hash, stem, rawFileName } = computeImageKey(absPath, rawBytes, pipelineCfg)
317
+ const cacheRoot = resolve(options.cacheDir ?? '.prunelle-cache/images')
318
+ const inBuild = appCtx !== undefined && isBuildPhase(appCtx.outDir)
319
+
320
+ // Runtime server mode (including --compile): never write to dist/public or block on Bun.spawnSync.
321
+ const runtimeStore = options.outPublicDir === undefined ? appCtx?.inject(RUNTIME_IMAGE_STORE_SERVICE) : undefined
322
+ if (runtimeStore !== undefined && !inBuild)
323
+ return optimizeForRuntime(absPath, ext, rawBytes, dims, stem, hash, rawFileName, cacheRoot, pipelineCfg, runtimeStore)
324
+
325
+ const outPublicDir = resolve(options.outPublicDir ?? appCtx?.publicDir ?? 'dist/public')
326
+ const imgOutDir = join(outPublicDir, 'img')
327
+ mkdirSync(imgOutDir, { recursive: true })
328
+ const emitRaw = (): ImageAsset => {
329
+ writeFileSync(join(imgOutDir, rawFileName), rawBytes)
330
+ appCtx?.registerPublicFile(`img/${rawFileName}`)
331
+ return { src: `/img/${rawFileName}`, width: dims.width, height: dims.height }
332
+ }
333
+
334
+ if (!hasMagick())
335
+ return emitRaw()
336
+
337
+ const metaPath = join(cacheRoot, `md-${stem}-${hash}.json`)
338
+ const cachedMeta = readCachedMeta(metaPath, cacheRoot, 'md-')
339
+ if (cachedMeta !== undefined) {
340
+ return assembleImageAsset(cachedMeta, cacheRoot, 'md-', '', (_rel, fileName, cachedFile) => {
341
+ writeFileSync(join(imgOutDir, fileName), readFileSync(cachedFile))
342
+ appCtx?.registerPublicFile(`img/${fileName}`)
343
+ })
344
+ }
345
+
346
+ if (!inBuild)
347
+ return emitRaw()
348
+
349
+ // Build / prerender mode: queue non-blocking async Bun.spawn encoding and flush in afterPrerender().
350
+ const jobs = planVariantJobs(dims, stem, hash, cacheRoot, pipelineCfg)
351
+ const plannedMeta: CachedImageMeta = {
352
+ width: dims.width,
353
+ height: dims.height,
354
+ files: jobs.map(j => ({ rel: `img/${j.fileName}`, width: j.width, format: j.format })),
355
+ }
356
+ queueBuildTask(appCtx.outDir, (async () => {
357
+ mkdirSync(cacheRoot, { recursive: true })
358
+ mkdirSync(imgOutDir, { recursive: true })
359
+ const encoded = await encodeVariants(absPath, jobs)
360
+ for (const job of encoded)
361
+ writeFileSync(join(imgOutDir, job.fileName), readFileSync(job.cachedFile))
362
+ const files = encoded.map(job => ({ rel: `img/${job.fileName}`, width: job.width, format: job.format }))
363
+ if (files.length === jobs.length)
364
+ writeFileAtomic(metaPath, JSON.stringify({ width: dims.width, height: dims.height, files }))
365
+ })())
366
+ return assembleImageAsset(plannedMeta, cacheRoot, 'md-', '', (_rel, fileName) => {
367
+ appCtx.registerPublicFile(`img/${fileName}`)
368
+ })
369
+ }
370
+
371
+ export interface MarkdownImageResolverOptions extends OptimizeImageFileOptions {
372
+ sizes?: string | undefined
373
+ /** Project root boundary confining resolved relative Markdown image paths. */
374
+ root?: string | undefined
375
+ }
376
+
377
+ /** Creates a `@prunellejs/content` `resolveImage` function backed by `optimizeImageFile()`. Automatically wired by `images()`. */
378
+ export function createMarkdownImageResolver(options: MarkdownImageResolverOptions = {}) {
379
+ const sizes = options.sizes ?? '(min-width: 48rem) 42rem, 100vw'
380
+ return (src: string, file: string | undefined) => {
381
+ if (!file || !src.startsWith('.'))
382
+ return undefined
383
+ const absFile = resolve(file)
384
+ let boundary: string
385
+ if (options.root !== undefined) {
386
+ boundary = resolve(options.root)
387
+ }
388
+ else {
389
+ const prunelleRoot = getAppContext()?.root
390
+ boundary = (typeof prunelleRoot === 'string' && prunelleRoot !== '' && isInside(resolve(prunelleRoot), absFile))
391
+ ? resolve(prunelleRoot)
392
+ : dirname(absFile)
393
+ }
394
+
395
+ const abs = resolve(dirname(absFile), src)
396
+ if (!isInside(boundary, abs))
397
+ return undefined
398
+ if (!ALLOWED_IMAGE_EXTS.has(extname(abs).toLowerCase()))
399
+ return undefined
400
+ if (!existsSync(abs))
401
+ return undefined
402
+
403
+ let realBoundary: string
404
+ let realTarget: string
405
+ try {
406
+ realBoundary = realpathSync(boundary)
407
+ realTarget = realpathSync(abs)
408
+ }
409
+ catch {
410
+ return undefined
411
+ }
412
+ if (!isInside(realBoundary, realTarget))
413
+ return undefined
414
+ if (!ALLOWED_IMAGE_EXTS.has(extname(realTarget).toLowerCase()))
415
+ return undefined
416
+
417
+ const asset = optimizeImageFile(realTarget, options)
418
+ const srcset = asset.webpSrcset ?? asset.avifSrcset
419
+ return {
420
+ src: asset.src,
421
+ ...(srcset !== undefined ? { srcset } : {}),
422
+ ...(asset.avifSrcset !== undefined && asset.webpSrcset !== undefined ? { avifSrcset: asset.avifSrcset } : {}),
423
+ ...(srcset !== undefined ? { sizes } : {}),
424
+ width: asset.width,
425
+ height: asset.height,
426
+ loading: 'lazy' as const,
427
+ }
428
+ }
429
+ }