@prunellejs/images 0.1.1 → 0.6.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/images",
3
- "version": "0.1.1",
3
+ "version": "0.6.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.6.0"
26
26
  }
27
27
  }
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
  }
@@ -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
  }
package/src/plugin.ts CHANGED
@@ -270,7 +270,7 @@ function optimizeForRuntime(
270
270
  return { body: bytes, contentType: mime, etag: computeEtag(bytes) }
271
271
  }
272
272
  catch {
273
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
273
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
274
274
  }
275
275
  })
276
276
  })
@@ -289,7 +289,7 @@ function optimizeForRuntime(
289
289
  const encoded = await encodeVariantToBytesAsync(absPath, job.width, job.format, job.quality)
290
290
  if (encoded !== undefined)
291
291
  return { body: encoded, contentType: targetMime, etag: computeEtag(encoded) }
292
- return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes) }
292
+ return { body: rawBytes, contentType: rawMime, etag: computeEtag(rawBytes), fallback: true }
293
293
  })
294
294
  })
295
295
  }
package/src/runtime.ts CHANGED
@@ -8,6 +8,8 @@ export interface RuntimeImagePayload {
8
8
  body: Uint8Array<ArrayBuffer> | string
9
9
  contentType: string
10
10
  etag: string
11
+ /** Marks a transient fallback payload: served with `Cache-Control: no-store` and never pinned to `entry.resolved`. */
12
+ fallback?: boolean | undefined
11
13
  }
12
14
 
13
15
  interface LazyEntry {
@@ -58,16 +60,26 @@ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
58
60
  return trimmed.split(',').some(part => strip(part.trim()) === target)
59
61
  }
60
62
 
61
- export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
62
- const entries = new Map<string, LazyEntry>()
63
+ export function createRuntimeImageStore(maxOgEntries = 256): RuntimeImageStore {
64
+ // Keep dynamic `/og/` share cards in a bounded LRU separate from the `/img/` asset store
65
+ // 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>, bounded: boolean } {
70
+ return pathname.startsWith('/og/')
71
+ ? { map: ogEntries, bounded: true }
72
+ : { map: imgEntries, bounded: false }
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, bounded } = bucketFor(pathname)
77
+ map.delete(pathname)
78
+ map.set(pathname, entry)
79
+ if (bounded && map.size > maxOgEntries) {
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,29 @@ 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, bounded } = bucketFor(pathname)
101
+ const entry = map.get(pathname)
88
102
  if (entry === undefined)
89
103
  return undefined
90
- // Refresh LRU position
91
- entries.delete(pathname)
92
- entries.set(pathname, entry)
104
+ if (bounded) {
105
+ // Refresh LRU position
106
+ map.delete(pathname)
107
+ map.set(pathname, entry)
108
+ }
93
109
 
94
110
  let payload = entry.resolved
