@kerf-js/media 0.0.0-stage → 0.1.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/LICENSE +16 -0
- package/README.md +488 -2
- package/package.json +42 -3
- package/src/build.mjs +297 -0
- package/src/check.mjs +251 -0
- package/src/index.d.ts +31 -0
- package/src/index.mjs +213 -0
- package/src/server/ingest.mjs +118 -0
- package/src/server/serve.mjs +60 -0
- package/src/server.mjs +65 -0
- package/src/shared.mjs +55 -0
- package/src/svg.mjs +15 -0
- package/src/upload/gif.mjs +46 -0
- package/src/upload/ingest.mjs +45 -0
- package/src/upload/record.mjs +10 -0
- package/src/upload/rung.mjs +37 -0
- package/src/upload/serve.mjs +41 -0
- package/src/upload/video.mjs +55 -0
- package/src/upload.mjs +123 -0
- package/src/video/audio.mjs +52 -0
- package/src/video/common.mjs +28 -0
- package/src/video.mjs +400 -0
package/src/build.mjs
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// probe (sharp, EXIF orientation) → width ladder → per-format quality search at the largest width (SSIMULACRA2,
|
|
2
|
+
// the libjxl tool) → encode every width → dominant colour + 16 px WebP placeholder. SVG: refuse unsafe files
|
|
3
|
+
// (M012), then SVGO. With a media.encode@1 provider (@kerf-js/media-ffmpeg), src/video.mjs takes video, audio
|
|
4
|
+
// and animated GIFs; without one, a GIF stays as it is and video is P101.
|
|
5
|
+
// Cached by content hash under `cacheDir`, so dev restarts and rebuilds don't re-encode. With `encoder: 'server'` the
|
|
6
|
+
// build only stores the original: the variants are media.server@1's to encode.
|
|
7
|
+
import { execFile, spawnSync } from 'node:child_process'
|
|
8
|
+
import { createHash } from 'node:crypto'
|
|
9
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { tmpdir } from 'node:os'
|
|
11
|
+
import { basename, extname, join } from 'node:path'
|
|
12
|
+
import { promisify } from 'node:util'
|
|
13
|
+
import sharp from 'sharp'
|
|
14
|
+
import { optimize } from 'svgo'
|
|
15
|
+
import { probe } from '@kerf-js/core/media-probe'
|
|
16
|
+
import { createMediaServer } from './server.mjs'
|
|
17
|
+
import { DEFAULTS, FIXED, encoders, hex, isPhoto, MIME, withPlaceholder } from './shared.mjs'
|
|
18
|
+
import { unsafeSvg } from './svg.mjs'
|
|
19
|
+
import { AUDIO, audioFile, gif, VIDEO, video } from './video.mjs'
|
|
20
|
+
|
|
21
|
+
const run = promisify(execFile)
|
|
22
|
+
const VERSION = 2 // bump when the output for the same input and options changes
|
|
23
|
+
|
|
24
|
+
export { DEFAULTS, FIXED, MIME, encoders, hex, isPhoto } from './shared.mjs'
|
|
25
|
+
|
|
26
|
+
/** The range the quality search walks. */
|
|
27
|
+
const RANGE = { avif: [20, 90], webp: [40, 95], jpeg: [40, 95] }
|
|
28
|
+
const EXT = { avif: 'avif', webp: 'webp', jpeg: 'jpg', png: 'png', gif: 'gif', svg: 'svg' }
|
|
29
|
+
|
|
30
|
+
const scorers = new Map()
|
|
31
|
+
/** The SSIMULACRA2 command if it runs, else null (the search then uses FIXED and says `quality: 'fixed'`). */
|
|
32
|
+
export function findScorer(name) {
|
|
33
|
+
if (!name || name === 'none') return null
|
|
34
|
+
if (!scorers.has(name)) {
|
|
35
|
+
const r = spawnSync(name, [], { encoding: 'utf8' })
|
|
36
|
+
scorers.set(name, r.error ? null : name)
|
|
37
|
+
}
|
|
38
|
+
return scorers.get(name)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Lowest quality whose SSIMULACRA2 score is ≥ target, within 5 encodes (scores rise with quality). */
|
|
42
|
+
async function search({ format, base, width, scorer, target, dir }) {
|
|
43
|
+
const ref = join(dir, 'ref.png')
|
|
44
|
+
if (!existsSync(ref)) writeFileSync(ref, await base().resize({ width }).png().toBuffer())
|
|
45
|
+
const score = async (q) => {
|
|
46
|
+
const encoded = await encoders[format](base().resize({ width }), q).toBuffer()
|
|
47
|
+
const out = join(dir, `${format}-${q}.png`)
|
|
48
|
+
writeFileSync(out, await sharp(encoded).png().toBuffer())
|
|
49
|
+
const { stdout } = await run(scorer, [ref, out])
|
|
50
|
+
return parseFloat(stdout)
|
|
51
|
+
}
|
|
52
|
+
let [lo, hi] = RANGE[format]
|
|
53
|
+
for (let i = 0; i < 5 && lo < hi; i++) {
|
|
54
|
+
const mid = Math.floor((lo + hi) / 2)
|
|
55
|
+
if ((await score(mid)) >= target) hi = mid
|
|
56
|
+
else lo = mid + 1
|
|
57
|
+
}
|
|
58
|
+
return hi
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const short = (bytes) => createHash('sha256').update(bytes).digest('hex').slice(0, 8)
|
|
62
|
+
|
|
63
|
+
/** The media.build@1 provider: `build` takes one source file and gives back its asset and encoded files, cached by content. */
|
|
64
|
+
export function createMediaBuild(input = {}) {
|
|
65
|
+
const o = {
|
|
66
|
+
...DEFAULTS,
|
|
67
|
+
...input,
|
|
68
|
+
quality: { ...DEFAULTS.quality, ...input.quality },
|
|
69
|
+
video: { ...DEFAULTS.video, ...input.video },
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
/**
|
|
73
|
+
* @param {{ file: string, bytes: Uint8Array, audio?: string, photo?: boolean }} source `photo`: encode as a photo
|
|
74
|
+
* (a JPEG fallback) whatever the container says, for a lossless source of photographic pixels.
|
|
75
|
+
* @param {{ cacheDir: string, dev?: boolean, encode?: Record<string, object> }} ctx
|
|
76
|
+
*/
|
|
77
|
+
async build({ file, bytes, audio, photo }, { cacheDir, root, encode = {} }) {
|
|
78
|
+
const name = basename(file)
|
|
79
|
+
const timed = VIDEO.test(file) || AUDIO.test(file)
|
|
80
|
+
if (o.encoder === 'server' && !timed) {
|
|
81
|
+
try {
|
|
82
|
+
return {
|
|
83
|
+
asset: await createMediaServer(o).at(root, encode).ingest(bytes, { name }),
|
|
84
|
+
files: [],
|
|
85
|
+
}
|
|
86
|
+
} catch (e) {
|
|
87
|
+
if (!e.code) throw e
|
|
88
|
+
return {
|
|
89
|
+
asset: null,
|
|
90
|
+
files: [],
|
|
91
|
+
diagnostics: [{ code: e.code, severity: 'error', message: e.message }],
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const stem = basename(file, extname(file)).replace(/[^\w-]+/g, '-')
|
|
96
|
+
// The name too: the files are named after the source, so a renamed source must not get the old names back.
|
|
97
|
+
const key = createHash('sha256')
|
|
98
|
+
.update(bytes)
|
|
99
|
+
.update(`${name}\0${photo ? 'photo' : ''}`)
|
|
100
|
+
.update(JSON.stringify(o))
|
|
101
|
+
.update(String(VERSION))
|
|
102
|
+
.update(audio ? readFileSync(audio) : '')
|
|
103
|
+
.update(JSON.stringify(await versions(encode)))
|
|
104
|
+
.digest('hex')
|
|
105
|
+
.slice(0, 20)
|
|
106
|
+
const cached = join(cacheDir, `${key}.json`)
|
|
107
|
+
if (existsSync(cached)) {
|
|
108
|
+
const hit = JSON.parse(readFileSync(cached, 'utf8'))
|
|
109
|
+
return {
|
|
110
|
+
...hit,
|
|
111
|
+
files: hit.files.map((n) => ({
|
|
112
|
+
name: n,
|
|
113
|
+
bytes: new Uint8Array(readFileSync(join(cacheDir, key, n))),
|
|
114
|
+
})),
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const source = { bytes, name, stem, audio, photo }
|
|
119
|
+
const scorer = findScorer(o.quality.scorer)
|
|
120
|
+
const out = await (/\.svg$/i.test(file)
|
|
121
|
+
? vector(name, stem, bytes)
|
|
122
|
+
: VIDEO.test(file)
|
|
123
|
+
? video(source, o, encode, scorer)
|
|
124
|
+
: AUDIO.test(file)
|
|
125
|
+
? audioFile(source, o, encode)
|
|
126
|
+
: raster(source, o, encode))
|
|
127
|
+
if (out.diagnostics?.some((d) => d.severity === 'error')) return out
|
|
128
|
+
mkdirSync(join(cacheDir, key), { recursive: true })
|
|
129
|
+
for (const f of out.files) writeFileSync(join(cacheDir, key, f.name), f.bytes)
|
|
130
|
+
writeFileSync(cached, JSON.stringify({ ...out, files: out.files.map((f) => f.name) }))
|
|
131
|
+
return out
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** What the encoders are: a new ffmpeg means new bytes. */
|
|
137
|
+
async function versions(encode) {
|
|
138
|
+
const found = {}
|
|
139
|
+
for (const [key, enc] of Object.entries(encode))
|
|
140
|
+
found[key] = await enc.versions().catch(() => null)
|
|
141
|
+
return found
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** SVG: refuse what can run or fetch (M012), else SVGO's default preset (it keeps the viewBox). */
|
|
145
|
+
function vector(name, stem, bytes) {
|
|
146
|
+
const text = new TextDecoder().decode(bytes)
|
|
147
|
+
const unsafe = unsafeSvg(text)
|
|
148
|
+
if (unsafe.length)
|
|
149
|
+
return {
|
|
150
|
+
asset: null,
|
|
151
|
+
files: [],
|
|
152
|
+
diagnostics: [
|
|
153
|
+
{
|
|
154
|
+
code: 'M012',
|
|
155
|
+
severity: 'error',
|
|
156
|
+
message: `${name} has ${unsafe.join(', ')}: an image with active content or external references is not optimised or served. Sanitise the file.`,
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
}
|
|
160
|
+
const size = probe(bytes, name)
|
|
161
|
+
if (!size)
|
|
162
|
+
return {
|
|
163
|
+
asset: null,
|
|
164
|
+
files: [],
|
|
165
|
+
diagnostics: [
|
|
166
|
+
{
|
|
167
|
+
code: 'M001',
|
|
168
|
+
severity: 'error',
|
|
169
|
+
message: `${name} has no width/height or viewBox, so its size is unknown.`,
|
|
170
|
+
},
|
|
171
|
+
],
|
|
172
|
+
}
|
|
173
|
+
const svg = new TextEncoder().encode(optimize(text, { multipass: true }).data)
|
|
174
|
+
const fileName = `${stem}-${short(svg)}.svg`
|
|
175
|
+
return {
|
|
176
|
+
asset: {
|
|
177
|
+
kind: 'vector',
|
|
178
|
+
src: fileName,
|
|
179
|
+
width: size.width,
|
|
180
|
+
height: size.height,
|
|
181
|
+
type: MIME.svg,
|
|
182
|
+
sources: [],
|
|
183
|
+
name,
|
|
184
|
+
quality: 'original',
|
|
185
|
+
},
|
|
186
|
+
files: [{ name: fileName, bytes: svg }],
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function animatedGif(
|
|
191
|
+
{ bytes, name, stem, audio, meta, width, height },
|
|
192
|
+
o,
|
|
193
|
+
encode,
|
|
194
|
+
diagnostics,
|
|
195
|
+
) {
|
|
196
|
+
const converted = await gif(
|
|
197
|
+
{ bytes, name, stem, audio, meta, width, height },
|
|
198
|
+
o,
|
|
199
|
+
encode,
|
|
200
|
+
findScorer(o.quality.scorer),
|
|
201
|
+
)
|
|
202
|
+
if (converted) return converted
|
|
203
|
+
if (bytes.length > o.gifLimit)
|
|
204
|
+
diagnostics.push({
|
|
205
|
+
code: 'M004',
|
|
206
|
+
severity: 'warning',
|
|
207
|
+
message: `${name} is a ${Math.round(bytes.length / 1024)} KB animated GIF, and it ships as is${encode['video/h264'] ? ': nothing beat it by 15%' : '. Add `mediaFfmpeg()` from @kerf-js/media-ffmpeg to turn it into video'}.`,
|
|
208
|
+
})
|
|
209
|
+
const fileName = `${stem}-${short(bytes)}.gif`
|
|
210
|
+
return {
|
|
211
|
+
asset: {
|
|
212
|
+
kind: 'graphic',
|
|
213
|
+
src: fileName,
|
|
214
|
+
width,
|
|
215
|
+
height,
|
|
216
|
+
type: MIME.gif,
|
|
217
|
+
sources: [],
|
|
218
|
+
name,
|
|
219
|
+
quality: 'original',
|
|
220
|
+
},
|
|
221
|
+
files: [{ name: fileName, bytes }],
|
|
222
|
+
diagnostics,
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function raster({ bytes, name, stem, audio, photo: hinted }, o, encode) {
|
|
227
|
+
const meta = await sharp(bytes, { animated: true }).metadata()
|
|
228
|
+
const turned = (meta.orientation ?? 1) >= 5
|
|
229
|
+
const width = turned ? meta.height : meta.width
|
|
230
|
+
const height = turned ? (meta.pageHeight ?? meta.width) : (meta.pageHeight ?? meta.height)
|
|
231
|
+
const diagnostics = []
|
|
232
|
+
|
|
233
|
+
if (meta.format === 'gif' && (meta.pages ?? 1) > 1)
|
|
234
|
+
return animatedGif({ bytes, name, stem, audio, meta, width, height }, o, encode, diagnostics)
|
|
235
|
+
|
|
236
|
+
const photo = hinted === true || isPhoto(meta)
|
|
237
|
+
const fallback = photo ? 'jpeg' : 'png'
|
|
238
|
+
const formats = [...new Set(o.formats.filter((f) => f !== fallback)), fallback]
|
|
239
|
+
const largest = Math.min(width, o.widths.at(-1))
|
|
240
|
+
const ladder = [...new Set([...o.widths.filter((w) => w < largest), largest])]
|
|
241
|
+
const base = () => sharp(bytes).rotate()
|
|
242
|
+
|
|
243
|
+
const scorer = findScorer(o.quality.scorer)
|
|
244
|
+
const dir = scorer ? mkdtempSync(join(tmpdir(), 'kerf-media-')) : null
|
|
245
|
+
const qualities = {}
|
|
246
|
+
try {
|
|
247
|
+
for (const f of formats) {
|
|
248
|
+
if (f === 'png') continue
|
|
249
|
+
qualities[f] = scorer
|
|
250
|
+
? await search({ format: f, base, width: largest, scorer, target: o.quality.target, dir })
|
|
251
|
+
: FIXED[f]
|
|
252
|
+
}
|
|
253
|
+
} finally {
|
|
254
|
+
if (dir) rmSync(dir, { recursive: true, force: true })
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const files = []
|
|
258
|
+
const sources = []
|
|
259
|
+
for (const f of formats) {
|
|
260
|
+
const entries = []
|
|
261
|
+
for (const w of ladder) {
|
|
262
|
+
const encoded = await encoders[f](base().resize({ width: w }), qualities[f]).toBuffer()
|
|
263
|
+
const fileName = `${stem}-${w}-${short(encoded)}.${EXT[f]}`
|
|
264
|
+
files.push({ name: fileName, bytes: new Uint8Array(encoded) })
|
|
265
|
+
entries.push([fileName, w])
|
|
266
|
+
}
|
|
267
|
+
sources.push({ type: MIME[f], srcset: entries.map(([n, w]) => `${n} ${w}w`).join(', ') })
|
|
268
|
+
}
|
|
269
|
+
const src = sources.at(-1).srcset.split(', ').at(-1).split(' ')[0]
|
|
270
|
+
|
|
271
|
+
const asset = {
|
|
272
|
+
kind: photo ? 'photo' : 'graphic',
|
|
273
|
+
src,
|
|
274
|
+
width,
|
|
275
|
+
height,
|
|
276
|
+
type: MIME[fallback],
|
|
277
|
+
sources,
|
|
278
|
+
name,
|
|
279
|
+
quality: scorer ? 'ssimulacra2' : 'fixed',
|
|
280
|
+
qualities,
|
|
281
|
+
}
|
|
282
|
+
if (o.encoder === 'compatible') {
|
|
283
|
+
// The fallback ladder is already built: a swap costs no extra files.
|
|
284
|
+
asset.copy = { src, type: MIME[fallback] }
|
|
285
|
+
asset.swap = o.swap ?? 'intent'
|
|
286
|
+
diagnostics.push({
|
|
287
|
+
code: 'M014',
|
|
288
|
+
severity: 'info',
|
|
289
|
+
message: `${name}: \`encoder: 'compatible'\` adds 0 KB: the compatible copy is the fallback ladder.`,
|
|
290
|
+
})
|
|
291
|
+
}
|
|
292
|
+
if (o.placeholder) {
|
|
293
|
+
asset.dominant = hex((await base().stats()).dominant)
|
|
294
|
+
await withPlaceholder(asset, files, base(), stem, o)
|
|
295
|
+
}
|
|
296
|
+
return { asset, files, diagnostics }
|
|
297
|
+
}
|
package/src/check.mjs
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// M001–M013 in `kerf check`. Runs as this plugin's `check`
|
|
2
|
+
// hook over the project's .tsx/.jsx files, with the JSX view `kerf check` passes in `ctx`.
|
|
3
|
+
import { basename, dirname, extname, join, normalize } from 'node:path'
|
|
4
|
+
import { probe } from '@kerf-js/core/media-probe'
|
|
5
|
+
import { unsafeSvg } from './svg.mjs'
|
|
6
|
+
|
|
7
|
+
const IMAGE = /\.(png|jpe?g|gif|webp|avif|svg)$/i
|
|
8
|
+
const MEDIA = new Set(['img', 'video', 'Media'])
|
|
9
|
+
const ROUTE = /(^|\/)src\/routes\//
|
|
10
|
+
|
|
11
|
+
const rel = (from, spec) =>
|
|
12
|
+
normalize(join(dirname(from), spec))
|
|
13
|
+
.split('\\')
|
|
14
|
+
.join('/')
|
|
15
|
+
|
|
16
|
+
function checkSource({ el, src, size, sized, raw, report }) {
|
|
17
|
+
// M016: a string has no dimensions until it loads
|
|
18
|
+
if (!raw && (src?.kind === 'string' || /^[`'"]/.test(src?.expr ?? '')))
|
|
19
|
+
report(
|
|
20
|
+
'M016',
|
|
21
|
+
el,
|
|
22
|
+
'`<Media src>` is a string, so nothing knows its size before it loads and the page shifts.',
|
|
23
|
+
{
|
|
24
|
+
description:
|
|
25
|
+
'Import it with `?media`, or store the record `ctx.media.ingest` returns and type the field `z.media()`',
|
|
26
|
+
safe: false,
|
|
27
|
+
},
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
// M001: raw media with no box (X030 covers it inside a Boundary)
|
|
31
|
+
if (raw && !sized && !el.ancestors.includes('Boundary')) {
|
|
32
|
+
report(
|
|
33
|
+
'M001',
|
|
34
|
+
el,
|
|
35
|
+
`<${el.name}> has no \`width\`/\`height\` or \`aspect-ratio\`: it renders 0 px tall and pushes the page down when it loads.`,
|
|
36
|
+
size
|
|
37
|
+
? {
|
|
38
|
+
description: `Insert the file's size (${size.width}×${size.height})`,
|
|
39
|
+
safe: true,
|
|
40
|
+
edits: [
|
|
41
|
+
{
|
|
42
|
+
start: el.tagEnd,
|
|
43
|
+
end: el.tagEnd,
|
|
44
|
+
text: ` width={${size.width}} height={${size.height}}`,
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
}
|
|
48
|
+
: undefined,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function checkImport({ el, a, src, imp, spec, query, target, size, ctx, file, report }) {
|
|
54
|
+
// M002: through Vite's URL import or a string path to a project file
|
|
55
|
+
if (el.name === 'img' && imp && IMAGE.test(spec) && query !== 'media') {
|
|
56
|
+
report(
|
|
57
|
+
'M002',
|
|
58
|
+
el,
|
|
59
|
+
`\`${imp.source}\` is the untouched file: no resizing, no AVIF, no placeholder.`,
|
|
60
|
+
{
|
|
61
|
+
description: 'Use ?media and <Media>',
|
|
62
|
+
safe: false,
|
|
63
|
+
edits: [
|
|
64
|
+
{ start: imp.start, end: imp.end, text: `import ${imp.local} from '${spec}?media'` },
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
)
|
|
68
|
+
} else if (
|
|
69
|
+
el.name === 'img' &&
|
|
70
|
+
src?.kind === 'string' &&
|
|
71
|
+
!/^(https?:|data:|\/\/)/.test(src.value) &&
|
|
72
|
+
!src.value.startsWith('/') &&
|
|
73
|
+
IMAGE.test(src.value) &&
|
|
74
|
+
ctx.exists(rel(file, src.value))
|
|
75
|
+
) {
|
|
76
|
+
report(
|
|
77
|
+
'M002',
|
|
78
|
+
el,
|
|
79
|
+
`\`${src.value}\` is a project file referenced by string: no resizing, no AVIF, no dimensions.`,
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
// M003: oversize for its rendered width
|
|
83
|
+
const w = Number(a('width')?.value ?? a('width')?.expr)
|
|
84
|
+
if (el.name === 'img' && size && w > 0 && size.width > w * 2 * 1.25) {
|
|
85
|
+
report(
|
|
86
|
+
'M003',
|
|
87
|
+
el,
|
|
88
|
+
`${basename(target)} is ${size.width} px wide for a ${w} px slot: ${Math.round((size.width / (w * 2)) * 100) / 100}× what a 2× screen needs.`,
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function checkMotion({ el, a, src, target, bytes, gifLimit, report }) {
|
|
94
|
+
// M004 and M011: GIFs in raw <img>
|
|
95
|
+
const gif =
|
|
96
|
+
(target && /\.gif$/i.test(target)) || (src?.kind === 'string' && /\.gif$/i.test(src.value))
|
|
97
|
+
if (el.name === 'img' && gif && bytes && bytes.length > gifLimit)
|
|
98
|
+
report('M004', el, `${basename(target)} is ${Math.round(bytes.length / 1024)} KB of GIF.`)
|
|
99
|
+
if (el.name === 'img' && gif)
|
|
100
|
+
report(
|
|
101
|
+
'M011',
|
|
102
|
+
el,
|
|
103
|
+
'An animated GIF in a raw <img> loops forever with no pause control (WCAG 2.2.2).',
|
|
104
|
+
)
|
|
105
|
+
// M005, M006, M011: video
|
|
106
|
+
if (el.name === 'video') {
|
|
107
|
+
if (a('autoplay') && !a('muted'))
|
|
108
|
+
report(
|
|
109
|
+
'M005',
|
|
110
|
+
el,
|
|
111
|
+
'<video autoplay> without `muted`: browsers block it, and sound before a gesture is hostile.',
|
|
112
|
+
{
|
|
113
|
+
description: 'Add muted',
|
|
114
|
+
safe: true,
|
|
115
|
+
edits: [{ start: el.tagEnd, end: el.tagEnd, text: ' muted' }],
|
|
116
|
+
},
|
|
117
|
+
)
|
|
118
|
+
if (!a('poster'))
|
|
119
|
+
report('M006', el, '<video> without `poster` is a blank box until its first frame decodes.')
|
|
120
|
+
if (a('autoplay') && a('loop') && !a('controls'))
|
|
121
|
+
report(
|
|
122
|
+
'M011',
|
|
123
|
+
el,
|
|
124
|
+
'<video autoplay loop> without `controls` moves forever with no way to pause it (WCAG 2.2.2).',
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function checkAlt({ el, a, src, imp, target, report }) {
|
|
130
|
+
// M007: alt
|
|
131
|
+
if (el.name !== 'video') {
|
|
132
|
+
const alt = a('alt')
|
|
133
|
+
const stems = [
|
|
134
|
+
imp?.local,
|
|
135
|
+
target && basename(target),
|
|
136
|
+
target && basename(target, extname(target)),
|
|
137
|
+
src?.kind === 'string' && basename(src.value),
|
|
138
|
+
]
|
|
139
|
+
.filter(Boolean)
|
|
140
|
+
.map((s) => s.toLowerCase())
|
|
141
|
+
if (!alt) report('M007', el, `<${el.name}> has no \`alt\`.`)
|
|
142
|
+
else if (el.name === 'Media' && alt.kind === 'string' && alt.value === '' && !a('decorative'))
|
|
143
|
+
report(
|
|
144
|
+
'M007',
|
|
145
|
+
el,
|
|
146
|
+
'`alt=""` hides the image from screen readers: say so with `decorative`, or describe it.',
|
|
147
|
+
)
|
|
148
|
+
else if (alt.kind === 'string' && alt.value && stems.includes(alt.value.toLowerCase()))
|
|
149
|
+
report(
|
|
150
|
+
'M007',
|
|
151
|
+
el,
|
|
152
|
+
`\`alt="${alt.value}"\` is the file name, which tells nobody what the image shows.`,
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function checkPriority({ el, a, route, i, priorities, report }) {
|
|
158
|
+
// M008, M009, M010: priority (route files: the likely LCP image)
|
|
159
|
+
const lazy = a('loading')?.value === 'lazy'
|
|
160
|
+
const priority = !!a('priority') || a('fetchpriority')?.value === 'high'
|
|
161
|
+
if (priority && lazy)
|
|
162
|
+
report('M008', el, '`priority` media with `loading="lazy"` loads late anyway.', {
|
|
163
|
+
description: 'Remove loading="lazy"',
|
|
164
|
+
safe: true,
|
|
165
|
+
edits: [{ start: a('loading').start - 1, end: a('loading').end, text: '' }],
|
|
166
|
+
})
|
|
167
|
+
else if (route && i === 0 && lazy)
|
|
168
|
+
report(
|
|
169
|
+
'M008',
|
|
170
|
+
el,
|
|
171
|
+
`The route's first media is \`loading="lazy"\`: it is the likely LCP image, and lazy delays it.`,
|
|
172
|
+
)
|
|
173
|
+
if (route && priority && ++priorities > 2) {
|
|
174
|
+
const p = a('priority') ?? a('fetchpriority')
|
|
175
|
+
report(
|
|
176
|
+
'M009',
|
|
177
|
+
el,
|
|
178
|
+
`More than 2 \`priority\` media in this route: they compete for the first bytes.`,
|
|
179
|
+
{
|
|
180
|
+
description: 'Remove priority',
|
|
181
|
+
safe: true,
|
|
182
|
+
edits: [{ start: p.start - 1, end: p.end, text: '' }],
|
|
183
|
+
},
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
if (el.name === 'Media' && a('priority') && !a('width') && !a('sizes'))
|
|
187
|
+
report(
|
|
188
|
+
'M010',
|
|
189
|
+
el,
|
|
190
|
+
'`priority` makes this image eager, and eager images can\'t use `sizes="auto"`: the browser assumes 100vw and fetches the largest file.',
|
|
191
|
+
)
|
|
192
|
+
return priorities
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function checkSecurity({ el, src, target, bytes, svgs, ctx, report }) {
|
|
196
|
+
// M012: unsafe SVG used as an image
|
|
197
|
+
if (target && /\.svg$/i.test(target) && bytes) {
|
|
198
|
+
if (!svgs.has(target)) svgs.set(target, unsafeSvg(new TextDecoder().decode(bytes)))
|
|
199
|
+
if (svgs.get(target).length)
|
|
200
|
+
report('M012', el, `${basename(target)} has ${svgs.get(target).join(', ')}.`)
|
|
201
|
+
}
|
|
202
|
+
// M013: public/ by string
|
|
203
|
+
if (
|
|
204
|
+
src?.kind === 'string' &&
|
|
205
|
+
src.value.startsWith('/') &&
|
|
206
|
+
!src.value.startsWith('//') &&
|
|
207
|
+
ctx.exists(`public${src.value.split('?')[0]}`)
|
|
208
|
+
) {
|
|
209
|
+
report(
|
|
210
|
+
'M013',
|
|
211
|
+
el,
|
|
212
|
+
`\`${src.value}\` is served from public/: untracked, unoptimised, with no dimensions.`,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** @param {{ files: string[], read: (f: string) => string, jsx: Function, importOf: Function, exists: (f: string) => boolean, bytes: (f: string) => Uint8Array | undefined }} ctx */
|
|
218
|
+
export function checkMedia(ctx, { gifLimit = 256 * 1024 } = {}) {
|
|
219
|
+
const out = []
|
|
220
|
+
const svgs = new Map()
|
|
221
|
+
for (const file of ctx.files) {
|
|
222
|
+
if (!/\.[jt]sx$/.test(file)) continue
|
|
223
|
+
const scan = ctx.jsx(file)
|
|
224
|
+
const report = (code, el, why, fix) =>
|
|
225
|
+
out.push({ code, file, start: el.start, end: el.tagEnd, why, ...(fix && { fix }) })
|
|
226
|
+
const media = scan.elements.filter((e) => MEDIA.has(e.name))
|
|
227
|
+
const route = ROUTE.test(file)
|
|
228
|
+
let priorities = 0
|
|
229
|
+
|
|
230
|
+
for (const [i, el] of media.entries()) {
|
|
231
|
+
const a = (n) => el.attr(n)
|
|
232
|
+
const src = a('src')
|
|
233
|
+
const imp = src?.kind === 'expr' ? ctx.importOf(scan, src.expr) : undefined
|
|
234
|
+
const [spec, query = ''] = imp ? imp.source.split('?') : []
|
|
235
|
+
const target = imp && spec.startsWith('.') ? rel(file, spec) : undefined
|
|
236
|
+
const bytes = target && IMAGE.test(target) ? ctx.bytes(target) : undefined
|
|
237
|
+
const size = bytes && probe(bytes, target)
|
|
238
|
+
const style = a('style')?.value ?? a('style')?.expr ?? ''
|
|
239
|
+
const sized = (a('width') && a('height')) || /aspect-?ratio/i.test(style)
|
|
240
|
+
const raw = el.name !== 'Media'
|
|
241
|
+
|
|
242
|
+
checkSource({ el, src, size, sized, raw, report })
|
|
243
|
+
checkImport({ el, a, src, imp, spec, query, target, size, ctx, file, report })
|
|
244
|
+
checkMotion({ el, a, src, target, bytes, gifLimit, report })
|
|
245
|
+
checkAlt({ el, a, src, imp, target, report })
|
|
246
|
+
priorities = checkPriority({ el, a, route, i, priorities, report })
|
|
247
|
+
checkSecurity({ el, src, target, bytes, svgs, ctx, report })
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return out
|
|
251
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { PluginInstance } from '@kerf-js/core/plugin'
|
|
2
|
+
|
|
3
|
+
/** Options of `media()`: what to encode, how far to search, and when the encoding happens. */
|
|
4
|
+
export interface MediaOptions {
|
|
5
|
+
/** Efficient formats in front of the source-format fallback. Default `['avif']`. */
|
|
6
|
+
formats?: ('avif' | 'webp')[]
|
|
7
|
+
/** The width ladder; the largest also caps the output. Default 320, 640, 960, 1280, 1920, 2560. */
|
|
8
|
+
widths?: number[]
|
|
9
|
+
/** `target`: the SSIMULACRA2 score each format is searched to (default 80). `scorer`: the command, or 'none'. */
|
|
10
|
+
quality?: { target?: number; scorer?: string }
|
|
11
|
+
/**
|
|
12
|
+
* Dominant colour and a 16 px WebP placeholder. `true` or 'inline' (the default) inlines it as a `data:` URL; 'file'
|
|
13
|
+
* writes it as its own file, for a CSP whose `img-src` has no `data:`; `false` leaves both out.
|
|
14
|
+
*/
|
|
15
|
+
placeholder?: boolean | 'inline' | 'file'
|
|
16
|
+
/** Bytes over which a GIF is M004. Default 256 KB. */
|
|
17
|
+
gifLimit?: number
|
|
18
|
+
/** 'server': `?media` imports are encoded on first request by the media route, not at build. 'compatible': the page shows the efficient file, and a compatible copy swaps in so saving gives a file that opens anywhere. Default 'off'. */
|
|
19
|
+
encoder?: 'off' | 'compatible' | 'server'
|
|
20
|
+
/** When a compatible copy swaps in, with `encoder: 'compatible'`. Default 'intent': on right-click, long-press or drag. */
|
|
21
|
+
swap?: 'intent' | 'idle' | 'never'
|
|
22
|
+
/** Efficient codecs next to H.264 (default `['av1']`), and the ladder (default 640, 960, 1280, 1920). */
|
|
23
|
+
video?: { codecs?: ('av1' | 'vp9' | 'hevc')[]; widths?: number[] }
|
|
24
|
+
/** `toVideo: 'never'` keeps GIFs. `keepUnder`: bytes under which a GIF stays one. Default 8 KB. */
|
|
25
|
+
gif?: { toVideo?: 'auto' | 'never'; keepUnder?: number }
|
|
26
|
+
/** The media route's store (uploads, and `encoder: 'server'`). `dir` default `.kerf/media`, `maxBytes` default 20 MB. */
|
|
27
|
+
server?: { dir?: string; maxBytes?: number }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The plugin for `kerf.config.ts`: `?media` imports become optimised, responsive assets. */
|
|
31
|
+
export declare function media(options?: MediaOptions): PluginInstance<MediaOptions>
|