@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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,62 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2026-10-09
9
+
10
+ ### Added
11
+
12
+ - First release. Requires `@nera-static/core` 4.13.0 or later (the
13
+ `getAssets` hook) and Node.js 20.18.1 or later
14
+ - `getMetaData` rewrites every local raster image in the
15
+ rendered pages to `<picture>` markup with AVIF/WebP `<source>`s, a
16
+ `srcset`/`sizes` fallback `<img>` with intrinsic `width`/`height`, and
17
+ lazy loading (the first image on a page eager, with
18
+ `fetchpriority="high"`). `getAssets` (core >= 4.13.0) prunes the cache and
19
+ hands the variants to core for `public/<output_path>`. The build fails
20
+ with a clear message when core is too old to call `getAssets`. Core's
21
+ version is read from the site first, so a symlinked plugin (`npm link`,
22
+ an install by path) cannot hide the site's older core behind its own
23
+ development copy
24
+ - Encoding with sharp: EXIF orientation applied, all metadata (EXIF, GPS,
25
+ ICC) stripped, colours converted to sRGB, widths never upscaled. Variants
26
+ are cached in `.nera-cache/images/` (config `cache_dir`) with stable,
27
+ content-hashed file names, so a warm build encodes nothing; variants no
28
+ longer used are pruned (`prune: true`). Encodes run in parallel, bounded
29
+ by `concurrency`
30
+ - Per-image options as query parameters on the image URL
31
+ (`![alt](/images/a.jpg?w=800&ratio=16:9)`): `w`, `h`, `ratio`, `fit`,
32
+ `focus` (percent or `attention`/`entropy`), `q`, `formats`, `sizes`,
33
+ `loading` and `skip`. Recognized parameters never reach the emitted URLs;
34
+ unknown or invalid ones warn with the page and the URL and fall back to
35
+ the defaults. `?w` also derives the default `sizes`
36
+ - Captions: `![alt](src "Caption")` alone in its paragraph becomes
37
+ `<figure class="nera-image">` with
38
+ `<figcaption class="nera-image__caption">`, replacing the paragraph
39
+ (config `figure: title`, the default; `figure: false` disables it)
40
+ - Frontmatter images: for every key in `frontmatter_keys` (default
41
+ `[image]`) holding a local image path, `meta.images.<key>` carries the
42
+ precomputed `src`, `srcset`, `sizes`, `width`, `height`, `type` and the
43
+ modern-format `sources`, plus `og` (one JPEG at the `og` preset,
44
+ 1200×630 cover by default; `og: false` disables it). The original
45
+ `meta.<key>` string is never modified. Query parameters work on the
46
+ frontmatter path as on a Markdown image
47
+ - The `+picture(meta.images.image, { alt, class, sizes, loading })` Pug
48
+ mixin (`views/picture.pug`), published to
49
+ `views/vendor/plugin-images/` with `npm run publish-template` or the
50
+ `nera-images` bin
51
+ - Placeholders (config `placeholder: none | color | blur`, default
52
+ `none`): `color` sets the image's dominant colour as
53
+ `style="background-color:#rrggbb"`, `blur` a 16 px wide WebP as an
54
+ inline `background-image`. Both apply to the content pass and to
55
+ `meta.images.<key>` (`color`/`blur`, rendered by the mixin), are computed
56
+ from the region the variants show, and are cached in the manifest. Images
57
+ that are not fully opaque get none. Inline styles need `'unsafe-inline'`
58
+ in a strict CSP's `style-src`
59
+ - README: installation, before/after markup, configuration reference,
60
+ query parameters, captions, frontmatter images and the mixin, `og:image`,
61
+ placeholders and CSP, keeping originals off the server with
62
+ `.neraignore`, and caching `.nera-cache` in CI
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Becker
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/README.md CHANGED
@@ -1,3 +1,259 @@
1
- # Temporary Holding Version
1
+ # @nera-static/plugin-images
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A plugin for the [Nera](https://github.com/seebaermichi/nera) static site generator that turns every local image in your Markdown into responsive, modern-format markup at build time: `<picture>` with AVIF/WebP, `srcset`/`sizes`, `width`/`height`, lazy loading, and camera metadata (EXIF/GPS) stripped.
4
+
5
+ 📖 **Documentation:** [nera.js.org](https://nera.js.org)
6
+
7
+ > Requires `@nera-static/core` **4.13.0 or later** (see [Compatibility](#compatibility)).
8
+
9
+ ## ✨ Features
10
+
11
+ - Every local raster image in Markdown becomes `<picture>` + AVIF/WebP + `srcset` + `width`/`height` + lazy loading, with no change to your content
12
+ - Variants are generated once, at build time, with [sharp](https://sharp.pixelplumbing.com), and cached between builds; a warm build encodes nothing
13
+ - EXIF orientation is applied, then **all metadata is stripped** (no camera data, no GPS on your server)
14
+ - The first image on each page loads eagerly with `fetchpriority="high"` (the usual LCP image), every other one lazily
15
+ - Per-image control with query parameters on the URL: `![alt](/images/a.jpg?w=800&ratio=16:9&focus=30,60)`
16
+ - `![alt](src "Caption")` becomes a `<figure>` with a `<figcaption>`
17
+ - Frontmatter images (`image: /images/hero.jpg`) get precomputed variants for your templates, including an `og:image` crop, plus a Pug mixin to render them
18
+ - Optional colour or blur placeholders
19
+ - Works with `base_path` and `asset_hashing`
20
+
21
+ ## 🚀 Installation
22
+
23
+ ```bash
24
+ npm install @nera-static/plugin-images
25
+ ```
26
+
27
+ Nera detects the plugin and processes images during `nera build`. There is nothing else to set up: `config/images.yaml` is optional.
28
+
29
+ Add the cache folder to your `.gitignore`:
30
+
31
+ ```gitignore
32
+ .nera-cache
33
+ ```
34
+
35
+ ## Before and after
36
+
37
+ ```md
38
+ ![Startseite der ZerpenSafari](/images/blog/2026/zerpensafari-iphone.jpg)
39
+ ```
40
+
41
+ Without the plugin, this is a bare `<img src="/images/blog/2026/zerpensafari-iphone.jpg" alt="…">`. Phones download the full original. With the plugin:
42
+
43
+ ```html
44
+ <picture>
45
+ <source type="image/avif" srcset="/_img/zerpensafari-iphone-fca66340-480.avif 480w, /_img/zerpensafari-iphone-fca66340-800.avif 800w" sizes="100vw">
46
+ <source type="image/webp" srcset="/_img/zerpensafari-iphone-881dc739-480.webp 480w, /_img/zerpensafari-iphone-881dc739-800.webp 800w" sizes="100vw">
47
+ <img src="/_img/zerpensafari-iphone-06076855-800.jpg"
48
+ srcset="/_img/zerpensafari-iphone-06076855-480.jpg 480w, /_img/zerpensafari-iphone-06076855-800.jpg 800w"
49
+ sizes="100vw" width="800" height="1739"
50
+ alt="Startseite der ZerpenSafari"
51
+ loading="eager" fetchpriority="high">
52
+ </picture>
53
+ ```
54
+
55
+ The `<img>` fallback keeps the source's own format (JPEG stays JPEG, PNG stays PNG; AVIF and TIFF fall back to JPEG) and always points at a processed variant, never the original. Widths are never upscaled. `width`/`height` are the largest variant's size, so the browser reserves the right space before the image loads (no layout shift). Every attribute you set on the original `<img>` (`alt`, `class`, `id`, `data-*`, …) is kept. A missing `alt` stays missing: [`nera validate`](https://nera.js.org) reports it, the plugin does not invent one.
56
+
57
+ On the field-test site (a German/English blog), the 32 content images went from 4.2 MB of originals to 0.45 MB of AVIF a phone downloads, and the Lighthouse mobile LCP of a blog post dropped from 3.5–3.8 s to 2.6 s; with its teaser image rendered through the mixin as well (see below), to 1.8–1.9 s.
58
+
59
+ ### What is left untouched
60
+
61
+ - SVG and GIF (animation), external `http(s)://` and `//` URLs, `data:` URIs
62
+ - An `<img>` already inside a `<picture>`, or with its own `srcset`
63
+ - An image with `?skip`, or a raw HTML `<img data-nera-skip>` (the attribute is removed from the output)
64
+ - A file that cannot be found: the build warns with the page and the URL and leaves the `<img>` as it is
65
+
66
+ Raw HTML `<img>` in Markdown is handled like a Markdown image. Images in your **Pug templates** are not processed; use frontmatter images and the mixin for those (see below).
67
+
68
+ ## ⚙️ Configuration
69
+
70
+ `config/images.yaml` is optional, and so is every key in it. These are the defaults:
71
+
72
+ ```yaml
73
+ # Which modern formats get a <source>, in order of preference.
74
+ formats: [avif, webp]
75
+ # Candidate widths for srcset (px). Never upscaled.
76
+ widths: [480, 800, 1200, 1600]
77
+ # Default sizes attribute.
78
+ sizes: 100vw
79
+ # Encoder quality per format (1–100). PNG output is lossless.
80
+ quality:
81
+ avif: 50
82
+ webp: 75
83
+ jpeg: 78
84
+ png: 80
85
+ # First image on each page: loading="eager" + fetchpriority="high".
86
+ eager_first: true
87
+ # "title" turns ![alt](src "Caption") into <figure>; false disables it.
88
+ figure: title
89
+ # Frontmatter keys holding an image path → meta.images.<key>. [] disables it.
90
+ frontmatter_keys: [image]
91
+ # og:image preset for frontmatter images; false disables it.
92
+ og:
93
+ width: 1200
94
+ height: 630
95
+ fit: cover
96
+ # Placeholder while an image loads: none | color | blur
97
+ placeholder: none
98
+ # Public URL path for the generated files.
99
+ output_path: /_img
100
+ # Cache folder (relative to the site root), and pruning of unused variants.
101
+ cache_dir: .nera-cache/images
102
+ prune: true
103
+ # Parallel encodes; default: CPU count - 1.
104
+ # concurrency: 4
105
+ ```
106
+
107
+ An invalid value warns and falls back to its default; an unknown key warns too (typo help). Neither fails the build.
108
+
109
+ ## Query parameters
110
+
111
+ Add them to the image URL in Markdown (or in a frontmatter path). They never reach the emitted URLs.
112
+
113
+ | Param | Meaning | Example |
114
+ |---|---|---|
115
+ | `w` | Maximum display width in px. `srcset` gets the configured widths below it plus `w` and `2w` (retina), capped at the source. The default `sizes` becomes `(min-width: {w}px) {w}px, 100vw` | `?w=800` |
116
+ | `h` | Target height; together with `w` it crops by `fit` | `?w=800&h=450` |
117
+ | `ratio` | Crop to an aspect ratio, `W:H` | `?ratio=16:9` |
118
+ | `fit` | `cover` (default when cropping), `contain` (pad) or `inside` (scale into the box) | `?fit=contain` |
119
+ | `focus` | Focal point of a `cover` crop in percent, `x,y` (default `50,50`), or `attention` / `entropy` to let sharp find it | `?focus=30,60` |
120
+ | `q` | Quality for all formats, 1–100 | `?q=60` |
121
+ | `formats` | Modern formats for this image, comma-separated, or `none` for a plain `<img>` with `srcset` | `?formats=webp` |
122
+ | `sizes` | `sizes` for this image (URL-encoded) | `?sizes=50vw` |
123
+ | `loading` | `eager` or `lazy`, overriding the first-image rule | `?loading=eager` |
124
+ | `skip` | Leave this image completely untouched | `?skip` |
125
+
126
+ An unknown parameter, an invalid value (`?w=abc`) or a parameter without effect (`h` without `w`, `focus` without a crop) warns with the page and the URL and is ignored.
127
+
128
+ ## Captions
129
+
130
+ ```md
131
+ ![A pier at dusk](/images/pier.jpg "Usedom, October 2026")
132
+ ```
133
+
134
+ An image with a title that is alone in its paragraph becomes:
135
+
136
+ ```html
137
+ <figure class="nera-image"><picture>…</picture><figcaption class="nera-image__caption">Usedom, October 2026</figcaption></figure>
138
+ ```
139
+
140
+ The `<figure>` replaces the paragraph (a `<figure>` inside `<p>` is invalid HTML), and the `title` attribute is dropped. An image inline with text, inside a link or next to another image keeps its `title` and gets no figure. `figure: false` turns this off. The classes `nera-image` and `nera-image__caption` are part of the public contract: style them freely.
141
+
142
+ ## Frontmatter images and the `+picture` mixin
143
+
144
+ ```yaml
145
+ ---
146
+ title: My post
147
+ image: /images/blog/hero.jpg
148
+ ---
149
+ ```
150
+
151
+ For every key in `frontmatter_keys` (default `[image]`), the plugin generates variants and adds precomputed data next to the original:
152
+
153
+ ```js
154
+ meta.images.image = {
155
+ src, srcset, sizes, width, height, type, // the fallback <img>
156
+ sources: [{ type: 'image/avif', srcset }, { type: 'image/webp', srcset }],
157
+ og: { src, width, height }, // 1200×630 JPEG (the og preset)
158
+ color, blur // only with a placeholder
159
+ }
160
+ ```
161
+
162
+ **`meta.image` itself stays the string you wrote**, so existing templates and plugins keep working. Query parameters work here too (`image: /images/hero.jpg?ratio=16:9&focus=30,60`).
163
+
164
+ Publish the mixin into your views once:
165
+
166
+ ```bash
167
+ npx nera-images
168
+ ```
169
+
170
+ It lands in `views/vendor/plugin-images/picture.pug` (`theme/views/…` on a themed site). Then, in a layout:
171
+
172
+ ```pug
173
+ include /vendor/plugin-images/picture
174
+
175
+ +picture(meta.images && meta.images.image, { alt: meta.image_alt, loading: 'eager' })
176
+ ```
177
+
178
+ **A hero above the content.** `eager_first` gives the first *Markdown* image `fetchpriority="high"`. If your layout renders a teaser or hero image above the content, that one is the page's LCP image: render it with `loading: 'eager'` as above and set `eager_first: false`, so the two do not compete.
179
+
180
+ Options: `alt`, `class`, `sizes` (for a column layout, e.g. `'(min-width: 60em) 50vw, 100vw'`) and `loading` (`lazy` by default; `eager` adds `fetchpriority="high"` for a hero). Extra attributes go onto the `<img>`: `+picture(image, { alt: '' })(data-zoom)`. A missing entry renders nothing.
181
+
182
+ ### `og:image`
183
+
184
+ Core's `base_path` rewriting does not touch `<meta content>`, and `og:image` must be an absolute URL anyway, so add your origin (and `base_path`, if you use one) in the template:
185
+
186
+ ```pug
187
+ if meta.images && meta.images.image && meta.images.image.og
188
+ - const og = meta.images.image.og
189
+ meta(property="og:image" content=`${app.origin}${app.basePath || ''}${og.src}`)
190
+ meta(property="og:image:width" content=og.width)
191
+ meta(property="og:image:height" content=og.height)
192
+ ```
193
+
194
+ ## Placeholders
195
+
196
+ `placeholder: color` sets the image's dominant colour as `style="background-color:#rrggbb"` on the `<img>`; `placeholder: blur` sets a tiny inline WebP as its `background-image` (about 100–300 bytes of HTML per image on real photos). The placeholder is visible only while the image loads. Both apply to Markdown images and to `meta.images` (the mixin renders them).
197
+
198
+ - An image that is not fully opaque (transparency, or `fit=contain` padding) gets **no** placeholder, because the background would stay visible through it after loading.
199
+ - **Content Security Policy:** placeholders are inline `style` attributes. A CSP whose `style-src` lacks `'unsafe-inline'` blocks them. That is why the default is `none`.
200
+
201
+ ## Keeping your originals off the server
202
+
203
+ The plugin reads images from your assets folder **regardless of `.neraignore`**. So if you list your photo folder in `.neraignore`, only the processed, metadata-stripped variants are published, and the originals, with their EXIF and GPS data, never leave your repository:
204
+
205
+ ```gitignore
206
+ # .neraignore (paths relative to the assets folder)
207
+ images/photos
208
+ ```
209
+
210
+ Before you do this, check what else uses that folder. `.neraignore` matches **exact paths and folder prefixes only, no glob patterns**, and everything in a listed folder that the plugin does not process stops being published:
211
+
212
+ - SVG and GIF images, and files you link for download
213
+ - images your **templates** use directly, such as a teaser `img(src=meta.image)` or an `og:image` built from `meta.image`. Render those from `meta.images` instead (the mixin, the `og` snippet above).
214
+
215
+ A folder that holds only Markdown photos is the safe case. On the field-test site, listing all of `images` broke 8 URLs: template teasers and `og:image` tags from `meta.image`, plus two SVG diagrams. To find such URLs, build once and look for `src`, `srcset` and `content` values that point into the ignored folder.
216
+
217
+ ## Cache and CI
218
+
219
+ Variants live in `.nera-cache/images/` (`cache_dir`): `files/` holds the images, `manifest.json` what they were made from. A variant is encoded only when its file is missing, and file names carry a hash of the source and the settings, so URLs are stable across builds and safe to cache forever. Variants no build uses any more are pruned (`prune: true`).
220
+
221
+ A cold build of a site with ~100 images takes a minute or more, because AVIF encoding is slow; a warm build adds well under a second. Keep the cache between CI runs:
222
+
223
+ ```yaml
224
+ # GitHub Actions, before `npm run build`
225
+ - uses: actions/cache@v4
226
+ with:
227
+ path: .nera-cache
228
+ key: nera-images-${{ hashFiles('assets/**', 'theme/assets/**', 'config/images.yaml') }}
229
+ restore-keys: nera-images-
230
+ ```
231
+
232
+ ```yaml
233
+ # GitLab CI, in the build job
234
+ cache:
235
+ - key: nera-images
236
+ paths:
237
+ - .nera-cache/
238
+ ```
239
+
240
+ `nera dev` does not watch the cache folder, so it never causes a rebuild loop.
241
+
242
+ ## Compatibility
243
+
244
+ - **`@nera-static/core` 4.13.0 or later** (the `getAssets` hook, which copies the variants into `public/`). On an older core the build stops with a message naming the required version, rather than publishing pages that link to missing files. A site without any processable image still builds.
245
+ - Node.js 20.18.1 or later.
246
+ - sharp ships prebuilt binaries for macOS, Linux and Windows on x64 and arm64.
247
+
248
+ ## 🧪 Development
249
+
250
+ ```bash
251
+ npx vitest run
252
+ npm run lint
253
+ ```
254
+
255
+ The fixture images are generated by sharp at test time (`test/fixtures/make-images.js`), so no binaries are committed.
256
+
257
+ ## 📦 License
258
+
259
+ MIT
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from 'path'
4
+ import { fileURLToPath } from 'url'
5
+ import { publishTemplates } from '@nera-static/plugin-utils'
6
+
7
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
8
+ const pluginName = 'plugin-images'
9
+ const sourceDir = path.resolve(__dirname, '../views/')
10
+ const force = process.argv.includes('--force')
11
+
12
+ const templateFiles = ['picture.pug']
13
+
14
+ const result = publishTemplates({
15
+ pluginName,
16
+ sourceDir,
17
+ templateFiles,
18
+ force,
19
+ })
20
+
21
+ process.exit(result ? 0 : 1)
package/index.js ADDED
@@ -0,0 +1,234 @@
1
+ // @nera-static/plugin-images — build-time responsive images.
2
+ //
3
+ // `getMetaData` finds every local raster image in the rendered pages,
4
+ // generates its variants into the cache and rewrites the `<img>` as
5
+ // `<picture>` markup; frontmatter images get the same variants as data in
6
+ // `meta.images.<key>`, for the `+picture` mixin, both with an optional
7
+ // placeholder. `getAssets` (core >= 4.13.0) then prunes the cache and
8
+ // hands its files to core, which copies them to `public/<output_path>`.
9
+ // See ROADMAP.md for the decisions (D1–D13) behind each step.
10
+ import fs from 'fs'
11
+ import path from 'path'
12
+ import { openCache } from './src/cache.js'
13
+ import { loadConfig } from './src/config.js'
14
+ import { frontmatterImages } from './src/frontmatter.js'
15
+ import { createGenerator } from './src/generate.js'
16
+ import { assertCoreVersion, coreVersion } from './src/guard.js'
17
+ import { parseParams, sizesFor, stripParams } from './src/params.js'
18
+ import { createQueue } from './src/queue.js'
19
+ import { resolveSource, sourceRoots, splitUrl } from './src/resolve-source.js'
20
+ import { pictureData, publicUrl, rewriteHtml } from './src/rewrite-html.js'
21
+ import { warn } from './src/warn.js'
22
+
23
+ // What `getMetaData` leaves for `getAssets` in the same build. Core calls the
24
+ // two hooks in that order, once per build, so one slot is enough.
25
+ let current = null
26
+
27
+ /**
28
+ * Throws (once per build, then again for every later image) when core is too
29
+ * old to call `getAssets` (D12). Checked on the first image that will be
30
+ * generated, before anything is encoded, so a site without images still
31
+ * builds on an older core (decided 2026-10-09).
32
+ */
33
+ function coreCheck(cwd) {
34
+ let result
35
+ return () => {
36
+ if (result === undefined) {
37
+ const version = coreVersion(cwd)
38
+ if (version === null) {
39
+ warn('could not determine the @nera-static/core version; it must be >= 4.13.0')
40
+ }
41
+ try {
42
+ assertCoreVersion(version)
43
+ result = null
44
+ } catch (err) {
45
+ result = err
46
+ }
47
+ }
48
+ if (result) throw result
49
+ }
50
+ }
51
+
52
+ export async function getMetaData({ app, pagesData }) {
53
+ const cwd = process.cwd()
54
+ const config = loadConfig({ cwd, app })
55
+ const roots = sourceRoots({ app, cwd })
56
+ const cache = openCache(path.resolve(cwd, config.cache_dir))
57
+ const generator = createGenerator({
58
+ cache,
59
+ queue: createQueue({ concurrency: config.concurrency }),
60
+ })
61
+ const ensureCore = coreCheck(cwd)
62
+ const options = {
63
+ widths: config.widths,
64
+ formats: config.formats,
65
+ quality: config.quality,
66
+ }
67
+ // D10. The og image (D9) gets none: it is a file for crawlers, not markup.
68
+ const placeholder = { placeholder: config.placeholder }
69
+ current = null
70
+
71
+ // What one URL on one page means: `null` (not ours, or left as is with a
72
+ // warning), `{ skip }` (`?skip`, with the recognized parameters stripped)
73
+ // or `{ file, params }`, ready to generate. Shared by both passes so a
74
+ // frontmatter path reads exactly like a Markdown image URL.
75
+ const prepare = (src, href, label) => {
76
+ const resolved = resolveSource(src, {
77
+ pageHref: href,
78
+ basePath: app.basePath || '',
79
+ roots,
80
+ })
81
+ // Not a local URL: neither the file nor the query is ours.
82
+ if (['empty', 'external', 'data'].includes(resolved.skip)) return null
83
+
84
+ const params = parseParams(splitUrl(src.trim()).search)
85
+ if (params.skip) return { skip: stripParams(src) }
86
+
87
+ if (resolved.skip) {
88
+ if (resolved.skip === 'missing' || resolved.skip === 'outside') {
89
+ warn(`${href}: ${label}not found, left as is: ${src}`)
90
+ }
91
+ return null
92
+ }
93
+ for (const message of params.warnings) {
94
+ warn(`${href}: ${message}: ${src}`)
95
+ }
96
+ ensureCore()
97
+ return { file: resolved.file, params }
98
+ }
99
+
100
+ let images = 0
101
+ const result = []
102
+ // Pages one after another, a page's images concurrently: the queue bounds
103
+ // the encoders, and only one page's source bytes are held at a time.
104
+ for (const page of pagesData) {
105
+ const href = page.meta?.href || '/index.html'
106
+
107
+ const handle = async (src) => {
108
+ const prepared = prepare(src, href, 'image ')
109
+ if (!prepared || prepared.skip) return prepared && { src: prepared.skip }
110
+ try {
111
+ const image = await generator.generate(prepared.file, {
112
+ ...options,
113
+ ...prepared.params.options,
114
+ }, placeholder)
115
+ return {
116
+ image,
117
+ sizes: sizesFor(prepared.params, config.sizes),
118
+ loading: prepared.params.loading,
119
+ }
120
+ } catch (err) {
121
+ warn(`${href}: could not process ${src}, left as is (${err.message})`)
122
+ return null
123
+ }
124
+ }
125
+
126
+ // D9: `meta.images.<key>` from the frontmatter keys. The `<img>`
127
+ // attributes a template sets itself (`loading`, `alt`) are the mixin's
128
+ // business, so `?loading` has nothing to act on here.
129
+ const prepareFrontmatter = async (key, src) => {
130
+ const prepared = prepare(src, href, `frontmatter ${key} `)
131
+ if (!prepared || prepared.skip) return null
132
+ const { params } = prepared
133
+ if (params.loading) {
134
+ warn(`${href}: loading has no effect on a frontmatter image, ignored: ${src}`)
135
+ }
136
+ try {
137
+ const image = await generator.generate(prepared.file, {
138
+ ...options,
139
+ ...params.options,
140
+ }, placeholder)
141
+ const entry = pictureData(image, {
142
+ outputPath: config.output_path,
143
+ sizes: sizesFor(params, config.sizes),
144
+ })
145
+ if (config.og) {
146
+ entry.og = await ogImage(generator, prepared.file, config, params)
147
+ }
148
+ return entry
149
+ } catch (err) {
150
+ warn(`${href}: could not process frontmatter ${key} ${src} (${err.message})`)
151
+ return null
152
+ }
153
+ }
154
+
155
+ const [rewritten, frontmatter] = await Promise.all([
156
+ rewriteHtml(page.content, {
157
+ handle,
158
+ outputPath: config.output_path,
159
+ sizes: config.sizes,
160
+ eagerFirst: config.eager_first,
161
+ figure: config.figure,
162
+ }),
163
+ frontmatterImages(page.meta, {
164
+ keys: config.frontmatter_keys,
165
+ prepare: prepareFrontmatter,
166
+ }),
167
+ ])
168
+ images += rewritten.count + frontmatter.count
169
+
170
+ const changed = rewritten.html !== page.content || frontmatter.meta !== page.meta
171
+ result.push(
172
+ changed ? { ...page, content: rewritten.html, meta: frontmatter.meta } : page
173
+ )
174
+ }
175
+
176
+ current = { config, cache, generator }
177
+ if (images > 0) {
178
+ const placeholders = config.placeholder === 'none'
179
+ ? ''
180
+ : `, ${generator.placeholders} placeholder(s) computed`
181
+ console.log(
182
+ `🖼️ plugin-images: ${images} image(s), ${generator.encoded} variant(s) encoded${placeholders}`
183
+ )
184
+ }
185
+ return result
186
+ }
187
+
188
+ /**
189
+ * The og preset (D9): one JPEG at `og.width` × `og.height` with `og.fit`,
190
+ * never upscaled. Only the frontmatter path's `focus` and `q` carry over; its
191
+ * own geometry (`w`, `ratio`, …) is for the page, not for the social card.
192
+ */
193
+ async function ogImage(generator, file, config, params) {
194
+ const { width, height, fit } = config.og
195
+ const { focus, q } = params.options
196
+ const image = await generator.generate(file, {
197
+ widths: [width],
198
+ formats: [],
199
+ quality: config.quality,
200
+ ratio: width / height,
201
+ fit,
202
+ focus,
203
+ q,
204
+ fallback: 'jpeg',
205
+ })
206
+ const [variant] = image.variants
207
+ return {
208
+ src: publicUrl(config.output_path, variant.file),
209
+ width: variant.width,
210
+ height: variant.height,
211
+ }
212
+ }
213
+
214
+ export async function getAssets() {
215
+ if (!current) return []
216
+ const { config, cache, generator } = current
217
+ current = null
218
+
219
+ const used = generator.usedKeys()
220
+ // A site that never had an image gets no cache folder at all.
221
+ if (used.length > 0 || fs.existsSync(cache.dir)) {
222
+ try {
223
+ if (config.prune) cache.prune(used)
224
+ cache.save()
225
+ } catch (err) {
226
+ // The variants on disk are complete (atomic writes); a stale
227
+ // manifest only costs a re-check next build. Not worth failing.
228
+ warn(`could not update the image cache (${err.message})`)
229
+ }
230
+ }
231
+
232
+ if (used.length === 0 || !fs.existsSync(cache.filesDir)) return []
233
+ return [{ from: cache.filesDir, to: config.output_path.slice(1) }]
234
+ }
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
- "name": "@nera-static/plugin-images",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@nera-static/plugin-images",
3
+ "version": "1.0.0",
4
+ "description": "A plugin for Nera static site generator to generate responsive, modern-format images (AVIF/WebP, srcset, width/height, lazy loading) at build time.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "publish-template": "node ./bin/publish-template.js",
8
+ "lint": "eslint .",
9
+ "test": "vitest",
10
+ "prepare": "husky"
11
+ },
12
+ "type": "module",
13
+ "exports": {
14
+ ".": "./index.js"
15
+ },
16
+ "bin": {
17
+ "nera-images": "./bin/publish-template.js"
18
+ },
19
+ "files": [
20
+ "bin",
21
+ "index.js",
22
+ "src",
23
+ "views",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "keywords": [
27
+ "nera",
28
+ "nera-plugin",
29
+ "static-site-generator",
30
+ "images",
31
+ "responsive-images",
32
+ "srcset",
33
+ "avif",
34
+ "webp",
35
+ "sharp"
36
+ ],
37
+ "author": "Michael Becker",
38
+ "license": "MIT",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/seebaermichi/nera-plugin-images"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/seebaermichi/nera-plugin-images/issues"
45
+ },
46
+ "homepage": "https://github.com/seebaermichi/nera-plugin-images#readme",
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "peerDependencies": {
51
+ "@nera-static/core": ">=4.13.0"
52
+ },
53
+ "dependencies": {
54
+ "@nera-static/plugin-utils": "^1.6.1",
55
+ "cheerio": "^1.2.0",
56
+ "sharp": "^0.35.5"
57
+ },
58
+ "engines": {
59
+ "node": ">=20.18.1"
60
+ },
61
+ "devDependencies": {
62
+ "@nera-static/core": "^4.13.0",
63
+ "eslint": "^10.8.0",
64
+ "husky": "^9.1.7",
65
+ "pug": "^3.0.4",
66
+ "vitest": "^5.0.0"
67
+ },
68
+ "sideEffects": false
69
+ }