@prunellejs/images 0.0.0-stage → 0.2.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 +53 -0
- package/package.json +25 -4
- package/src/Picture.tsx +24 -0
- package/src/ambient.d.ts +25 -0
- package/src/card.ts +251 -0
- package/src/dimensions.ts +130 -0
- package/src/helpers.ts +46 -0
- package/src/index.ts +10 -0
- package/src/pipeline.ts +282 -0
- package/src/plugin.ts +429 -0
- package/src/runtime.ts +239 -0
- package/README.md +0 -3
package/src/pipeline.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Variant encoding pipeline helpers shared by @prunellejs/images build loader and Markdown image optimizer.
|
|
2
|
+
|
|
3
|
+
import type { ImageAsset } from './helpers'
|
|
4
|
+
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { availableParallelism } from 'node:os'
|
|
6
|
+
import { basename, extname, join } from 'node:path'
|
|
7
|
+
|
|
8
|
+
export const ALLOWED_IMAGE_EXTS = new Set([
|
|
9
|
+
'.png',
|
|
10
|
+
'.jpg',
|
|
11
|
+
'.jpeg',
|
|
12
|
+
'.webp',
|
|
13
|
+
'.avif',
|
|
14
|
+
'.gif',
|
|
15
|
+
'.svg',
|
|
16
|
+
'.ico',
|
|
17
|
+
'.bmp',
|
|
18
|
+
'.tiff',
|
|
19
|
+
'.tif',
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
// Bun runs every image's onLoad at once, so a limit per image multiplies: every magick call takes one of these slots, half the cores and at most 8 for the whole build.
|
|
24
|
+
export const ENCODE_SLOTS = Math.max(1, Math.min(8, Math.floor(availableParallelism() / 2)))
|
|
25
|
+
// One thread and bounded memory each (magick spills to its disk cache past the limit), killed after two minutes.
|
|
26
|
+
const MAGICK_LIMITS = ['-limit', 'thread', '1', '-limit', 'memory', '512MiB', '-limit', 'map', '1GiB']
|
|
27
|
+
const MAGICK_TIMEOUT_MS = 120_000
|
|
28
|
+
|
|
29
|
+
// Resolved from the current PATH, as `hasMagick()` checks it: a bare `magick` would come from the PATH the process started with.
|
|
30
|
+
let magickBin: { path: string | undefined, bin: string } | undefined
|
|
31
|
+
function magickBinary(): string {
|
|
32
|
+
const path = process.env.PATH
|
|
33
|
+
if (magickBin === undefined || magickBin.path !== path)
|
|
34
|
+
magickBin = { path, bin: Bun.which('magick', { PATH: path ?? '' }) ?? 'magick' }
|
|
35
|
+
return magickBin.bin
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let activeSlots = 0
|
|
39
|
+
const waitingForSlot: (() => void)[] = []
|
|
40
|
+
|
|
41
|
+
async function takeSlot(): Promise<void> {
|
|
42
|
+
if (activeSlots < ENCODE_SLOTS) {
|
|
43
|
+
activeSlots++
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
// The caller releasing a slot hands it straight to the next in line.
|
|
47
|
+
await new Promise<void>(resolve => waitingForSlot.push(resolve))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function releaseSlot(): void {
|
|
51
|
+
const next = waitingForSlot.shift()
|
|
52
|
+
if (next !== undefined)
|
|
53
|
+
next()
|
|
54
|
+
else
|
|
55
|
+
activeSlots--
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface MagickResult {
|
|
59
|
+
ok: boolean
|
|
60
|
+
stdout: Uint8Array<ArrayBuffer>
|
|
61
|
+
/** Why it failed: magick's stderr, or the timeout. */
|
|
62
|
+
error: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Runs `magick <args>` in one of the build's slots, with its limits and timeout; stderr is read so a chatty run cannot fill the pipe and stall. */
|
|
66
|
+
export async function runMagick(args: readonly string[], stdin?: Response): Promise<MagickResult> {
|
|
67
|
+
// A subcommand such as `identify` stays first, its options after it.
|
|
68
|
+
const bin = magickBinary()
|
|
69
|
+
const argv = args[0] === 'identify' ? [bin, 'identify', ...MAGICK_LIMITS, ...args.slice(1)] : [bin, ...MAGICK_LIMITS, ...args]
|
|
70
|
+
await takeSlot()
|
|
71
|
+
try {
|
|
72
|
+
const proc = Bun.spawn(argv, { stdin: stdin ?? 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: MAGICK_TIMEOUT_MS, killSignal: 'SIGKILL' })
|
|
73
|
+
const [exitCode, stdout, stderr] = await Promise.all([proc.exited, new Response(proc.stdout).arrayBuffer(), new Response(proc.stderr).text()])
|
|
74
|
+
const error = proc.signalCode === 'SIGKILL' ? `timed out after ${MAGICK_TIMEOUT_MS / 1000} s` : stderr.trim()
|
|
75
|
+
return { ok: exitCode === 0, stdout: new Uint8Array(stdout), error }
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
releaseSlot()
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface CachedImageMeta {
|
|
83
|
+
width: number
|
|
84
|
+
height: number
|
|
85
|
+
files: { rel: string, width: number, format: string }[]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface VariantEncodeJob {
|
|
89
|
+
fileName: string
|
|
90
|
+
cachedFile: string
|
|
91
|
+
width: number
|
|
92
|
+
format: 'avif' | 'webp'
|
|
93
|
+
quality: number
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface VariantPipelineConfig {
|
|
97
|
+
widths: number[]
|
|
98
|
+
formats: ('avif' | 'webp')[]
|
|
99
|
+
quality: number
|
|
100
|
+
avifQuality: number
|
|
101
|
+
cachePrefix: string
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
// EXIF orientations 5 to 8, which `-auto-orient` turns a quarter.
|
|
106
|
+
const QUARTER_TURNS = new Set(['LeftTop', 'RightTop', 'RightBottom', 'LeftBottom'])
|
|
107
|
+
|
|
108
|
+
function parseMagickDimensions(stdout: string): { width: number, height: number } | undefined {
|
|
109
|
+
const parts = stdout.trim().split(/\s+/)
|
|
110
|
+
const w = Number(parts[0])
|
|
111
|
+
const h = Number(parts[1])
|
|
112
|
+
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0)
|
|
113
|
+
return undefined
|
|
114
|
+
return QUARTER_TURNS.has(parts[2] ?? '') ? { width: h, height: w } : { width: w, height: h }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The size the variants will have, after `-auto-orient`, for a file whose header prunelle cannot read. */
|
|
118
|
+
export async function identifyImageAsync(filePath: string): Promise<{ width: number, height: number } | undefined> {
|
|
119
|
+
const result = await runMagick(['identify', '-ping', '-format', '%w %h %[orientation]', `${filePath}[0]`])
|
|
120
|
+
if (!result.ok)
|
|
121
|
+
return undefined
|
|
122
|
+
return parseMagickDimensions(new TextDecoder().decode(result.stdout))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
export function writeFileAtomic(dstPath: string, data: string | Uint8Array): void {
|
|
127
|
+
const tmpPath = `${dstPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
128
|
+
writeFileSync(tmpPath, data)
|
|
129
|
+
try {
|
|
130
|
+
renameSync(tmpPath, dstPath)
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
rmSync(tmpPath, { force: true })
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function variantTmpPath(dstPath: string): string {
|
|
138
|
+
const ext = extname(dstPath)
|
|
139
|
+
const stem = ext !== '' ? dstPath.slice(0, -ext.length) : dstPath
|
|
140
|
+
return `${stem}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}${ext}`
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Writes one format's variants of an image in a single `magick` run: the source is decoded and oriented once, kept as `mpr:src`, and each width resized from it.
|
|
145
|
+
* A run that fails part way keeps the variants it wrote before failing, and warns with the widths it left out.
|
|
146
|
+
*/
|
|
147
|
+
async function encodeFormatAsync(srcPath: string, jobs: readonly VariantEncodeJob[]): Promise<void> {
|
|
148
|
+
const tmpPaths = jobs.map(job => variantTmpPath(job.cachedFile))
|
|
149
|
+
const result = await runMagick([
|
|
150
|
+
`${srcPath}[0]`,
|
|
151
|
+
'-auto-orient',
|
|
152
|
+
'-strip',
|
|
153
|
+
'-write',
|
|
154
|
+
'mpr:src',
|
|
155
|
+
'+delete',
|
|
156
|
+
...jobs.flatMap((job, i) => ['(', 'mpr:src', '-resize', `${job.width}x>`, '-quality', String(job.quality), '-write', tmpPaths[i]!, '+delete', ')']),
|
|
157
|
+
'null:',
|
|
158
|
+
])
|
|
159
|
+
// magick writes the variants in order, so after a failed run only the last file it wrote can be cut short.
|
|
160
|
+
if (!result.ok) {
|
|
161
|
+
const last = tmpPaths.findLastIndex(tmpPath => existsSync(tmpPath))
|
|
162
|
+
if (last !== -1)
|
|
163
|
+
rmSync(tmpPaths[last]!, { force: true })
|
|
164
|
+
}
|
|
165
|
+
const missing: number[] = []
|
|
166
|
+
for (const [i, job] of jobs.entries()) {
|
|
167
|
+
const tmpPath = tmpPaths[i]!
|
|
168
|
+
if (existsSync(tmpPath)) {
|
|
169
|
+
try {
|
|
170
|
+
renameSync(tmpPath, job.cachedFile)
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
rmSync(tmpPath, { force: true })
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (!existsSync(job.cachedFile))
|
|
177
|
+
missing.push(job.width)
|
|
178
|
+
}
|
|
179
|
+
if (missing.length > 0)
|
|
180
|
+
console.warn(`@prunellejs/images: magick could not encode ${srcPath} at ${missing.map(w => `${w}w`).join(', ')} (${jobs[0]!.format}), so those variants are left out: ${result.error || 'no output'}`)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Encodes the jobs not in the cache yet, one `magick` run per format, and returns every job whose file is now in the cache, in plan order. */
|
|
184
|
+
export async function encodeVariants(srcPath: string, jobs: readonly VariantEncodeJob[]): Promise<VariantEncodeJob[]> {
|
|
185
|
+
const byFormat = new Map<VariantEncodeJob['format'], VariantEncodeJob[]>()
|
|
186
|
+
for (const job of jobs) {
|
|
187
|
+
if (existsSync(job.cachedFile))
|
|
188
|
+
continue
|
|
189
|
+
const group = byFormat.get(job.format)
|
|
190
|
+
if (group === undefined)
|
|
191
|
+
byFormat.set(job.format, [job])
|
|
192
|
+
else
|
|
193
|
+
group.push(job)
|
|
194
|
+
}
|
|
195
|
+
await Promise.all([...byFormat.values()].map(group => encodeFormatAsync(srcPath, group)))
|
|
196
|
+
return jobs.filter(job => existsSync(job.cachedFile))
|
|
197
|
+
}
|
|
198
|
+
|
|
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
|
|
201
|
+
|
|
202
|
+
export function computeImageKey(srcPath: string, rawBytes: Uint8Array, cfg: VariantPipelineConfig): { hash: string, stem: string, rawFileName: string } {
|
|
203
|
+
const ext = extname(srcPath).toLowerCase()
|
|
204
|
+
const hash = Bun.hash(`${VARIANT_CACHE_VERSION}:${Bun.hash(rawBytes)}:${cfg.widths.join(',')}:${cfg.formats.join(',')}:${cfg.quality}:${cfg.avifQuality}`).toString(36)
|
|
205
|
+
const stem = basename(srcPath, extname(srcPath)).toLowerCase().replace(/[^a-z0-9-_]/g, '-')
|
|
206
|
+
return { hash, stem, rawFileName: `${stem}-${hash}${ext}` }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function readCachedMeta(metaPath: string, cacheRoot: string, cachePrefix: string): CachedImageMeta | undefined {
|
|
210
|
+
if (!existsSync(metaPath))
|
|
211
|
+
return undefined
|
|
212
|
+
try {
|
|
213
|
+
const parsed = JSON.parse(readFileSync(metaPath, 'utf8')) as CachedImageMeta
|
|
214
|
+
if (parsed.files.every(f => existsSync(join(cacheRoot, `${cachePrefix}${basename(f.rel)}`))))
|
|
215
|
+
return parsed
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return undefined
|
|
219
|
+
}
|
|
220
|
+
return undefined
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function planVariantJobs(
|
|
224
|
+
dims: { width: number, height: number },
|
|
225
|
+
stem: string,
|
|
226
|
+
hash: string,
|
|
227
|
+
cacheRoot: string,
|
|
228
|
+
cfg: VariantPipelineConfig,
|
|
229
|
+
): VariantEncodeJob[] {
|
|
230
|
+
const targetWidths = cfg.widths.filter(w => w < dims.width)
|
|
231
|
+
targetWidths.push(dims.width)
|
|
232
|
+
const jobs: VariantEncodeJob[] = []
|
|
233
|
+
for (const w of targetWidths) {
|
|
234
|
+
for (const fmt of cfg.formats) {
|
|
235
|
+
const fileName = `${stem}-${hash}-${w}w.${fmt}`
|
|
236
|
+
jobs.push({
|
|
237
|
+
fileName,
|
|
238
|
+
cachedFile: join(cacheRoot, `${cfg.cachePrefix}${fileName}`),
|
|
239
|
+
width: w,
|
|
240
|
+
format: fmt,
|
|
241
|
+
quality: fmt === 'avif' ? cfg.avifQuality : cfg.quality,
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return jobs
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function assembleImageAsset(
|
|
249
|
+
meta: CachedImageMeta,
|
|
250
|
+
cacheRoot: string,
|
|
251
|
+
cachePrefix: string,
|
|
252
|
+
urlPrefix: string,
|
|
253
|
+
emitVariant: (rel: string, fileName: string, cachedFile: string) => void,
|
|
254
|
+
): ImageAsset {
|
|
255
|
+
const webpEntries: string[] = []
|
|
256
|
+
const avifEntries: string[] = []
|
|
257
|
+
let fallbackSrc = ''
|
|
258
|
+
|
|
259
|
+
for (const f of meta.files) {
|
|
260
|
+
const fileName = basename(f.rel)
|
|
261
|
+
const cachedFile = join(cacheRoot, `${cachePrefix}${fileName}`)
|
|
262
|
+
emitVariant(f.rel, fileName, cachedFile)
|
|
263
|
+
const url = `${urlPrefix}/${f.rel}`
|
|
264
|
+
if (f.format === 'webp') {
|
|
265
|
+
webpEntries.push(`${url} ${f.width}w`)
|
|
266
|
+
fallbackSrc = url
|
|
267
|
+
}
|
|
268
|
+
else if (f.format === 'avif') {
|
|
269
|
+
avifEntries.push(`${url} ${f.width}w`)
|
|
270
|
+
if (fallbackSrc === '')
|
|
271
|
+
fallbackSrc = url
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
src: fallbackSrc,
|
|
277
|
+
width: meta.width,
|
|
278
|
+
height: meta.height,
|
|
279
|
+
...(webpEntries.length > 0 ? { webpSrcset: webpEntries.join(', ') } : {}),
|
|
280
|
+
...(avifEntries.length > 0 ? { avifSrcset: avifEntries.join(', ') } : {}),
|
|
281
|
+
}
|
|
282
|
+
}
|