@nera-static/plugin-images 0.0.0-stage → 1.0.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.
@@ -0,0 +1,282 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import sharp from 'sharp'
4
+
5
+ // What to produce for one source image (planVariants, pure) and how to produce
6
+ // one variant (encodeVariant, sharp). ROADMAP D6 (output), D7 (parameters).
7
+
8
+ // The `<img>` fallback stays in the source's own family (D6); formats a
9
+ // browser cannot show in `<img>` fall back to JPEG. sharp reports AVIF (and
10
+ // HEIC) sources as `heif`.
11
+ const FALLBACK_FORMAT = {
12
+ jpeg: 'jpeg',
13
+ png: 'png',
14
+ webp: 'webp',
15
+ heif: 'jpeg',
16
+ avif: 'jpeg',
17
+ tiff: 'jpeg',
18
+ }
19
+
20
+ export const EXTENSIONS = { avif: 'avif', webp: 'webp', jpeg: 'jpg', png: 'png' }
21
+
22
+ export const MIME_TYPES = {
23
+ avif: 'image/avif',
24
+ webp: 'image/webp',
25
+ jpeg: 'image/jpeg',
26
+ png: 'image/png',
27
+ }
28
+
29
+ export const STRATEGIES = ['attention', 'entropy']
30
+
31
+ export function fallbackFormat(sourceFormat) {
32
+ return FALLBACK_FORMAT[sourceFormat] || 'jpeg'
33
+ }
34
+
35
+ /**
36
+ * Dimensions as a visitor sees them: EXIF orientation 5–8 swaps width and
37
+ * height, and `.rotate()` in encodeVariant applies it.
38
+ *
39
+ * @param {string|Buffer} input file path or bytes
40
+ * @returns {Promise<{ width: number, height: number, format: string, hasAlpha: boolean }>}
41
+ */
42
+ export async function readSourceMeta(input) {
43
+ const meta = await sharp(input).metadata()
44
+ if (!meta.width || !meta.height) {
45
+ throw new Error('could not read image dimensions')
46
+ }
47
+ const { width, height } = meta.autoOrient || meta
48
+ return { width, height, format: meta.format, hasAlpha: Boolean(meta.hasAlpha) }
49
+ }
50
+
51
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max)
52
+
53
+ // The largest region of `aspect` (width / height) inside the source, centred
54
+ // on the focal point and pushed back inside the edges.
55
+ function coverCrop(source, aspect, focus) {
56
+ const { width: sw, height: sh } = source
57
+ const width = sw / sh > aspect ? Math.round(sh * aspect) : sw
58
+ const height = sw / sh > aspect ? sh : Math.round(sw / aspect)
59
+
60
+ if (typeof focus === 'string') {
61
+ return { region: { width, height }, crop: { strategy: focus } }
62
+ }
63
+ const { x = 50, y = 50 } = focus || {}
64
+ const left = clamp(Math.round((x / 100) * sw - width / 2), 0, sw - width)
65
+ const top = clamp(Math.round((y / 100) * sh - height / 2), 0, sh - height)
66
+ return { region: { width, height }, crop: { left, top, width, height } }
67
+ }
68
+
69
+ // The geometry shared by every variant of one image: how the source is cut and
70
+ // fitted, independent of the output width.
71
+ function geometry(source, { w, h, ratio, fit, focus }) {
72
+ const aspect = w && h ? w / h : ratio || null
73
+
74
+ if (!aspect) {
75
+ return { aspect: null, fit: 'fill', crop: null, region: source }
76
+ }
77
+ const mode = fit || 'cover'
78
+ if (mode === 'cover') {
79
+ const { region, crop } = coverCrop(source, aspect, focus)
80
+ return { aspect, fit: 'cover', crop, region }
81
+ }
82
+ return { aspect, fit: mode, crop: null, region: source }
83
+ }
84
+
85
+ // Output size for a candidate width W, and the largest W that does not
86
+ // upscale the image content.
87
+ function sizer(source, geo) {
88
+ const { aspect, fit, region } = geo
89
+ const { width: sw, height: sh } = source
90
+
91
+ if (fit === 'contain' || fit === 'inside') {
92
+ // Box W × W/aspect; the image is scaled to fit inside it. `contain`
93
+ // pads the box, `inside` returns just the scaled image.
94
+ const scale = (W) => Math.min(W / sw, W / aspect / sh)
95
+ return {
96
+ max: Math.round(Math.max(sw, sh * aspect)),
97
+ size: (W) =>
98
+ fit === 'contain'
99
+ ? { width: W, height: Math.round(W / aspect) }
100
+ : {
101
+ width: Math.round(sw * scale(W)),
102
+ height: Math.round(sh * scale(W)),
103
+ },
104
+ }
105
+ }
106
+ // `fill` (no crop) and `cover` both scale the region to the full width.
107
+ const ratio = aspect || region.width / region.height
108
+ return {
109
+ max: region.width,
110
+ size: (W) => ({ width: W, height: Math.max(1, Math.round(W / ratio)) }),
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Plan every variant of one image. Pure: no I/O, the main unit-test target.
116
+ *
117
+ * Widths (D6, D7): the config widths, or with `w` those below `w` plus `w` and
118
+ * `2w` (retina). Never upscaled: config widths above the source are dropped
119
+ * and the source width is used when none is left; `w`/`2w` are capped at it.
120
+ *
121
+ * Geometry: `w` + `h` or `ratio` (width / height, a number) set an aspect.
122
+ * With `fit: cover` (the default once an aspect is set) the source is cropped
123
+ * to it around `focus` (`{ x, y }` in percent, default 50/50, or `attention` /
124
+ * `entropy` for sharp's strategies). `contain` pads to the aspect, `inside`
125
+ * scales to fit within it. `w` + `h` take precedence over `ratio`.
126
+ *
127
+ * Formats: one set per modern format, then the fallback (D6). A modern format
128
+ * equal to the fallback is produced once, as the fallback. `fallback` forces
129
+ * the fallback format instead of deriving it from the source (the og preset,
130
+ * D9, is always JPEG).
131
+ *
132
+ * @param {{ width: number, height: number, format: string }} source oriented
133
+ * @param {object} options `{ widths, formats, quality, w?, h?, ratio?, fit?, focus?, q?, fallback? }`
134
+ * @returns {Array<{ width, height, format, quality, fit, crop, aspect }>}
135
+ * modern formats in `formats` order, fallback last, each ascending by width
136
+ */
137
+ export function planVariants(source, options) {
138
+ const { widths, formats = [], quality = {}, w, q } = options
139
+ const geo = geometry(source, options)
140
+ const { max, size } = sizer(source, geo)
141
+
142
+ let candidates
143
+ if (w) {
144
+ candidates = [...widths.filter((x) => x < w), w, 2 * w].map((x) =>
145
+ Math.min(x, max)
146
+ )
147
+ } else {
148
+ candidates = widths.filter((x) => x <= max)
149
+ if (candidates.length === 0) candidates = [max]
150
+ }
151
+
152
+ // `inside` can map two box widths to the same output width; keep one.
153
+ const sizes = []
154
+ for (const W of [...new Set(candidates)].sort((a, b) => a - b)) {
155
+ const dims = size(W)
156
+ if (!sizes.some((s) => s.width === dims.width)) sizes.push(dims)
157
+ }
158
+
159
+ const fallback = options.fallback || fallbackFormat(source.format)
160
+ const order = [...formats.filter((f) => f !== fallback), fallback]
161
+
162
+ return order.flatMap((format) =>
163
+ sizes.map(({ width, height }) => ({
164
+ width,
165
+ height,
166
+ format,
167
+ quality: q || quality[format],
168
+ fit: geo.fit,
169
+ crop: geo.crop,
170
+ aspect: geo.aspect,
171
+ }))
172
+ )
173
+ }
174
+
175
+ // The pixels of one variant before encoding: EXIF orientation applied,
176
+ // cropped, resized and in sRGB. Shared by the encoder and the placeholders,
177
+ // so a placeholder always shows exactly the variant's region.
178
+ function shape(input, { width, height, fit, crop }) {
179
+ let image = sharp(input).rotate()
180
+
181
+ if (crop && crop.strategy) {
182
+ image = image.resize(width, height, {
183
+ fit: 'cover',
184
+ position: sharp.strategy[crop.strategy],
185
+ })
186
+ } else {
187
+ if (crop) image = image.extract(crop)
188
+ image = image.resize(width, height, {
189
+ fit,
190
+ background: { r: 255, g: 255, b: 255, alpha: 0 },
191
+ })
192
+ }
193
+ return image.toColourspace('srgb')
194
+ }
195
+
196
+ function encoder(image, { format, quality }) {
197
+ switch (format) {
198
+ case 'avif':
199
+ return image.avif({ quality })
200
+ case 'webp':
201
+ return image.webp({ quality })
202
+ case 'png':
203
+ // Lossless; `quality` only matters with palette quantisation, which
204
+ // stays off (see the config reference).
205
+ return image.png()
206
+ case 'jpeg':
207
+ return image.flatten({ background: '#ffffff' }).jpeg({ quality, mozjpeg: true })
208
+ default:
209
+ throw new Error(`unsupported output format "${format}"`)
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Encode one planned variant and write it to `outFile`.
215
+ *
216
+ * Applies EXIF orientation, crops, resizes, converts to sRGB and encodes.
217
+ * Metadata is stripped: that is sharp's default, and `.withMetadata()` is never
218
+ * called (D6). The file is written to a temporary name and renamed into place,
219
+ * so an interrupted build never leaves a truncated file the cache would later
220
+ * take for a finished one.
221
+ *
222
+ * @param {string|Buffer} input source file path or bytes
223
+ * @param {object} variant one entry from planVariants
224
+ * @param {string} outFile absolute target path
225
+ */
226
+ export async function encodeVariant(input, variant, outFile) {
227
+ const image = encoder(shape(input, variant), variant)
228
+
229
+ fs.mkdirSync(path.dirname(outFile), { recursive: true })
230
+ const temp = `${outFile}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
231
+ try {
232
+ await image.toFile(temp)
233
+ fs.renameSync(temp, outFile)
234
+ } catch (err) {
235
+ fs.rmSync(temp, { force: true })
236
+ throw err
237
+ }
238
+ }
239
+
240
+ export const PLACEHOLDER_SAMPLE_WIDTH = 64
241
+ export const BLUR_WIDTH = 16
242
+ const BLUR_QUALITY = 50
243
+
244
+ // The same variant at another width, with the height following its aspect.
245
+ const scaled = (variant, width) => {
246
+ const w = Math.min(width, variant.width)
247
+ return { ...variant, width: w, height: Math.max(1, Math.round((w * variant.height) / variant.width)) }
248
+ }
249
+
250
+ const hex = (value) => Math.round(value).toString(16).padStart(2, '0')
251
+
252
+ /**
253
+ * The placeholder of one image (D10), computed from its largest variant's
254
+ * geometry so it shows the same crop the visitor will see.
255
+ *
256
+ * - `color`: the dominant colour as `#rrggbb`;
257
+ * - `blur`: a {@link BLUR_WIDTH} px wide WebP as a base64 data URI.
258
+ *
259
+ * An image that is not fully opaque (alpha, or `fit=contain` padding) gets
260
+ * `{ transparent: true }` instead: a background behind it would stay visible
261
+ * through the transparent parts after loading (decided 2026-10-09).
262
+ *
263
+ * @param {string|Buffer} input source file path or bytes
264
+ * @param {object} variant the largest planned variant
265
+ * @param {'color'|'blur'} mode
266
+ * @returns {Promise<{ color: string }|{ blur: string }|{ transparent: true }>}
267
+ */
268
+ export async function placeholderOf(input, variant, mode) {
269
+ const sample = await shape(input, scaled(variant, PLACEHOLDER_SAMPLE_WIDTH)).png().toBuffer()
270
+ const { isOpaque, dominant } = await sharp(sample).stats()
271
+ if (!isOpaque) return { transparent: true }
272
+
273
+ if (mode === 'color') {
274
+ return { color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}` }
275
+ }
276
+ const { width, height } = scaled(variant, BLUR_WIDTH)
277
+ const blur = await sharp(sample)
278
+ .resize(width, height, { fit: 'fill' })
279
+ .webp({ quality: BLUR_QUALITY })
280
+ .toBuffer()
281
+ return { blur: `data:image/webp;base64,${blur.toString('base64')}` }
282
+ }
package/src/warn.js ADDED
@@ -0,0 +1,6 @@
1
+ // One prefix for every message the plugin prints, matching the fleet's
2
+ // `⚠️ plugin-<name>: …` style, so a site owner can tell where a warning came
3
+ // from in a build log full of other plugins.
4
+ export function warn(message) {
5
+ console.warn(`⚠️ plugin-images: ${message}`)
6
+ }
@@ -0,0 +1,42 @@
1
+ //- @nera-static/plugin-images: the markup for a frontmatter image.
2
+ //-
3
+ //- include /vendor/plugin-images/picture
4
+ //- +picture(meta.images && meta.images.image, { alt: meta.title })
5
+ //-
6
+ //- `image` is a `meta.images.<key>` entry the plugin prepared at build time
7
+ //- (pure markup from precomputed data, nothing is encoded here). Renders
8
+ //- nothing when it is missing, so a page without the frontmatter key just
9
+ //- has no image. Options: `alt`, `class`, `sizes` (overrides the entry's),
10
+ //- `loading` (`lazy` by default; `eager` adds `fetchpriority="high"` for a
11
+ //- hero image). Extra attributes go onto the <img>:
12
+ //- `+picture(image, { alt: '' })(data-zoom)`. A placeholder the plugin
13
+ //- computed (`placeholder: color | blur` in config/images.yaml) becomes the
14
+ //- <img>'s `style`, as in the content pass.
15
+ mixin picture-img(image, opts, sizes)
16
+ - const eager = opts.loading === 'eager'
17
+ - const placeholder = image.blur ? `background-image:url(${image.blur});background-size:cover` : image.color ? `background-color:${image.color}` : undefined
18
+ img(
19
+ src=image.src
20
+ srcset=image.srcset
21
+ sizes=sizes
22
+ width=image.width
23
+ height=image.height
24
+ style=placeholder
25
+ alt=opts.alt
26
+ class=opts.class
27
+ loading=eager ? 'eager' : 'lazy'
28
+ decoding=eager ? undefined : 'async'
29
+ fetchpriority=eager ? 'high' : undefined
30
+ )&attributes(attributes)
31
+
32
+ mixin picture(image, options)
33
+ if image
34
+ - const opts = options || {}
35
+ - const sizes = opts.sizes || image.sizes
36
+ if image.sources && image.sources.length
37
+ picture
38
+ each source in image.sources
39
+ source(type=source.type srcset=source.srcset sizes=sizes)
40
+ +picture-img(image, opts, sizes)&attributes(attributes)
41
+ else
42
+ +picture-img(image, opts, sizes)&attributes(attributes)