95
111
  if (payload === undefined && entry.load !== undefined) {
96
112
  entry.pending ??= entry.load().then((res) => {
97
- if (res !== undefined) {
113
+ if (res !== undefined && !res.fallback) {
98
114
  entry.resolved = res
99
115
  entry.load = undefined
100
116
  }
@@ -109,12 +125,17 @@ export function createRuntimeImageStore(maxEntries = 256): RuntimeImageStore {
109
125
  if (payload === undefined)
110
126
  return undefined
111
127
 
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))
128
+ const headers: Record<string, string> = payload.fallback
129
+ ? {
130
+ 'content-type': payload.contentType,
131
+ 'cache-control': 'no-store',
132
+ }
133
+ : {
134
+ 'content-type': payload.contentType,
135
+ 'cache-control': 'public, max-age=31536000, immutable',
136
+ 'etag': payload.etag,
137
+ }
138
+ if (!payload.fallback && etagMatchesHeader(request.headers.get('if-none-match'), payload.etag))
118
139
  return new Response(null, { status: 304, headers })
119
140
  if (request.method === 'HEAD')
120
141
  return new Response(null, { status: 200, headers })
@@ -190,8 +211,30 @@ export async function flushBuildPhase(outDir: string): Promise<void> {
190
211
  }
191
212
  }
192
213
 
214
+ export const RSVG_SLOTS = 4
215
+ export const RSVG_TIMEOUT_MS = 15_000
216
+
217
+ let activeRsvgSlots = 0
218
+ const waitingForRsvgSlot: (() => void)[] = []
219
+
220
+ async function takeRsvgSlot(): Promise<void> {
221
+ if (activeRsvgSlots < RSVG_SLOTS) {
222
+ activeRsvgSlots++
223
+ return
224
+ }
225
+ await new Promise<void>(resolve => waitingForRsvgSlot.push(resolve))
226
+ }
227
+
228
+ function releaseRsvgSlot(): void {
229
+ const next = waitingForRsvgSlot.shift()
230
+ if (next !== undefined)
231
+ next()
232
+ else
233
+ activeRsvgSlots--
234
+ }
235
+
193
236
  let magickCache: { path: string | undefined, available: boolean } | undefined
194
- let rsvgCache: { path: string | undefined, available: boolean } | undefined
237
+ let rsvgCache: { path: string | undefined, available: boolean, bin: string } | undefined
195
238
 
196
239
  export function hasMagick(): boolean {
197
240
  const envPath = process.env.PATH
@@ -202,18 +245,74 @@ export function hasMagick(): boolean {
202
245
 
203
246
  export function hasRsvgConvert(): boolean {
204
247
  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 }
248
+ if (rsvgCache === undefined || rsvgCache.path !== envPath) {
249
+ const resolved = (envPath ?? '') !== '' ? Bun.which('rsvg-convert', { PATH: envPath! }) : null
250
+ rsvgCache = { path: envPath, available: resolved !== null, bin: resolved ?? 'rsvg-convert' }
251
+ }
207
252
  return rsvgCache.available
208
253
  }
209
254
 
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> {
255
+ async function readStreamChunks(reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer>> {
256
+ const chunks: Uint8Array<ArrayBuffer>[] = []
257
+ let total = 0
258
+ while (true) {
259
+ const { done, value } = await reader.read()
260
+ if (done)
261
+ break
262
+ chunks.push(value)
263
+ total += value.byteLength
264
+ }
265
+ if (chunks.length === 1)
266
+ return chunks[0]!
267
+ const out = new Uint8Array(total)
268
+ let offset = 0
269
+ for (const chunk of chunks) {
270
+ out.set(chunk, offset)
271
+ offset += chunk.byteLength
272
+ }
273
+ return out
274
+ }
275
+
276
+ async function runRsvgConvert(svg: string, timeoutMs: number): Promise<Uint8Array<ArrayBuffer> | undefined> {
277
+ const bin = rsvgCache?.bin ?? 'rsvg-convert'
278
+ await takeRsvgSlot()
279
+ try {
280
+ const proc = Bun.spawn([bin], { stdin: new Response(svg), stdout: 'pipe', stderr: 'ignore', timeout: timeoutMs, killSignal: 'SIGKILL' })
281
+ const reader = proc.stdout.getReader()
282
+ let timedOut = false
283
+ const timer = setTimeout(() => {
284
+ timedOut = true
285
+ if (!proc.killed)
286
+ proc.kill('SIGKILL')
287
+ void reader.cancel()
288
+ }, timeoutMs)
289
+ try {
290
+ const [exitCode, bytes] = await Promise.all([
291
+ proc.exited,
292
+ readStreamChunks(reader).catch(() => new Uint8Array(0)),
293
+ ])
294
+ if (!timedOut && proc.signalCode !== 'SIGKILL' && exitCode === 0 && bytes.byteLength > 8)
295
+ return bytes
296
+ return undefined
297
+ }
298
+ finally {
299
+ clearTimeout(timer)
300
+ }
301
+ }
302
+ finally {
303
+ releaseRsvgSlot()
304
+ }
305
+ }
306
+
307
+ /** Non-blocking SVG->PNG rasterization over stdin/stdout pipes (zero temp files, bounded concurrency & timeout). */
308
+ export async function rasterizeSvgToPngBytesAsync(
309
+ svg: string,
310
+ options?: { timeoutMs?: number | undefined },
311
+ ): Promise<Uint8Array<ArrayBuffer> | undefined> {
212
312
  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)
313
+ const png = await runRsvgConvert(svg, options?.timeoutMs ?? RSVG_TIMEOUT_MS)
314
+ if (png !== undefined)
315
+ return png
217
316
  }
218
317
  if (hasMagick()) {
219
318
  const result = await runMagick(['svg:-', 'png:-'], new Response(svg))