@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.
@@ -0,0 +1,191 @@
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 isStandaloneJpegMarker(marker: number): boolean {
68
+ return marker === 0x01 || (marker >= 0xD0 && marker <= 0xD7) || marker === 0xD9
69
+ }
70
+
71
+ function stripJpeg(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
72
+ const kept: Uint8Array[] = [bytes.subarray(0, 2)]
73
+ const removed = new Set<ImageMetadataKind>()
74
+ let orientation: number | undefined
75
+ let insertAt = 1
76
+ let at = 2
77
+ while (at < bytes.length) {
78
+ if (bytes[at] !== 0xFF)
79
+ return { bytes, removed: [] }
80
+ const start = at
81
+ while (at < bytes.length && bytes[at] === 0xFF)
82
+ at++
83
+ if (at >= bytes.length)
84
+ return { bytes, removed: [] }
85
+ const marker = bytes[at]!
86
+ if (marker === 0x00)
87
+ return { bytes, removed: [] }
88
+ if (marker === 0xDA) {
89
+ kept.push(bytes.subarray(start))
90
+ at = bytes.length
91
+ break
92
+ }
93
+ if (isStandaloneJpegMarker(marker)) {
94
+ kept.push(bytes.subarray(start, at + 1))
95
+ at += 1
96
+ if (marker === 0xD9)
97
+ break
98
+ continue
99
+ }
100
+ if (at + 3 > bytes.length)
101
+ return { bytes, removed: [] }
102
+ const length = (bytes[at + 1]! << 8) | bytes[at + 2]!
103
+ const end = at + 1 + length
104
+ if (length < 2 || end > bytes.length)
105
+ return { bytes, removed: [] }
106
+ const payload = bytes.subarray(at + 3, end)
107
+ const kind = jpegSegmentKind(marker, payload)
108
+ if (kind === undefined) {
109
+ if (kept.length === 1 && marker === 0xE0)
110
+ insertAt = 2
111
+ kept.push(bytes.subarray(start, end))
112
+ }
113
+ else {
114
+ removed.add(kind)
115
+ if (kind === 'exif')
116
+ orientation ??= exifOrientation(payload)
117
+ }
118
+ at = end
119
+ }
120
+ if (at !== bytes.length || removed.size === 0)
121
+ return { bytes, removed: [] }
122
+ if (orientation !== undefined && orientation > 1 && orientation <= 8)
123
+ kept.splice(insertAt, 0, orientationSegment(orientation))
124
+ return { bytes: concat(kept), removed: [...removed] }
125
+ }
126
+
127
+ const PNG_METADATA: Record<string, ImageMetadataKind> = { eXIf: 'exif', iTXt: 'text', tEXt: 'text', zTXt: 'text', tIME: 'text' }
128
+
129
+ function stripPng(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
130
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
131
+ const kept: Uint8Array[] = [bytes.subarray(0, 8)]
132
+ const removed = new Set<ImageMetadataKind>()
133
+ let at = 8
134
+ while (at + 12 <= bytes.length) {
135
+ const end = at + 12 + view.getUint32(at)
136
+ if (end > bytes.length)
137
+ return { bytes, removed: [] }
138
+ const type = ascii(bytes, at + 4, 4)
139
+ const kind = type === 'iTXt' && ascii(bytes, at + 8, 17) === 'XML:com.adobe.xmp' ? 'xmp' : PNG_METADATA[type]
140
+ if (kind === undefined)
141
+ kept.push(bytes.subarray(at, end))
142
+ else
143
+ removed.add(kind)
144
+ at = end
145
+ }
146
+ if (at !== bytes.length || removed.size === 0)
147
+ return { bytes, removed: [] }
148
+ return { bytes: concat(kept), removed: [...removed] }
149
+ }
150
+
151
+ const WEBP_METADATA: Record<string, ImageMetadataKind> = { 'EXIF': 'exif', 'XMP ': 'xmp' }
152
+
153
+ function stripWebp(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
154
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
155
+ const kept: Uint8Array[] = []
156
+ const removed = new Set<ImageMetadataKind>()
157
+ let at = 12
158
+ while (at + 8 <= bytes.length) {
159
+ const size = view.getUint32(at + 4, true)
160
+ const end = Math.min(at + 8 + size + (size & 1), bytes.length)
161
+ if (at + 8 + size > bytes.length)
162
+ return { bytes, removed: [] }
163
+ const kind = WEBP_METADATA[ascii(bytes, at, 4)]
164
+ if (kind === undefined)
165
+ kept.push(bytes.slice(at, end))
166
+ else
167
+ removed.add(kind)
168
+ at = end
169
+ }
170
+ if (removed.size === 0)
171
+ return { bytes, removed: [] }
172
+ const vp8x = kept.find(chunk => ascii(chunk, 0, 4) === 'VP8X')
173
+ if (vp8x !== undefined)
174
+ vp8x[8] = vp8x[8]! & ~0x0C
175
+ const body = concat(kept)
176
+ const header = new Uint8Array(12)
177
+ header.set(bytes.subarray(0, 12))
178
+ new DataView(header.buffer).setUint32(4, body.length + 4, true)
179
+ return { bytes: concat([header, body]), removed: [...removed] }
180
+ }
181
+
182
+ /** 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. */
183
+ export function stripImageMetadata(bytes: Uint8Array<ArrayBuffer>): StrippedImage {
184
+ if (bytes[0] === 0xFF && bytes[1] === 0xD8)
185
+ return stripJpeg(bytes)
186
+ if (ascii(bytes, 1, 3) === 'PNG')
187
+ return stripPng(bytes)
188
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP')
189
+ return stripWebp(bytes)
190
+ return { bytes, removed: [] }
191
+ }
@@ -0,0 +1,285 @@
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
+ /** 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
+
41
+ let activeSlots = 0
42
+ const waitingForSlot: (() => void)[] = []
43
+
44
+ async function takeSlot(): Promise<void> {
45
+ if (activeSlots < ENCODE_SLOTS) {
46
+ activeSlots++
47
+ return
48
+ }
49
+ // The caller releasing a slot hands it straight to the next in line.
50
+ await new Promise<void>(resolve => waitingForSlot.push(resolve))
51
+ }
52
+
53
+ function releaseSlot(): void {
54
+ const next = waitingForSlot.shift()
55
+ if (next !== undefined)
56
+ next()
57
+ else
58
+ activeSlots--
59
+ }
60
+
61
+ export interface MagickResult {
62
+ ok: boolean
63
+ stdout: Uint8Array<ArrayBuffer>
64
+ /** Why it failed: magick's stderr, or the timeout. */
65
+ error: string
66
+ }
67
+
68
+ /** 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. */
69
+ export async function runMagick(args: readonly string[], stdin?: Response): Promise<MagickResult> {
70
+ // A subcommand such as `identify` stays first, its options after it.
71
+ const bin = magickBinary()
72
+ const argv = args[0] === 'identify' ? [bin, 'identify', ...MAGICK_LIMITS, ...args.slice(1)] : [bin, ...MAGICK_LIMITS, ...args]
73
+ await takeSlot()
74
+ try {
75
+ const proc = Bun.spawn(argv, { stdin: stdin ?? 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: MAGICK_TIMEOUT_MS, killSignal: 'SIGKILL' })
76
+ const [exitCode, stdout, stderr] = await Promise.all([proc.exited, new Response(proc.stdout).arrayBuffer(), new Response(proc.stderr).text()])
77
+ const error = proc.signalCode === 'SIGKILL' ? `timed out after ${MAGICK_TIMEOUT_MS / 1000} s` : stderr.trim()
78
+ return { ok: exitCode === 0, stdout: new Uint8Array(stdout), error }
79
+ }
80
+ finally {
81
+ releaseSlot()
82
+ }
83
+ }
84
+
85
+ export interface CachedImageMeta {
86
+ width: number
87
+ height: number
88
+ files: { rel: string, width: number, format: string }[]
89
+ }
90
+
91
+ export interface VariantEncodeJob {
92
+ fileName: string
93
+ cachedFile: string
94
+ width: number
95
+ format: 'avif' | 'webp'
96
+ quality: number
97
+ }
98
+
99
+ export interface VariantPipelineConfig {
100
+ widths: number[]
101
+ formats: ('avif' | 'webp')[]
102
+ quality: number
103
+ avifQuality: number
104
+ cachePrefix: string
105
+ }
106
+
107
+
108
+ // EXIF orientations 5 to 8, which `-auto-orient` turns a quarter.
109
+ const QUARTER_TURNS = new Set(['LeftTop', 'RightTop', 'RightBottom', 'LeftBottom'])
110
+
111
+ function parseMagickDimensions(stdout: string): { width: number, height: number } | undefined {
112
+ const parts = stdout.trim().split(/\s+/)
113
+ const w = Number(parts[0])
114
+ const h = Number(parts[1])
115
+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0)
116
+ return undefined
117
+ return QUARTER_TURNS.has(parts[2] ?? '') ? { width: h, height: w } : { width: w, height: h }
118
+ }
119
+
120
+ /** The size the variants will have, after `-auto-orient`, for a file whose header prunelle cannot read. */
121
+ export async function identifyImageAsync(filePath: string): Promise<{ width: number, height: number } | undefined> {
122
+ const result = await runMagick(['identify', '-ping', '-format', '%w %h %[orientation]', `${filePath}[0]`])
123
+ if (!result.ok)
124
+ return undefined
125
+ return parseMagickDimensions(new TextDecoder().decode(result.stdout))
126
+ }
127
+
128
+
129
+ export function writeFileAtomic(dstPath: string, data: string | Uint8Array): void {
130
+ const tmpPath = `${dstPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
131
+ writeFileSync(tmpPath, data)
132
+ try {
133
+ renameSync(tmpPath, dstPath)
134
+ }
135
+ catch {
136
+ rmSync(tmpPath, { force: true })
137
+ }
138
+ }
139
+
140
+ function variantTmpPath(dstPath: string): string {
141
+ const ext = extname(dstPath)
142
+ const stem = ext !== '' ? dstPath.slice(0, -ext.length) : dstPath
143
+ return `${stem}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}${ext}`
144
+ }
145
+
146
+ /**
147
+ * 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.
148
+ * A run that fails part way keeps the variants it wrote before failing, and warns with the widths it left out.
149
+ */
150
+ async function encodeFormatAsync(srcPath: string, jobs: readonly VariantEncodeJob[]): Promise<void> {
151
+ const tmpPaths = jobs.map(job => variantTmpPath(job.cachedFile))
152
+ const result = await runMagick([
153
+ `${srcPath}[0]`,
154
+ '-auto-orient',
155
+ ...DROP_METADATA_KEEP_ICC,
156
+ '-write',
157
+ 'mpr:src',
158
+ '+delete',
159
+ ...jobs.flatMap((job, i) => ['(', 'mpr:src', '-resize', `${job.width}x>`, '-quality', String(job.quality), '-write', tmpPaths[i]!, '+delete', ')']),
160
+ 'null:',
161
+ ])
162
+ // magick writes the variants in order, so after a failed run only the last file it wrote can be cut short.
163
+ if (!result.ok) {
164
+ const last = tmpPaths.findLastIndex(tmpPath => existsSync(tmpPath))
165
+ if (last !== -1)
166
+ rmSync(tmpPaths[last]!, { force: true })
167
+ }
168
+ const missing: number[] = []
169
+ for (const [i, job] of jobs.entries()) {
170
+ const tmpPath = tmpPaths[i]!
171
+ if (existsSync(tmpPath)) {
172
+ try {
173
+ renameSync(tmpPath, job.cachedFile)
174
+ }
175
+ catch {
176
+ rmSync(tmpPath, { force: true })
177
+ }
178
+ }
179
+ if (!existsSync(job.cachedFile))
180
+ missing.push(job.width)
181
+ }
182
+ if (missing.length > 0)
183
+ 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'}`)
184
+ }
185
+
186
+ /** 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. */
187
+ export async function encodeVariants(srcPath: string, jobs: readonly VariantEncodeJob[]): Promise<VariantEncodeJob[]> {
188
+ const byFormat = new Map<VariantEncodeJob['format'], VariantEncodeJob[]>()
189
+ for (const job of jobs) {
190
+ if (existsSync(job.cachedFile))
191
+ continue
192
+ const group = byFormat.get(job.format)
193
+ if (group === undefined)
194
+ byFormat.set(job.format, [job])
195
+ else
196
+ group.push(job)
197
+ }
198
+ await Promise.all([...byFormat.values()].map(group => encodeFormatAsync(srcPath, group)))
199
+ return jobs.filter(job => existsSync(job.cachedFile))
200
+ }
201
+
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
204
+
205
+ export function computeImageKey(srcPath: string, rawBytes: Uint8Array, cfg: VariantPipelineConfig): { hash: string, stem: string, rawFileName: string } {
206
+ const ext = extname(srcPath).toLowerCase()
207
+ const hash = Bun.hash(`${VARIANT_CACHE_VERSION}:${Bun.hash(rawBytes)}:${cfg.widths.join(',')}:${cfg.formats.join(',')}:${cfg.quality}:${cfg.avifQuality}`).toString(36)
208
+ const stem = basename(srcPath, extname(srcPath)).toLowerCase().replace(/[^a-z0-9-_]/g, '-')
209
+ return { hash, stem, rawFileName: `${stem}-${hash}${ext}` }
210
+ }
211
+
212
+ export function readCachedMeta(metaPath: string, cacheRoot: string, cachePrefix: string): CachedImageMeta | undefined {
213
+ if (!existsSync(metaPath))
214
+ return undefined
215
+ try {
216
+ const parsed = JSON.parse(readFileSync(metaPath, 'utf8')) as CachedImageMeta
217
+ if (parsed.files.every(f => existsSync(join(cacheRoot, `${cachePrefix}${basename(f.rel)}`))))
218
+ return parsed
219
+ }
220
+ catch {
221
+ return undefined
222
+ }
223
+ return undefined
224
+ }
225
+
226
+ export function planVariantJobs(
227
+ dims: { width: number, height: number },
228
+ stem: string,
229
+ hash: string,
230
+ cacheRoot: string,
231
+ cfg: VariantPipelineConfig,
232
+ ): VariantEncodeJob[] {
233
+ const targetWidths = cfg.widths.filter(w => w < dims.width)
234
+ targetWidths.push(dims.width)
235
+ const jobs: VariantEncodeJob[] = []
236
+ for (const w of targetWidths) {
237
+ for (const fmt of cfg.formats) {
238
+ const fileName = `${stem}-${hash}-${w}w.${fmt}`
239
+ jobs.push({
240
+ fileName,
241
+ cachedFile: join(cacheRoot, `${cfg.cachePrefix}${fileName}`),
242
+ width: w,
243
+ format: fmt,
244
+ quality: fmt === 'avif' ? cfg.avifQuality : cfg.quality,
245
+ })
246
+ }
247
+ }
248
+ return jobs
249
+ }
250
+
251
+ export function assembleImageAsset(
252
+ meta: CachedImageMeta,
253
+ cacheRoot: string,
254
+ cachePrefix: string,
255
+ urlPrefix: string,
256
+ emitVariant: (rel: string, fileName: string, cachedFile: string) => void,
257
+ ): ImageAsset {
258
+ const webpEntries: string[] = []
259
+ const avifEntries: string[] = []
260
+ let fallbackSrc = ''
261
+
262
+ for (const f of meta.files) {
263
+ const fileName = basename(f.rel)
264
+ const cachedFile = join(cacheRoot, `${cachePrefix}${fileName}`)
265
+ emitVariant(f.rel, fileName, cachedFile)
266
+ const url = `${urlPrefix}/${f.rel}`
267
+ if (f.format === 'webp') {
268
+ webpEntries.push(`${url} ${f.width}w`)
269
+ fallbackSrc = url
270
+ }
271
+ else if (f.format === 'avif') {
272
+ avifEntries.push(`${url} ${f.width}w`)
273
+ if (fallbackSrc === '')
274
+ fallbackSrc = url
275
+ }
276
+ }
277
+
278
+ return {
279
+ src: fallbackSrc,
280
+ width: meta.width,
281
+ height: meta.height,
282
+ ...(webpEntries.length > 0 ? { webpSrcset: webpEntries.join(', ') } : {}),
283
+ ...(avifEntries.length > 0 ? { avifSrcset: avifEntries.join(', ') } : {}),
284
+ }
285
+ }