@nera-static/plugin-images 0.0.0-stage → 1.0.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/CHANGELOG.md +71 -0
- package/LICENSE +21 -0
- package/README.md +258 -2
- package/bin/publish-template.js +21 -0
- package/index.js +234 -0
- package/package.json +68 -5
- package/src/cache.js +161 -0
- package/src/config.js +208 -0
- package/src/frontmatter.js +50 -0
- package/src/generate.js +105 -0
- package/src/guard.js +73 -0
- package/src/params.js +173 -0
- package/src/queue.js +61 -0
- package/src/resolve-source.js +135 -0
- package/src/rewrite-html.js +294 -0
- package/src/transform.js +282 -0
- package/src/warn.js +6 -0
- package/views/picture.pug +42 -0
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@nera-static/plugin-images",
|
|
3
|
+
"version": "1.0.1",
|
|
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
|
+
}
|
package/src/cache.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import crypto from 'crypto'
|
|
2
|
+
import fs from 'fs'
|
|
3
|
+
import path from 'path'
|
|
4
|
+
import { slugify } from '@nera-static/plugin-utils'
|
|
5
|
+
import { EXTENSIONS } from './transform.js'
|
|
6
|
+
import { warn } from './warn.js'
|
|
7
|
+
|
|
8
|
+
// The variant cache (ROADMAP D3, D4): `<dir>/files/` holds every generated
|
|
9
|
+
// file, `<dir>/manifest.json` one entry per image. A variant is encoded only
|
|
10
|
+
// when its file is missing, and pruning removes what a build did not use.
|
|
11
|
+
|
|
12
|
+
// Bump when the encoder's output changes for the same inputs (new sharp
|
|
13
|
+
// settings, a fixed crop bug). It feeds every hash, so all names change and
|
|
14
|
+
// the next build re-encodes; pruning then removes the old files.
|
|
15
|
+
export const CACHE_VERSION = 1
|
|
16
|
+
|
|
17
|
+
const MANIFEST = 'manifest.json'
|
|
18
|
+
|
|
19
|
+
const sha256 = (...parts) => {
|
|
20
|
+
const hash = crypto.createHash('sha256')
|
|
21
|
+
for (const part of parts) hash.update(part)
|
|
22
|
+
return hash.digest('hex')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// JSON with sorted keys and `undefined` dropped, so two option objects that
|
|
26
|
+
// mean the same thing hash the same regardless of key order.
|
|
27
|
+
export function stableStringify(value) {
|
|
28
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
|
|
29
|
+
if (value !== null && typeof value === 'object') {
|
|
30
|
+
const entries = Object.keys(value)
|
|
31
|
+
.filter((key) => value[key] !== undefined)
|
|
32
|
+
.sort()
|
|
33
|
+
.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`)
|
|
34
|
+
return `{${entries.join(',')}}`
|
|
35
|
+
}
|
|
36
|
+
return JSON.stringify(value)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** sha256 hex of the source bytes. */
|
|
40
|
+
export function sourceDigest(bytes) {
|
|
41
|
+
return sha256(bytes)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Manifest key of one image: the source plus every option that shapes its
|
|
46
|
+
* set of files (widths, formats, quality, geometry).
|
|
47
|
+
*/
|
|
48
|
+
export function imageKey(digest, options) {
|
|
49
|
+
return sha256(digest, '\0', stableStringify(options), '\0', String(CACHE_VERSION))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* D3 `hash8` of one variant: source bytes + transform parameters + cache
|
|
54
|
+
* version. Width is left out on purpose, it is part of the file name, so all
|
|
55
|
+
* widths of one format share a hash and the files sort together.
|
|
56
|
+
*/
|
|
57
|
+
export function variantHash(digest, { format, quality, fit, crop, aspect }) {
|
|
58
|
+
const params = stableStringify({ format, quality, fit, crop, aspect })
|
|
59
|
+
return sha256(digest, '\0', params, '\0', String(CACHE_VERSION)).slice(0, 8)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* `<basename>-<hash8>-<width>.<ext>` (D3). The basename is slugified so a
|
|
64
|
+
* photo named `Straße am Meer.JPG` yields a URL that needs no escaping;
|
|
65
|
+
* a name with nothing usable left becomes `image`.
|
|
66
|
+
*/
|
|
67
|
+
export function variantFileName(source, hash8, { width, format }) {
|
|
68
|
+
const base = slugify(path.parse(source).name) || 'image'
|
|
69
|
+
return `${base}-${hash8}-${width}.${EXTENSIONS[format]}`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readManifest(file) {
|
|
73
|
+
let raw
|
|
74
|
+
try {
|
|
75
|
+
raw = fs.readFileSync(file, 'utf-8')
|
|
76
|
+
} catch {
|
|
77
|
+
return {}
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const parsed = JSON.parse(raw)
|
|
81
|
+
if (parsed?.version === CACHE_VERSION && parsed.entries && typeof parsed.entries === 'object') {
|
|
82
|
+
return parsed.entries
|
|
83
|
+
}
|
|
84
|
+
} catch {
|
|
85
|
+
warn(`ignoring unreadable cache manifest ${file}`)
|
|
86
|
+
}
|
|
87
|
+
// Another cache version or a broken file: start empty. Nothing references
|
|
88
|
+
// the old files any more, so the next prune removes them.
|
|
89
|
+
return {}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function writeAtomic(file, content) {
|
|
93
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
94
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
95
|
+
fs.writeFileSync(temp, content)
|
|
96
|
+
fs.renameSync(temp, file)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Open (or start) the cache at `dir`.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} dir absolute cache directory (config `cache_dir`, resolved)
|
|
103
|
+
*/
|
|
104
|
+
export function openCache(dir) {
|
|
105
|
+
const filesDir = path.join(dir, 'files')
|
|
106
|
+
const manifestFile = path.join(dir, MANIFEST)
|
|
107
|
+
const entries = readManifest(manifestFile)
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
dir,
|
|
111
|
+
filesDir,
|
|
112
|
+
|
|
113
|
+
filePath: (name) => path.join(filesDir, name),
|
|
114
|
+
hasFile: (name) => fs.existsSync(path.join(filesDir, name)),
|
|
115
|
+
|
|
116
|
+
has: (key) => Object.hasOwn(entries, key),
|
|
117
|
+
get: (key) => entries[key],
|
|
118
|
+
put(key, entry) {
|
|
119
|
+
entries[key] = entry
|
|
120
|
+
},
|
|
121
|
+
keys: () => Object.keys(entries),
|
|
122
|
+
|
|
123
|
+
/** Write the manifest (temp file + rename, so it is never half-written). */
|
|
124
|
+
save() {
|
|
125
|
+
const sorted = Object.fromEntries(
|
|
126
|
+
Object.keys(entries).sort().map((key) => [key, entries[key]])
|
|
127
|
+
)
|
|
128
|
+
writeAtomic(
|
|
129
|
+
manifestFile,
|
|
130
|
+
`${JSON.stringify({ version: CACHE_VERSION, entries: sorted }, null, 2)}\n`
|
|
131
|
+
)
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Drop every manifest entry not in `usedKeys`, then every file in
|
|
136
|
+
* `files/` that no remaining entry lists (D4). Builds are always full,
|
|
137
|
+
* so "unused this build" means "unused". Returns what was removed.
|
|
138
|
+
*
|
|
139
|
+
* @param {Iterable<string>} usedKeys
|
|
140
|
+
* @returns {{ entries: string[], files: string[] }}
|
|
141
|
+
*/
|
|
142
|
+
prune(usedKeys) {
|
|
143
|
+
const used = new Set(usedKeys)
|
|
144
|
+
const removedEntries = Object.keys(entries).filter((key) => !used.has(key))
|
|
145
|
+
for (const key of removedEntries) delete entries[key]
|
|
146
|
+
|
|
147
|
+
const keep = new Set(Object.values(entries).flatMap((entry) => entry.files || []))
|
|
148
|
+
let present = []
|
|
149
|
+
try {
|
|
150
|
+
present = fs.readdirSync(filesDir)
|
|
151
|
+
} catch {
|
|
152
|
+
// No files yet.
|
|
153
|
+
}
|
|
154
|
+
const removedFiles = present.filter((name) => !keep.has(name)).sort()
|
|
155
|
+
for (const name of removedFiles) {
|
|
156
|
+
fs.rmSync(path.join(filesDir, name), { recursive: true, force: true })
|
|
157
|
+
}
|
|
158
|
+
return { entries: removedEntries.sort(), files: removedFiles }
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import os from 'os'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import { getConfig } from '@nera-static/plugin-utils'
|
|
4
|
+
import { warn } from './warn.js'
|
|
5
|
+
|
|
6
|
+
// `config/images.yaml` is optional and every key has a default (ROADMAP
|
|
7
|
+
// "Configuration"). `getConfig` returns `{}` for a missing file, so each key
|
|
8
|
+
// gets its own JS fallback here. A key with a bad value warns and falls back to
|
|
9
|
+
// its default rather than failing the build: a typo in an image config must not
|
|
10
|
+
// take the site down.
|
|
11
|
+
|
|
12
|
+
export const MODERN_FORMATS = ['avif', 'webp']
|
|
13
|
+
export const QUALITY_FORMATS = ['avif', 'webp', 'jpeg', 'png']
|
|
14
|
+
export const FITS = ['cover', 'contain', 'inside']
|
|
15
|
+
export const PLACEHOLDERS = ['none', 'color', 'blur']
|
|
16
|
+
|
|
17
|
+
export function defaultConcurrency() {
|
|
18
|
+
return Math.max(1, os.availableParallelism() - 1)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function defaults() {
|
|
22
|
+
return {
|
|
23
|
+
formats: ['avif', 'webp'],
|
|
24
|
+
widths: [480, 800, 1200, 1600],
|
|
25
|
+
sizes: '100vw',
|
|
26
|
+
quality: { avif: 50, webp: 75, jpeg: 78, png: 80 },
|
|
27
|
+
eager_first: true,
|
|
28
|
+
figure: 'title',
|
|
29
|
+
frontmatter_keys: ['image'],
|
|
30
|
+
og: { width: 1200, height: 630, fit: 'cover' },
|
|
31
|
+
placeholder: 'none',
|
|
32
|
+
output_path: '/_img',
|
|
33
|
+
cache_dir: '.nera-cache/images',
|
|
34
|
+
prune: true,
|
|
35
|
+
concurrency: defaultConcurrency(),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const isPlainObject = (value) =>
|
|
40
|
+
value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
41
|
+
|
|
42
|
+
const isPositiveInt = (value) => Number.isInteger(value) && value > 0
|
|
43
|
+
|
|
44
|
+
const isQuality = (value) => Number.isInteger(value) && value >= 1 && value <= 100
|
|
45
|
+
|
|
46
|
+
const show = (value) => JSON.stringify(value)
|
|
47
|
+
|
|
48
|
+
function bad(key, value, fallback) {
|
|
49
|
+
warn(
|
|
50
|
+
`config/images.yaml: invalid ${key} ${show(value)}, using ${show(fallback)}`
|
|
51
|
+
)
|
|
52
|
+
return fallback
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readFormats(value, fallback) {
|
|
56
|
+
if (!Array.isArray(value)) return bad('formats', value, fallback)
|
|
57
|
+
|
|
58
|
+
const formats = []
|
|
59
|
+
for (const format of value) {
|
|
60
|
+
if (!MODERN_FORMATS.includes(format)) {
|
|
61
|
+
warn(
|
|
62
|
+
`config/images.yaml: ignoring unknown format ${show(format)} (supported: ${MODERN_FORMATS.join(', ')})`
|
|
63
|
+
)
|
|
64
|
+
} else if (!formats.includes(format)) {
|
|
65
|
+
formats.push(format)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// An explicit `[]` is valid: plain `<img>` with srcset, no `<source>`.
|
|
69
|
+
return formats
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readWidths(value, fallback) {
|
|
73
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
74
|
+
return bad('widths', value, fallback)
|
|
75
|
+
}
|
|
76
|
+
const widths = value.filter(isPositiveInt)
|
|
77
|
+
if (widths.length === 0) return bad('widths', value, fallback)
|
|
78
|
+
if (widths.length !== value.length) {
|
|
79
|
+
warn(
|
|
80
|
+
`config/images.yaml: ignoring widths that are not positive integers in ${show(value)}`
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return [...new Set(widths)].sort((a, b) => a - b)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readQuality(value, fallback) {
|
|
88
|
+
if (!isPlainObject(value)) return bad('quality', value, fallback)
|
|
89
|
+
|
|
90
|
+
const quality = { ...fallback }
|
|
91
|
+
for (const [format, q] of Object.entries(value)) {
|
|
92
|
+
if (!QUALITY_FORMATS.includes(format)) {
|
|
93
|
+
warn(`config/images.yaml: ignoring quality for unknown format ${show(format)}`)
|
|
94
|
+
} else if (!isQuality(q)) {
|
|
95
|
+
quality[format] = bad(`quality.${format}`, q, fallback[format])
|
|
96
|
+
} else {
|
|
97
|
+
quality[format] = q
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return quality
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function readOg(value, fallback) {
|
|
104
|
+
if (value === false) return false
|
|
105
|
+
if (!isPlainObject(value)) return bad('og', value, fallback)
|
|
106
|
+
|
|
107
|
+
const og = { ...fallback }
|
|
108
|
+
for (const key of ['width', 'height']) {
|
|
109
|
+
if (value[key] === undefined) continue
|
|
110
|
+
og[key] = isPositiveInt(value[key])
|
|
111
|
+
? value[key]
|
|
112
|
+
: bad(`og.${key}`, value[key], fallback[key])
|
|
113
|
+
}
|
|
114
|
+
if (value.fit !== undefined) {
|
|
115
|
+
og.fit = FITS.includes(value.fit)
|
|
116
|
+
? value.fit
|
|
117
|
+
: bad('og.fit', value.fit, fallback.fit)
|
|
118
|
+
}
|
|
119
|
+
return og
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// `/_img`, `_img/`, `/a/b/` → `/_img`, `/a/b`. A root-absolute URL path
|
|
123
|
+
// without a trailing slash, so `${output_path}/${file}` is always right.
|
|
124
|
+
function readOutputPath(value, fallback) {
|
|
125
|
+
if (typeof value !== 'string') return bad('output_path', value, fallback)
|
|
126
|
+
|
|
127
|
+
const segments = value.split('/').filter(Boolean)
|
|
128
|
+
if (segments.length === 0 || segments.some((s) => s === '.' || s === '..')) {
|
|
129
|
+
return bad('output_path', value, fallback)
|
|
130
|
+
}
|
|
131
|
+
return `/${segments.join('/')}`
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function readCacheDir(value, fallback) {
|
|
135
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
136
|
+
return bad('cache_dir', value, fallback)
|
|
137
|
+
}
|
|
138
|
+
return value.trim()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const readers = {
|
|
142
|
+
formats: readFormats,
|
|
143
|
+
widths: readWidths,
|
|
144
|
+
quality: readQuality,
|
|
145
|
+
og: readOg,
|
|
146
|
+
output_path: readOutputPath,
|
|
147
|
+
cache_dir: readCacheDir,
|
|
148
|
+
sizes: (value, fallback) =>
|
|
149
|
+
typeof value === 'string' && value.trim() !== ''
|
|
150
|
+
? value.trim()
|
|
151
|
+
: bad('sizes', value, fallback),
|
|
152
|
+
eager_first: (value, fallback) =>
|
|
153
|
+
typeof value === 'boolean' ? value : bad('eager_first', value, fallback),
|
|
154
|
+
prune: (value, fallback) =>
|
|
155
|
+
typeof value === 'boolean' ? value : bad('prune', value, fallback),
|
|
156
|
+
figure: (value, fallback) =>
|
|
157
|
+
value === 'title' || value === false ? value : bad('figure', value, fallback),
|
|
158
|
+
frontmatter_keys: (value, fallback) =>
|
|
159
|
+
Array.isArray(value) && value.every((k) => typeof k === 'string' && k !== '')
|
|
160
|
+
? [...new Set(value)]
|
|
161
|
+
: bad('frontmatter_keys', value, fallback),
|
|
162
|
+
placeholder: (value, fallback) =>
|
|
163
|
+
PLACEHOLDERS.includes(value) ? value : bad('placeholder', value, fallback),
|
|
164
|
+
concurrency: (value, fallback) =>
|
|
165
|
+
isPositiveInt(value) ? value : bad('concurrency', value, fallback),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Merge a raw config object over the defaults, key by key, with validation.
|
|
170
|
+
* Pure apart from warnings; `normalizeConfig({})` is the full default config.
|
|
171
|
+
*
|
|
172
|
+
* @param {object} raw parsed `config/images.yaml` (anything `getConfig` returns)
|
|
173
|
+
* @returns {object} complete, validated config
|
|
174
|
+
*/
|
|
175
|
+
export function normalizeConfig(raw) {
|
|
176
|
+
const config = defaults()
|
|
177
|
+
if (raw === null || raw === undefined) return config
|
|
178
|
+
if (!isPlainObject(raw)) {
|
|
179
|
+
warn('config/images.yaml: expected a mapping at the top level, using defaults')
|
|
180
|
+
return config
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
184
|
+
const read = readers[key]
|
|
185
|
+
if (!read) {
|
|
186
|
+
warn(`config/images.yaml: ignoring unknown key ${show(key)}`)
|
|
187
|
+
continue
|
|
188
|
+
}
|
|
189
|
+
// A key present but empty (`widths:` with nothing after it) reads as
|
|
190
|
+
// null; treat it like an absent key rather than an invalid one.
|
|
191
|
+
if (value === null) continue
|
|
192
|
+
config[key] = read(value, config[key])
|
|
193
|
+
}
|
|
194
|
+
return config
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Read and normalize the site's `config/images.yaml`. Called inside the hook,
|
|
199
|
+
* not at module scope, so each build (and each test) sees the current file.
|
|
200
|
+
*
|
|
201
|
+
* @param {{ cwd?: string, app?: object }} [options] `app.folders.config` is
|
|
202
|
+
* honoured when set, like the rest of the pipeline
|
|
203
|
+
* @returns {object} complete, validated config
|
|
204
|
+
*/
|
|
205
|
+
export function loadConfig({ cwd = process.cwd(), app } = {}) {
|
|
206
|
+
const folder = app?.folders?.config || 'config'
|
|
207
|
+
return normalizeConfig(getConfig(path.resolve(cwd, folder, 'images.yaml')))
|
|
208
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { warn } from './warn.js'
|
|
2
|
+
|
|
3
|
+
// Frontmatter images (ROADMAP D9): for each configured key holding an image
|
|
4
|
+
// path, the plugin prepares variants and writes the data a template needs to
|
|
5
|
+
// `meta.images.<key>`. The original `meta.<key>` string is never modified:
|
|
6
|
+
// canonical-links, social plugins and existing templates keep reading it.
|
|
7
|
+
|
|
8
|
+
const isPlainObject = (value) =>
|
|
9
|
+
value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Prepare every configured frontmatter image of one page.
|
|
13
|
+
*
|
|
14
|
+
* `prepare(key, src)` resolves and generates one image and answers with its
|
|
15
|
+
* `meta.images` entry, or `null` (external, SVG, missing file, `?skip`: the
|
|
16
|
+
* callback decides and warns). Non-string values are not image paths and are
|
|
17
|
+
* passed over silently. Keys are prepared concurrently; the entries are
|
|
18
|
+
* assembled in `keys` order, so the result does not depend on encode timing.
|
|
19
|
+
*
|
|
20
|
+
* @param {object} meta the page's meta
|
|
21
|
+
* @param {object} options
|
|
22
|
+
* @param {string[]} options.keys config `frontmatter_keys`
|
|
23
|
+
* @param {(key: string, src: string) => Promise<object|null>} options.prepare
|
|
24
|
+
* @returns {Promise<{ meta: object, count: number }>} `meta` is the input
|
|
25
|
+
* itself (same object) when no image was prepared
|
|
26
|
+
*/
|
|
27
|
+
export async function frontmatterImages(meta, { keys, prepare }) {
|
|
28
|
+
const wanted = keys.filter((key) => typeof meta?.[key] === 'string' && meta[key].trim() !== '')
|
|
29
|
+
if (wanted.length === 0) return { meta, count: 0 }
|
|
30
|
+
|
|
31
|
+
const existing = meta.images
|
|
32
|
+
if (existing !== undefined && !isPlainObject(existing)) {
|
|
33
|
+
// An author's own `images:` (a gallery list, say) is theirs; merging
|
|
34
|
+
// into it or replacing it would break the page's templates.
|
|
35
|
+
warn(
|
|
36
|
+
`${meta.href || '/index.html'}: meta.images is already set by the page and is not a mapping, frontmatter images not prepared`
|
|
37
|
+
)
|
|
38
|
+
return { meta, count: 0 }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const entries = await Promise.all(wanted.map((key) => prepare(key, meta[key])))
|
|
42
|
+
const images = {}
|
|
43
|
+
wanted.forEach((key, i) => {
|
|
44
|
+
if (entries[i]) images[key] = entries[i]
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
const count = Object.keys(images).length
|
|
48
|
+
if (count === 0) return { meta, count }
|
|
49
|
+
return { meta: { ...meta, images: { ...existing, ...images } }, count }
|
|
50
|
+
}
|
package/src/generate.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import { imageKey, sourceDigest, variantFileName, variantHash } from './cache.js'
|
|
3
|
+
import { encodeVariant, placeholderOf, planVariants, readSourceMeta } from './transform.js'
|
|
4
|
+
|
|
5
|
+
// One image in, its variants on disk and a manifest entry out. Ties the cache,
|
|
6
|
+
// the plan, the queue and the encoder together; the content pass (slice 3)
|
|
7
|
+
// and the frontmatter pass (slice 5) both go through here.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {object} deps
|
|
11
|
+
* @param {ReturnType<import('./cache.js').openCache>} deps.cache
|
|
12
|
+
* @param {ReturnType<import('./queue.js').createQueue>} deps.queue
|
|
13
|
+
* @param {typeof encodeVariant} [deps.encode] injectable for tests
|
|
14
|
+
* @param {typeof placeholderOf} [deps.placeholder] injectable for tests
|
|
15
|
+
*/
|
|
16
|
+
export function createGenerator({ cache, queue, encode = encodeVariant, placeholder = placeholderOf }) {
|
|
17
|
+
const used = new Set()
|
|
18
|
+
let encoded = 0
|
|
19
|
+
let placeholders = 0
|
|
20
|
+
|
|
21
|
+
// A placeholder (D10) from the manifest when the entry already has one for
|
|
22
|
+
// this mode (or knows the image is transparent), otherwise computed once
|
|
23
|
+
// per build and image (queue key) and stored with the entry.
|
|
24
|
+
const placeholderFor = (key, bytes, largest, mode) => {
|
|
25
|
+
const previous = cache.get(key)
|
|
26
|
+
if (previous?.transparent) return { transparent: true }
|
|
27
|
+
if (previous?.[mode] !== undefined) return { [mode]: previous[mode] }
|
|
28
|
+
return queue.add(async () => {
|
|
29
|
+
const result = await placeholder(bytes, largest, mode)
|
|
30
|
+
placeholders++
|
|
31
|
+
return result
|
|
32
|
+
}, `placeholder:${mode}:${key}`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Make sure every variant of `file` under `options` exists in the cache.
|
|
37
|
+
*
|
|
38
|
+
* The source is re-hashed on every call (D4: cheap next to encoding), and
|
|
39
|
+
* only variants whose file is missing are encoded. Variants shared with
|
|
40
|
+
* another page or image are encoded once (queue keyed by file name).
|
|
41
|
+
*
|
|
42
|
+
* The placeholder mode is not part of the manifest key: it adds data to
|
|
43
|
+
* the entry but changes none of its files, so switching it on keeps every
|
|
44
|
+
* cached variant.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} file absolute source path
|
|
47
|
+
* @param {object} options planVariants options
|
|
48
|
+
* @param {{ placeholder?: 'none'|'color'|'blur' }} [extra]
|
|
49
|
+
* @returns {Promise<{ key, width, height, files, source, variants, color?, blur?, transparent? }>}
|
|
50
|
+
* `width`/`height` are the largest variant's (D6); every variant
|
|
51
|
+
* carries its cache `file` name
|
|
52
|
+
*/
|
|
53
|
+
async function generate(file, options, { placeholder: mode = 'none' } = {}) {
|
|
54
|
+
const bytes = await fs.promises.readFile(file)
|
|
55
|
+
const digest = sourceDigest(bytes)
|
|
56
|
+
const key = imageKey(digest, options)
|
|
57
|
+
used.add(key)
|
|
58
|
+
|
|
59
|
+
const source = await readSourceMeta(bytes)
|
|
60
|
+
const variants = planVariants(source, options).map((variant) => ({
|
|
61
|
+
...variant,
|
|
62
|
+
file: variantFileName(file, variantHash(digest, variant), variant),
|
|
63
|
+
}))
|
|
64
|
+
|
|
65
|
+
const largest = variants.reduce((a, b) => (b.width > a.width ? b : a))
|
|
66
|
+
|
|
67
|
+
const [extra] = await Promise.all([
|
|
68
|
+
mode === 'none' ? {} : placeholderFor(key, bytes, largest, mode),
|
|
69
|
+
...variants
|
|
70
|
+
.filter((variant) => !cache.hasFile(variant.file))
|
|
71
|
+
.map((variant) =>
|
|
72
|
+
queue.add(async () => {
|
|
73
|
+
await encode(bytes, variant, cache.filePath(variant.file))
|
|
74
|
+
encoded++
|
|
75
|
+
}, variant.file)
|
|
76
|
+
),
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
// Only the placeholder of the current mode is kept, so the manifest
|
|
80
|
+
// never carries data the build does not use.
|
|
81
|
+
const entry = {
|
|
82
|
+
width: largest.width,
|
|
83
|
+
height: largest.height,
|
|
84
|
+
files: [...new Set(variants.map((variant) => variant.file))],
|
|
85
|
+
...extra,
|
|
86
|
+
}
|
|
87
|
+
cache.put(key, entry)
|
|
88
|
+
|
|
89
|
+
return { key, ...entry, source, variants }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
generate,
|
|
94
|
+
/** Manifest keys touched by this build, for `cache.prune`. */
|
|
95
|
+
usedKeys: () => [...used],
|
|
96
|
+
/** Variants actually encoded by this generator (not served from cache). */
|
|
97
|
+
get encoded() {
|
|
98
|
+
return encoded
|
|
99
|
+
},
|
|
100
|
+
/** Placeholders actually computed by this generator (not from the manifest). */
|
|
101
|
+
get placeholders() {
|
|
102
|
+
return placeholders
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
}
|
package/src/guard.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createRequire } from 'module'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
|
|
4
|
+
// D12 runtime safety net. The plugin rewrites pages to reference files it only
|
|
5
|
+
// hands to core through `getAssets`, which core calls from 4.13.0 on. On an
|
|
6
|
+
// older core the hook is never called, every rewritten page points at missing
|
|
7
|
+
// files, and the build would still exit 0. So the plugin checks core's version
|
|
8
|
+
// and fails loudly instead. `peerDependencies` reports the same at install
|
|
9
|
+
// time; this catches an install that ignored it.
|
|
10
|
+
|
|
11
|
+
export const REQUIRED_CORE = '4.13.0'
|
|
12
|
+
|
|
13
|
+
const parse = (version) => {
|
|
14
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version).trim())
|
|
15
|
+
return match ? match.slice(1, 4).map(Number) : null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True when `version` is at least `required` (major.minor.patch; a
|
|
20
|
+
* prerelease suffix is ignored). False for anything unparseable.
|
|
21
|
+
*/
|
|
22
|
+
export function satisfies(version, required = REQUIRED_CORE) {
|
|
23
|
+
const have = parse(version)
|
|
24
|
+
const need = parse(required)
|
|
25
|
+
if (!have || !need) return false
|
|
26
|
+
for (let i = 0; i < 3; i++) {
|
|
27
|
+
if (have[i] !== need[i]) return have[i] > need[i]
|
|
28
|
+
}
|
|
29
|
+
return true
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The version of `@nera-static/core` this build most likely runs on, or
|
|
34
|
+
* `null` when it cannot be found.
|
|
35
|
+
*
|
|
36
|
+
* Resolved from the site root first: that is the core `nera` loads. Only
|
|
37
|
+
* when the site has none is it resolved from the plugin's own location. The
|
|
38
|
+
* plugin's location alone is not enough: Node resolves a symlinked plugin
|
|
39
|
+
* (`npm install ../nera-plugin-images`, `npm link`) from its real path, where
|
|
40
|
+
* its own devDependency core would answer for the site's (found in the
|
|
41
|
+
* slice 7 field test, decided 2026-10-09).
|
|
42
|
+
*
|
|
43
|
+
* @param {string} [cwd]
|
|
44
|
+
*/
|
|
45
|
+
export function coreVersion(cwd = process.cwd()) {
|
|
46
|
+
const bases = [path.join(cwd, 'package.json'), import.meta.url]
|
|
47
|
+
for (const base of bases) {
|
|
48
|
+
try {
|
|
49
|
+
return createRequire(base)('@nera-static/core/package.json').version
|
|
50
|
+
} catch {
|
|
51
|
+
// Try the next base.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Throw when core is known to be older than `REQUIRED_CORE`. An unknown
|
|
59
|
+
* version (core not resolvable from here) passes: the plugin is running inside
|
|
60
|
+
* a build, so some core is calling it, and refusing on a guess would block a
|
|
61
|
+
* working setup.
|
|
62
|
+
*
|
|
63
|
+
* @param {string|null} version
|
|
64
|
+
*/
|
|
65
|
+
export function assertCoreVersion(version) {
|
|
66
|
+
if (version === null || satisfies(version)) return
|
|
67
|
+
throw new Error(
|
|
68
|
+
`plugin-images: @nera-static/core ${version} is too old; this plugin needs ` +
|
|
69
|
+
`>= ${REQUIRED_CORE} (the getAssets hook). Without it, pages would link ` +
|
|
70
|
+
'to image files that are never copied to public/. Update with ' +
|
|
71
|
+
'`npm update @nera-static/nera` (or `@nera-static/core`).'
|
|
72
|
+
)
|
|
73
|
+
}
|