@prunellejs/images 0.0.0-stage → 0.7.2

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/runtime.ts ADDED
@@ -0,0 +1,336 @@
1
+ // In-memory runtime image store, non-blocking Bun.spawn encoders, and build-phase task coordination for @prunellejs/images.
2
+
3
+ import type { ServerPluginAPI } from 'prunelle/config'
4
+ import { serviceKey } from 'prunelle/config'
5
+ import { MIN_IMG_ENTRIES, MIN_OG_ENTRIES } from './cache'
6
+ import { DROP_METADATA_KEEP_ICC, runMagick } from './pipeline'
7
+
8
+ export interface RuntimeImagePayload {
9
+ body: Uint8Array<ArrayBuffer> | string
10
+ contentType: string
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
14
+ }
15
+
16
+ interface LazyEntry {
17
+ resolved?: RuntimeImagePayload | undefined
18
+ pending?: Promise<RuntimeImagePayload | undefined> | undefined
19
+ load?: (() => Promise<RuntimeImagePayload | undefined>) | undefined
20
+ }
21
+
22
+ export interface RuntimeImageStore {
23
+ setStatic(pathname: string, body: Uint8Array<ArrayBuffer> | string, contentType: string): void
24
+ setLazy(pathname: string, load: () => Promise<RuntimeImagePayload | undefined>): void
25
+ has(pathname: string): boolean
26
+ serve(pathname: string, request: Request): Promise<Response | undefined>
27
+ }
28
+
29
+ export const RUNTIME_IMAGE_STORE_SERVICE = serviceKey<RuntimeImageStore>('prunelle.images.runtimeStore')
30
+
31
+ const IMAGE_MIME: Record<string, string> = {
32
+ '.png': 'image/png',
33
+ '.jpg': 'image/jpeg',
34
+ '.jpeg': 'image/jpeg',
35
+ '.webp': 'image/webp',
36
+ '.avif': 'image/avif',
37
+ '.gif': 'image/gif',
38
+ '.svg': 'image/svg+xml',
39
+ '.ico': 'image/x-icon',
40
+ '.bmp': 'image/bmp',
41
+ '.tiff': 'image/tiff',
42
+ '.tif': 'image/tiff',
43
+ }
44
+
45
+ export function mimeForImageExt(ext: string): string {
46
+ return IMAGE_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
47
+ }
48
+
49
+ export function computeEtag(body: Uint8Array | string): string {
50
+ return `W/"${Bun.hash(body).toString(36)}"`
51
+ }
52
+
53
+ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
54
+ if (!ifNoneMatch)
55
+ return false
56
+ const trimmed = ifNoneMatch.trim()
57
+ if (trimmed === '*')
58
+ return true
59
+ const strip = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
60
+ const target = strip(etag)
61
+ return trimmed.split(',').some(part => strip(part.trim()) === target)
62
+ }
63
+
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
+ }
74
+
75
+ function put(pathname: string, entry: LazyEntry): void {
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()
81
+ if (!oldest.done)
82
+ map.delete(oldest.value)
83
+ }
84
+ }
85
+
86
+ return {
87
+ setStatic(pathname, body, contentType) {
88
+ put(pathname, { resolved: { body, contentType, etag: computeEtag(body) } })
89
+ },
90
+ setLazy(pathname, load) {
91
+ const { map } = bucketFor(pathname)
92
+ if (map.has(pathname))
93
+ return
94
+ put(pathname, { load })
95
+ },
96
+ has(pathname) {
97
+ return bucketFor(pathname).map.has(pathname)
98
+ },
99
+ async serve(pathname, request) {
100
+ const { map } = bucketFor(pathname)
101
+ const entry = map.get(pathname)
102
+ if (entry === undefined)
103
+ return undefined
104
+ // Refresh LRU position
105
+ map.delete(pathname)
106
+ map.set(pathname, entry)
107
+
108
+ let payload = entry.resolved
109
+ if (payload === undefined && entry.load !== undefined) {
110
+ entry.pending ??= entry.load().then((res) => {
111
+ if (res !== undefined && !res.fallback) {
112
+ entry.resolved = res
113
+ entry.load = undefined
114
+ }
115
+ entry.pending = undefined
116
+ return res
117
+ }).catch(() => {
118
+ entry.pending = undefined
119
+ return undefined
120
+ })
121
+ payload = await entry.pending
122
+ }
123
+ if (payload === undefined)
124
+ return undefined
125
+
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))
137
+ return new Response(null, { status: 304, headers })
138
+ if (request.method === 'HEAD')
139
+ return new Response(null, { status: 200, headers })
140
+ return new Response(payload.body, { status: 200, headers })
141
+ },
142
+ }
143
+ }
144
+
145
+ export function registerRuntimeImageMiddleware(api: ServerPluginAPI, store: RuntimeImageStore): void {
146
+ const serveRuntime = async (ctx: { request: Request, url: URL }, next: () => Promise<Response>): Promise<Response> => {
147
+ if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
148
+ const served = await store.serve(ctx.url.pathname, ctx.request)
149
+ if (served !== undefined)
150
+ return served
151
+ }
152
+ return next()
153
+ }
154
+ api.use(serveRuntime, { scope: '/og' })
155
+ api.use(serveRuntime, { scope: '/img' })
156
+ }
157
+
158
+ // Build-phase coordination shared across native and bundled copies of @prunellejs/images in the same process.
159
+ interface BuildPhaseState {
160
+ activeOutDirs: Set<string>
161
+ tasks: Map<string, Promise<void>[]>
162
+ }
163
+
164
+ const BUILD_STATE_KEY = Symbol.for('pru.images.buildState')
165
+
166
+ function buildState(): BuildPhaseState {
167
+ const g = globalThis as Record<symbol, BuildPhaseState | undefined>
168
+ return (g[BUILD_STATE_KEY] ??= { activeOutDirs: new Set(), tasks: new Map() })
169
+ }
170
+
171
+ export function enterBuildPhase(outDir: string): void {
172
+ buildState().activeOutDirs.add(outDir)
173
+ }
174
+
175
+ export function leaveBuildPhase(outDir: string): void {
176
+ const state = buildState()
177
+ state.activeOutDirs.delete(outDir)
178
+ state.tasks.delete(outDir)
179
+ }
180
+
181
+ export function isBuildPhase(outDir: string): boolean {
182
+ return buildState().activeOutDirs.has(outDir)
183
+ }
184
+
185
+ export function queueBuildTask(outDir: string, task: Promise<void>): void {
186
+ const state = buildState()
187
+ let list = state.tasks.get(outDir)
188
+ if (list === undefined) {
189
+ list = []
190
+ state.tasks.set(outDir, list)
191
+ }
192
+ list.push(task)
193
+ }
194
+
195
+ export async function flushBuildPhase(outDir: string): Promise<void> {
196
+ const state = buildState()
197
+ try {
198
+ while (true) {
199
+ const pending = state.tasks.get(outDir)
200
+ if (pending === undefined || pending.length === 0)
201
+ break
202
+ state.tasks.set(outDir, [])
203
+ await Promise.all(pending)
204
+ }
205
+ }
206
+ finally {
207
+ state.activeOutDirs.delete(outDir)
208
+ state.tasks.delete(outDir)
209
+ }
210
+ }
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
+
234
+ let magickCache: { path: string | undefined, available: boolean } | undefined
235
+ let rsvgCache: { path: string | undefined, available: boolean, bin: string } | undefined
236
+
237
+ export function hasMagick(): boolean {
238
+ const envPath = process.env.PATH
239
+ if (magickCache === undefined || magickCache.path !== envPath)
240
+ magickCache = { path: envPath, available: (envPath ?? '') !== '' && Bun.which('magick', { PATH: envPath! }) !== null }
241
+ return magickCache.available
242
+ }
243
+
244
+ export function hasRsvgConvert(): boolean {
245
+ const envPath = process.env.PATH
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
+ }
250
+ return rsvgCache.available
251
+ }
252
+
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> {
310
+ if (hasRsvgConvert()) {
311
+ const png = await runRsvgConvert(svg, options?.timeoutMs ?? RSVG_TIMEOUT_MS)
312
+ if (png !== undefined)
313
+ return png
314
+ }
315
+ if (hasMagick()) {
316
+ const result = await runMagick(['svg:-', 'png:-'], new Response(svg))
317
+ if (result.ok && result.stdout.byteLength > 8)
318
+ return result.stdout
319
+ }
320
+ return undefined
321
+ }
322
+
323
+ /** Non-blocking image variant encoding via stdout pipe (zero temp files, works on read-only FS). */
324
+ export async function encodeVariantToBytesAsync(
325
+ srcPath: string,
326
+ width: number,
327
+ format: 'avif' | 'webp',
328
+ quality: number,
329
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
330
+ if (!hasMagick())
331
+ return undefined
332
+ const result = await runMagick([`${srcPath}[0]`, '-auto-orient', ...DROP_METADATA_KEEP_ICC, '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
333
+ if (result.ok && result.stdout.byteLength > 0)
334
+ return result.stdout
335
+ return undefined
336
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.