@prunellejs/images 0.6.0 → 0.7.1
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/LICENSE +21 -0
- package/llms.txt +2 -1
- package/package.json +2 -2
- package/src/cache.ts +53 -0
- package/src/card.ts +1 -1
- package/src/metadata.ts +191 -0
- package/src/pipeline.ts +6 -3
- package/src/plugin.ts +38 -10
- package/src/runtime.ts +14 -16
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
- `widths`: responsive widths in px (default `[320, 640, 960, 1280, 1920]`).
|
|
13
13
|
- `formats`: `('avif' | 'webp')[]` (default `['avif', 'webp']`; uses ImageMagick `magick` on `PATH`, falls back to original file with parsed dimensions when unavailable). Each image is decoded once per format, one `magick` run writing all its widths; runs share one budget for the whole build (half the cores, at most 8 `magick` at once), each limited to one thread and 512 MiB and killed after 2 min; a failed run warns with the file, the widths and `magick`'s error and leaves those variants out until the next build retries them (the original ships when none succeeds).
|
|
14
|
-
-
|
|
14
|
+
- Every image the build ships, original included, loses its EXIF (GPS position, camera serial), XMP, IPTC and text metadata; a JPEG keeps only its Orientation, and every variant keeps its ICC colour profile (`magick ... +profile "!icc,*"`, not `-strip`). `prunelle check` warns about each JPEG, PNG or WebP under `public/` still carrying EXIF, XMP or IPTC, since `public/` is copied as is.
|
|
15
|
+
- `quality` (WebP, default `80`), `avifQuality` (default `55`), `cacheDir` (default `'.prunelle-cache/images'`), `pruneCache` (default `true`: after a build that prerendered pages, `og-` and `md-` cache files no page registered are deleted, together with the imported-image cache the build did not load). The runtime `/og/` and `/img/` stores are LRUs of twice the files the build registered, at least 256 and 4096.
|
|
15
16
|
- `card`: `ShareCardDefaults` (`{ site?, publicDir?, cacheDir?, background?, color?, accent?, mutedColor?, fontFamily?, width? (1200), height? (630) }`).
|
|
16
17
|
- `markdownSizes`: default `sizes` attribute for relative images inside `@prunellejs/content` Markdown (auto-wired via `CONTENT_IMAGE_RESOLVER_SERVICE`).
|
|
17
18
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/images",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
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.
|
|
25
|
+
"prunelle": "^0.7.1"
|
|
26
26
|
}
|
|
27
27
|
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// What a build leaves in the image cache, and how many images the runtime stores must be able to hold.
|
|
2
|
+
|
|
3
|
+
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
4
|
+
import { basename, join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
/** Cache files a prerendering build did not register: `og-<n>` is the cache of public `og/<n>`, `md-<n>` that of public `img/<n>`, and `md-<stem>-<hash>.json` the meta of a kept variant. */
|
|
7
|
+
export function unusedOgAndMdCacheFiles(cacheEntries: readonly string[], publicFiles: readonly string[]): string[] {
|
|
8
|
+
const kept = new Set<string>()
|
|
9
|
+
for (const rel of publicFiles) {
|
|
10
|
+
if (rel.startsWith('og/'))
|
|
11
|
+
kept.add(`og-${basename(rel)}`)
|
|
12
|
+
else if (rel.startsWith('img/')) {
|
|
13
|
+
const variant = `md-${basename(rel)}`
|
|
14
|
+
kept.add(variant)
|
|
15
|
+
// `md-<stem>-<hash>.json` describes the variants `md-<stem>-<hash>-<width>w.<format>`.
|
|
16
|
+
kept.add(variant.replace(/-\d+w\.\w+$/, '.json'))
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return cacheEntries.filter(entry => (entry.startsWith('og-') || entry.startsWith('md-')) && !kept.has(entry))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function removeUnusedOgAndMd(cacheRoot: string, publicFiles: readonly string[]): void {
|
|
23
|
+
if (!existsSync(cacheRoot))
|
|
24
|
+
return
|
|
25
|
+
for (const entry of unusedOgAndMdCacheFiles(readdirSync(cacheRoot), publicFiles))
|
|
26
|
+
rmSync(join(cacheRoot, entry), { force: true })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** How many `og/` and `img/` files the build registered, kept in its plugin data: what the runtime stores must hold at least. */
|
|
30
|
+
export interface KnownImages {
|
|
31
|
+
knownOg?: number | undefined
|
|
32
|
+
knownImg?: number | undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function knownImages(publicFiles: readonly string[]): Required<KnownImages> {
|
|
36
|
+
let knownOg = 0
|
|
37
|
+
let knownImg = 0
|
|
38
|
+
for (const rel of publicFiles) {
|
|
39
|
+
if (rel.startsWith('og/'))
|
|
40
|
+
knownOg++
|
|
41
|
+
else if (rel.startsWith('img/'))
|
|
42
|
+
knownImg++
|
|
43
|
+
}
|
|
44
|
+
return { knownOg, knownImg }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const MIN_OG_ENTRIES = 256
|
|
48
|
+
export const MIN_IMG_ENTRIES = 4096
|
|
49
|
+
|
|
50
|
+
/** The size of the `/og/` and `/img/` stores: twice what the build knows, never under its floor, so an image the HTML references is served and a flood of unique URLs still cannot grow a store for ever. */
|
|
51
|
+
export function runtimeStoreLimits(known: KnownImages | undefined): [maxOg: number, maxImg: number] {
|
|
52
|
+
return [Math.max(MIN_OG_ENTRIES, (known?.knownOg ?? 0) * 2), Math.max(MIN_IMG_ENTRIES, (known?.knownImg ?? 0) * 2)]
|
|
53
|
+
}
|
package/src/card.ts
CHANGED
|
@@ -116,7 +116,7 @@ function buildCardSvg(input: ShareCardInput, cfg: ShareCardDefaults): string {
|
|
|
116
116
|
const fg = input.color ?? cfg.color ?? '#dbe0ea'
|
|
117
117
|
const accent = input.accent ?? cfg.accent ?? '#f5b83d'
|
|
118
118
|
const muted = cfg.mutedColor ?? '#8b95aa'
|
|
119
|
-
const font = cfg.fontFamily ?? '
|
|
119
|
+
const font = cfg.fontFamily ?? '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", "Helvetica Neue", Arial, sans-serif'
|
|
120
120
|
|
|
121
121
|
const hasGraphic = Boolean(input.image)
|
|
122
122
|
const titleLines = wrapLines(input.title, hasGraphic ? 20 : 26, 3)
|
package/src/metadata.ts
ADDED
|
@@ -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
|
+
}
|
package/src/pipeline.ts
CHANGED
|
@@ -35,6 +35,9 @@ function magickBinary(): string {
|
|
|
35
35
|
return magickBin.bin
|
|
36
36
|
}
|
|
37
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
|
+
|
|
38
41
|
let activeSlots = 0
|
|
39
42
|
const waitingForSlot: (() => void)[] = []
|
|
40
43
|
|
|
@@ -149,7 +152,7 @@ async function encodeFormatAsync(srcPath: string, jobs: readonly VariantEncodeJo
|
|
|
149
152
|
const result = await runMagick([
|
|
150
153
|
`${srcPath}[0]`,
|
|
151
154
|
'-auto-orient',
|
|
152
|
-
|
|
155
|
+
...DROP_METADATA_KEEP_ICC,
|
|
153
156
|
'-write',
|
|
154
157
|
'mpr:src',
|
|
155
158
|
'+delete',
|
|
@@ -196,8 +199,8 @@ export async function encodeVariants(srcPath: string, jobs: readonly VariantEnco
|
|
|
196
199
|
return jobs.filter(job => existsSync(job.cachedFile))
|
|
197
200
|
}
|
|
198
201
|
|
|
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 =
|
|
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
|
|
201
204
|
|
|
202
205
|
export function computeImageKey(srcPath: string, rawBytes: Uint8Array, cfg: VariantPipelineConfig): { hash: string, stem: string, rawFileName: string } {
|
|
203
206
|
const ext = extname(srcPath).toLowerCase()
|
package/src/plugin.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Built strictly on the public PrunellePlugin API (bunPlugins + build(ctx).emitAsset).
|
|
3
3
|
|
|
4
4
|
import type { BunPlugin } from 'bun'
|
|
5
|
-
import type { PrunellePlugin } from 'prunelle/config'
|
|
5
|
+
import type { CheckPluginContext, PrunellePlugin } from 'prunelle/config'
|
|
6
6
|
import type { ShareCardDefaults } from './card'
|
|
7
7
|
import type { ImageAsset } from './helpers'
|
|
8
8
|
import type { CachedImageMeta, VariantPipelineConfig } from './pipeline'
|
|
@@ -11,8 +11,11 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync,
|
|
|
11
11
|
import { dirname, extname, join, resolve } from 'node:path'
|
|
12
12
|
import { CONTENT_IMAGE_RESOLVER_SERVICE, definePlugin, isInside } from 'prunelle/config'
|
|
13
13
|
import { getAppContext } from 'prunelle/internal/server'
|
|
14
|
+
import type { KnownImages } from './cache'
|
|
15
|
+
import { knownImages, removeUnusedOgAndMd, runtimeStoreLimits } from './cache'
|
|
14
16
|
import { SHARE_CARD_CONFIG_SERVICE } from './card'
|
|
15
17
|
import { readImageDimensions } from './dimensions'
|
|
18
|
+
import { stripImageMetadata } from './metadata'
|
|
16
19
|
import {
|
|
17
20
|
ALLOWED_IMAGE_EXTS,
|
|
18
21
|
assembleImageAsset,
|
|
@@ -58,9 +61,34 @@ export interface ImagesPluginOptions {
|
|
|
58
61
|
|
|
59
62
|
const DEFAULT_WIDTHS = [320, 640, 960, 1280, 1920]
|
|
60
63
|
const DEFAULT_FORMATS: ('avif' | 'webp')[] = ['avif', 'webp']
|
|
64
|
+
const PUBLIC_IMAGE = /\.(?:png|jpe?g|webp)$/i
|
|
65
|
+
const PERSONAL_METADATA = new Set(['exif', 'xmp', 'iptc'])
|
|
66
|
+
|
|
67
|
+
// Files in public/ are served as they are, so a photo there hands its GPS position and camera serial to every visitor.
|
|
68
|
+
function publicImageMetadataWarnings(publicDir: string): string[] {
|
|
69
|
+
if (!existsSync(publicDir))
|
|
70
|
+
return []
|
|
71
|
+
const warnings: string[] = []
|
|
72
|
+
for (const rel of readdirSync(publicDir, { recursive: true, encoding: 'utf8' })) {
|
|
73
|
+
if (!PUBLIC_IMAGE.test(rel))
|
|
74
|
+
continue
|
|
75
|
+
const kinds = stripImageMetadata(new Uint8Array(readFileSync(join(publicDir, rel)))).removed.filter(kind => PERSONAL_METADATA.has(kind))
|
|
76
|
+
if (kinds.length > 0)
|
|
77
|
+
warnings.push(`@prunellejs/images: public/${rel} carries ${kinds.map(k => k.toUpperCase()).join(' and ')} metadata (GPS position, camera serial) that every visitor can download: import it from src/ so the build strips it, or strip it yourself (\`magick public/${rel} +profile "!icc,*" public/${rel}\`, which keeps the ICC colour profile).`)
|
|
78
|
+
}
|
|
79
|
+
return warnings
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function checkImages(ctx: CheckPluginContext): void {
|
|
83
|
+
if (!hasMagick())
|
|
84
|
+
ctx.error(MISSING_MAGICK_MESSAGE)
|
|
85
|
+
for (const warning of publicImageMetadataWarnings(join(ctx.root, 'public')))
|
|
86
|
+
ctx.warn(warning)
|
|
87
|
+
}
|
|
88
|
+
|
|
61
89
|
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
90
|
|
|
63
|
-
interface PersistedImagesConfig {
|
|
91
|
+
interface PersistedImagesConfig extends KnownImages {
|
|
64
92
|
cacheDirRel: string
|
|
65
93
|
widths: number[]
|
|
66
94
|
formats: ('avif' | 'webp')[]
|
|
@@ -92,10 +120,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
|
|
|
92
120
|
|
|
93
121
|
return definePlugin({
|
|
94
122
|
name: '@prunellejs/images',
|
|
95
|
-
check
|
|
96
|
-
if (!hasMagick())
|
|
97
|
-
ctx.error(MISSING_MAGICK_MESSAGE)
|
|
98
|
-
},
|
|
123
|
+
check: checkImages,
|
|
99
124
|
bunPlugins: ({ root, assetPrefix }): BunPlugin[] => {
|
|
100
125
|
const cacheRoot = resolve(root, cacheDirRel)
|
|
101
126
|
lastCacheRoot = cacheRoot
|
|
@@ -112,7 +137,7 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
|
|
|
112
137
|
if (args.path.includes('/node_modules/'))
|
|
113
138
|
return undefined
|
|
114
139
|
|
|
115
|
-
const rawBytes = new Uint8Array(readFileSync(args.path))
|
|
140
|
+
const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(args.path))).bytes
|
|
116
141
|
const { hash, stem, rawFileName } = computeImageKey(args.path, rawBytes, pipelineCfg)
|
|
117
142
|
const emitRaw = (width: number, height: number) => {
|
|
118
143
|
const rel = `img/${rawFileName}`
|
|
@@ -202,12 +227,16 @@ export function images(options: ImagesPluginOptions = {}): PrunellePlugin {
|
|
|
202
227
|
},
|
|
203
228
|
async afterPrerender(ctx) {
|
|
204
229
|
await flushBuildPhase(ctx.outDir)
|
|
230
|
+
ctx.setData(knownImages(ctx.publicFiles))
|
|
231
|
+
// Only a build that rendered pages registered the cards and variants it uses: without one the runtime still reads those cache files.
|
|
232
|
+
if (pruneCache && lastCacheRoot !== undefined && ctx.routes.some(route => Object.keys(route.prerendered ?? {}).length > 0))
|
|
233
|
+
removeUnusedOgAndMd(lastCacheRoot, ctx.publicFiles)
|
|
205
234
|
},
|
|
206
235
|
server(api) {
|
|
207
236
|
const persisted = api.getBuildData<PersistedImagesConfig>()
|
|
208
237
|
const publicDir = join(api.outDir, 'public')
|
|
209
238
|
const cacheDir = resolve(api.root, persisted?.cacheDirRel ?? cacheDirRel)
|
|
210
|
-
const runtimeStore = createRuntimeImageStore()
|
|
239
|
+
const runtimeStore = createRuntimeImageStore(...runtimeStoreLimits(persisted))
|
|
211
240
|
api.provide(RUNTIME_IMAGE_STORE_SERVICE, runtimeStore)
|
|
212
241
|
registerRuntimeImageMiddleware(api, runtimeStore)
|
|
213
242
|
api.onShutdown(() => {
|
|
@@ -308,7 +337,7 @@ export function optimizeImageFile(absPath: string, options: OptimizeImageFileOpt
|
|
|
308
337
|
cachePrefix: 'md-',
|
|
309
338
|
}
|
|
310
339
|
const appCtx = getAppContext()
|
|
311
|
-
const rawBytes = new Uint8Array(readFileSync(absPath))
|
|
340
|
+
const rawBytes = stripImageMetadata(new Uint8Array(readFileSync(absPath))).bytes
|
|
312
341
|
const dims = readImageDimensions(rawBytes)
|
|
313
342
|
if (dims === undefined)
|
|
314
343
|
throw new Error(`@prunellejs/images: could not determine dimensions for "${absPath}"`)
|
|
@@ -423,7 +452,6 @@ export function createMarkdownImageResolver(options: MarkdownImageResolverOption
|
|
|
423
452
|
...(srcset !== undefined ? { sizes } : {}),
|
|
424
453
|
width: asset.width,
|
|
425
454
|
height: asset.height,
|
|
426
|
-
loading: 'lazy' as const,
|
|
427
455
|
}
|
|
428
456
|
}
|
|
429
457
|
}
|
package/src/runtime.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ServerPluginAPI } from 'prunelle/config'
|
|
4
4
|
import { serviceKey } from 'prunelle/config'
|
|
5
|
-
import {
|
|
5
|
+
import { MIN_IMG_ENTRIES, MIN_OG_ENTRIES } from './cache'
|
|
6
|
+
import { DROP_METADATA_KEEP_ICC, runMagick } from './pipeline'
|
|
6
7
|
|
|
7
8
|
export interface RuntimeImagePayload {
|
|
8
9
|
body: Uint8Array<ArrayBuffer> | string
|
|
@@ -60,23 +61,22 @@ function etagMatchesHeader(ifNoneMatch: string | null, etag: string): boolean {
|
|
|
60
61
|
return trimmed.split(',').some(part => strip(part.trim()) === target)
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
export function createRuntimeImageStore(maxOgEntries =
|
|
64
|
-
//
|
|
65
|
-
// so flooding unique `/og/` URLs can never evict live `/img/` entries to 404.
|
|
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
66
|
const ogEntries = new Map<string, LazyEntry>()
|
|
67
67
|
const imgEntries = new Map<string, LazyEntry>()
|
|
68
68
|
|
|
69
|
-
function bucketFor(pathname: string): { map: Map<string, LazyEntry>,
|
|
69
|
+
function bucketFor(pathname: string): { map: Map<string, LazyEntry>, limit: number } {
|
|
70
70
|
return pathname.startsWith('/og/')
|
|
71
|
-
? { map: ogEntries,
|
|
72
|
-
: { map: imgEntries,
|
|
71
|
+
? { map: ogEntries, limit: maxOgEntries }
|
|
72
|
+
: { map: imgEntries, limit: maxImgEntries }
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
function put(pathname: string, entry: LazyEntry): void {
|
|
76
|
-
const { map,
|
|
76
|
+
const { map, limit } = bucketFor(pathname)
|
|
77
77
|
map.delete(pathname)
|
|
78
78
|
map.set(pathname, entry)
|
|
79
|
-
if (
|
|
79
|
+
if (map.size > limit) {
|
|
80
80
|
const oldest = map.keys().next()
|
|
81
81
|
if (!oldest.done)
|
|
82
82
|
map.delete(oldest.value)
|
|
@@ -97,15 +97,13 @@ export function createRuntimeImageStore(maxOgEntries = 256): RuntimeImageStore {
|
|
|
97
97
|
return bucketFor(pathname).map.has(pathname)
|
|
98
98
|
},
|
|
99
99
|
async serve(pathname, request) {
|
|
100
|
-
const { map
|
|
100
|
+
const { map } = bucketFor(pathname)
|
|
101
101
|
const entry = map.get(pathname)
|
|
102
102
|
if (entry === undefined)
|
|
103
103
|
return undefined
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
map.set(pathname, entry)
|
|
108
|
-
}
|
|
104
|
+
// Refresh LRU position
|
|
105
|
+
map.delete(pathname)
|
|
106
|
+
map.set(pathname, entry)
|
|
109
107
|
|
|
110
108
|
let payload = entry.resolved
|
|
111
109
|
if (payload === undefined && entry.load !== undefined) {
|
|
@@ -331,7 +329,7 @@ export async function encodeVariantToBytesAsync(
|
|
|
331
329
|
): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
332
330
|
if (!hasMagick())
|
|
333
331
|
return undefined
|
|
334
|
-
const result = await runMagick([`${srcPath}[0]`, '-auto-orient',
|
|
332
|
+
const result = await runMagick([`${srcPath}[0]`, '-auto-orient', ...DROP_METADATA_KEEP_ICC, '-resize', `${width}x>`, '-quality', String(quality), `${format}:-`])
|
|
335
333
|
if (result.ok && result.stdout.byteLength > 0)
|
|
336
334
|
return result.stdout
|
|
337
335
|
return undefined
|