@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/index.mjs
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// media() for kerf.config.ts: provides media.build@1 (src/build.mjs,
|
|
2
|
+
// run by @kerf-js/core/vite for `?media` imports) and media.server@1 (src/server.mjs, the route for uploads and `encoder:
|
|
3
|
+
// 'server'`), and reports M001–M013 and M016 through its `check` hook (src/check.mjs).
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
|
|
6
|
+
import { checkMedia } from './check.mjs'
|
|
7
|
+
|
|
8
|
+
const mediaBuild = defineSlot({
|
|
9
|
+
id: 'media.build',
|
|
10
|
+
version: 1,
|
|
11
|
+
cardinality: 'one',
|
|
12
|
+
sides: ['build'],
|
|
13
|
+
})
|
|
14
|
+
const mediaServer = defineSlot({
|
|
15
|
+
id: 'media.server',
|
|
16
|
+
version: 1,
|
|
17
|
+
cardinality: 'one',
|
|
18
|
+
sides: ['server'],
|
|
19
|
+
})
|
|
20
|
+
const FORMATS = ['avif', 'webp']
|
|
21
|
+
const CODECS = ['av1', 'vp9', 'hevc']
|
|
22
|
+
|
|
23
|
+
const fail = (path, message) => {
|
|
24
|
+
throw Object.assign(new Error(message), { path })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function playbackOptions(input, out) {
|
|
28
|
+
if (input.video !== undefined) {
|
|
29
|
+
const { codecs, widths } = input.video
|
|
30
|
+
if (codecs !== undefined) {
|
|
31
|
+
if (!Array.isArray(codecs)) fail('video.codecs', 'expected an array')
|
|
32
|
+
for (const [i, c] of codecs.entries())
|
|
33
|
+
if (!CODECS.includes(c))
|
|
34
|
+
fail(`video.codecs.${i}`, `\`${c}\`: ${CODECS.join(', ')} (H.264 is always there)`)
|
|
35
|
+
}
|
|
36
|
+
if (
|
|
37
|
+
widths !== undefined &&
|
|
38
|
+
!(Array.isArray(widths) && widths.length && widths.every((w) => Number.isInteger(w) && w > 0))
|
|
39
|
+
)
|
|
40
|
+
fail('video.widths', 'expected positive integers')
|
|
41
|
+
out.video = { ...input.video, ...(widths && { widths: [...widths].sort((a, b) => a - b) }) }
|
|
42
|
+
}
|
|
43
|
+
if (input.gif !== undefined) {
|
|
44
|
+
const { toVideo, keepUnder } = input.gif
|
|
45
|
+
if (toVideo !== undefined && !['auto', 'never'].includes(toVideo))
|
|
46
|
+
fail('gif.toVideo', "'auto' or 'never'")
|
|
47
|
+
if (keepUnder !== undefined && !(Number.isInteger(keepUnder) && keepUnder >= 0))
|
|
48
|
+
fail('gif.keepUnder', 'a number of bytes')
|
|
49
|
+
out.gif = input.gif
|
|
50
|
+
}
|
|
51
|
+
if (input.server !== undefined) {
|
|
52
|
+
const { dir, maxBytes } = input.server
|
|
53
|
+
if (dir !== undefined && typeof dir !== 'string')
|
|
54
|
+
fail('server.dir', 'a directory, relative to the app')
|
|
55
|
+
if (maxBytes !== undefined && !(Number.isInteger(maxBytes) && maxBytes > 0))
|
|
56
|
+
fail('server.maxBytes', 'a positive number of bytes')
|
|
57
|
+
out.server = input.server
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function options(input) {
|
|
62
|
+
for (const key of Object.keys(input))
|
|
63
|
+
if (
|
|
64
|
+
![
|
|
65
|
+
'formats',
|
|
66
|
+
'widths',
|
|
67
|
+
'quality',
|
|
68
|
+
'placeholder',
|
|
69
|
+
'gifLimit',
|
|
70
|
+
'encoder',
|
|
71
|
+
'swap',
|
|
72
|
+
'video',
|
|
73
|
+
'gif',
|
|
74
|
+
'server',
|
|
75
|
+
].includes(key)
|
|
76
|
+
)
|
|
77
|
+
fail(key, 'unknown option')
|
|
78
|
+
const out = {}
|
|
79
|
+
if (input.encoder !== undefined) {
|
|
80
|
+
if (!['off', 'compatible', 'server'].includes(input.encoder))
|
|
81
|
+
fail('encoder', `\`${input.encoder}\`: 'off', 'compatible' or 'server'`)
|
|
82
|
+
out.encoder = input.encoder
|
|
83
|
+
}
|
|
84
|
+
if (input.swap !== undefined) {
|
|
85
|
+
if (!['intent', 'idle', 'never'].includes(input.swap))
|
|
86
|
+
fail('swap', `\`${input.swap}\`: 'intent', 'idle' or 'never'`)
|
|
87
|
+
if (input.encoder !== 'compatible')
|
|
88
|
+
fail('swap', "only means something with `encoder: 'compatible'`")
|
|
89
|
+
out.swap = input.swap
|
|
90
|
+
}
|
|
91
|
+
playbackOptions(input, out)
|
|
92
|
+
if (input.formats !== undefined) {
|
|
93
|
+
if (!Array.isArray(input.formats)) fail('formats', 'expected an array')
|
|
94
|
+
for (const [i, f] of input.formats.entries())
|
|
95
|
+
if (!FORMATS.includes(f))
|
|
96
|
+
fail(
|
|
97
|
+
`formats.${i}`,
|
|
98
|
+
`\`${f}\`: the efficient formats are ${FORMATS.join(', ')} (the fallback follows the source)`,
|
|
99
|
+
)
|
|
100
|
+
out.formats = input.formats
|
|
101
|
+
}
|
|
102
|
+
if (input.widths !== undefined) {
|
|
103
|
+
if (
|
|
104
|
+
!Array.isArray(input.widths) ||
|
|
105
|
+
!input.widths.length ||
|
|
106
|
+
!input.widths.every((w) => Number.isInteger(w) && w > 0)
|
|
107
|
+
)
|
|
108
|
+
fail('widths', 'expected positive integers')
|
|
109
|
+
out.widths = [...input.widths].sort((a, b) => a - b)
|
|
110
|
+
}
|
|
111
|
+
if (input.quality !== undefined) {
|
|
112
|
+
const { target = 80, scorer = 'ssimulacra2' } = input.quality
|
|
113
|
+
if (!(target > 0 && target <= 100))
|
|
114
|
+
fail(
|
|
115
|
+
'quality.target',
|
|
116
|
+
'an SSIMULACRA2 score, 1–100 (80 ≈ visually lossless at normal viewing)',
|
|
117
|
+
)
|
|
118
|
+
if (typeof scorer !== 'string')
|
|
119
|
+
fail('quality.scorer', "the SSIMULACRA2 command, or 'none' for fixed qualities")
|
|
120
|
+
out.quality = { target, scorer }
|
|
121
|
+
}
|
|
122
|
+
if (input.placeholder !== undefined) {
|
|
123
|
+
if (![true, false, 'inline', 'file'].includes(input.placeholder))
|
|
124
|
+
fail(
|
|
125
|
+
'placeholder',
|
|
126
|
+
"true or 'inline' (a data: URL), 'file' (its own file, for a strict CSP), or false",
|
|
127
|
+
)
|
|
128
|
+
out.placeholder = input.placeholder === 'inline' ? true : input.placeholder
|
|
129
|
+
}
|
|
130
|
+
if (input.gifLimit !== undefined) out.gifLimit = input.gifLimit
|
|
131
|
+
return out
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const CODES = [
|
|
135
|
+
['M001', 'Raw <img>/<video> without width/height or aspect-ratio'],
|
|
136
|
+
['M002', 'Image through ?url or a string path'],
|
|
137
|
+
['M003', 'Raw <img> file far wider than its slot'],
|
|
138
|
+
['M004', 'GIF over 256 KB rendered raw'],
|
|
139
|
+
['M005', '<video autoplay> without muted'],
|
|
140
|
+
['M006', '<video> without poster'],
|
|
141
|
+
['M007', 'Missing or meaningless alt'],
|
|
142
|
+
['M008', 'Likely LCP image loaded lazily'],
|
|
143
|
+
['M009', 'More than 2 priority media in a route'],
|
|
144
|
+
['M010', 'priority <Media> with no width or sizes'],
|
|
145
|
+
['M011', 'Endless motion with no pause control'],
|
|
146
|
+
['M012', 'Unsafe SVG used as an image'],
|
|
147
|
+
['M013', 'public/ file referenced by string'],
|
|
148
|
+
['M014', "What `encoder: 'compatible'` adds to the build"],
|
|
149
|
+
['M015', 'An HDR or over-8-bit source that comes out 8-bit SDR'],
|
|
150
|
+
['M016', '<Media src> given a string: no dimensions before render'],
|
|
151
|
+
['M017', 'Media requested with no media.server provider'],
|
|
152
|
+
['M018', 'An upload refused: not an image, or over the size limit'],
|
|
153
|
+
['M019', 'ffmpeg missing, not the pinned binary, or without an encoder'],
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
export const media = definePlugin({
|
|
157
|
+
name: '@kerf-js/media',
|
|
158
|
+
version: '0.1.0',
|
|
159
|
+
kerf: '*',
|
|
160
|
+
namespace: 'M',
|
|
161
|
+
options,
|
|
162
|
+
permissions: {
|
|
163
|
+
fs: {
|
|
164
|
+
read: [
|
|
165
|
+
'**/*.{png,jpg,jpeg,gif,webp,avif,svg,mp4,m4v,mov,webm,mkv,ogv,mp3,wav,flac,ogg,oga,opus,m4a,aac}',
|
|
166
|
+
],
|
|
167
|
+
},
|
|
168
|
+
env: ['KERF_MEDIA_DIR'],
|
|
169
|
+
spawn: ['ssimulacra2'],
|
|
170
|
+
native: true,
|
|
171
|
+
},
|
|
172
|
+
contribute: (o) => ({
|
|
173
|
+
provides: [
|
|
174
|
+
provide(mediaBuild, {
|
|
175
|
+
sides: {
|
|
176
|
+
build: {
|
|
177
|
+
module: fileURLToPath(new URL('./build.mjs', import.meta.url)),
|
|
178
|
+
export: 'createMediaBuild',
|
|
179
|
+
options: o,
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
}),
|
|
183
|
+
provide(mediaServer, {
|
|
184
|
+
sides: {
|
|
185
|
+
server: {
|
|
186
|
+
module: '@kerf-js/media/server',
|
|
187
|
+
export: 'createMediaServer',
|
|
188
|
+
options: o,
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
}),
|
|
192
|
+
],
|
|
193
|
+
check: { include: ['**/*.{tsx,jsx}'], run: (ctx) => checkMedia(ctx, { gifLimit: o.gifLimit }) },
|
|
194
|
+
diagnostics: CODES.map(([code, catches]) => ({ code, catches, fix: `kerf docs ${code}` })),
|
|
195
|
+
agents: {
|
|
196
|
+
title: 'Media (@kerf-js/media)',
|
|
197
|
+
text: [
|
|
198
|
+
'- Import images with `?media` and render `<Media src={x} alt="…" />` from `@kerf-js/core/media`. Never hand-write srcset, sizes, width/height or blur placeholders.',
|
|
199
|
+
'- Mark the one hero image `priority` and give it `width` (`"1/2"`, `"480px"`) so its `sizes` is right (M010). Nothing else gets `priority` (M009).',
|
|
200
|
+
'- `alt` is required; use `alt="" decorative` for purely visual media (M007).',
|
|
201
|
+
'- Never reference files in public/ by string (M013) or render `?url` imports in `<img>` (M002).',
|
|
202
|
+
'- Uploads: `await ctx.media.ingest(file)` in a mutation returns a record. Store it, type the field `z.media()` (from `@kerf-js/start/media`), and pass it to `<Media src>` (M016).',
|
|
203
|
+
].join('\n'),
|
|
204
|
+
},
|
|
205
|
+
catalog: [
|
|
206
|
+
{
|
|
207
|
+
name: 'Media',
|
|
208
|
+
import: '@kerf-js/core/media',
|
|
209
|
+
summary: '<Media src={x} alt>: dimensions, AVIF + fallback, srcset/sizes, placeholder',
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
}),
|
|
213
|
+
})
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { mkdirSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import sharp from 'sharp'
|
|
5
|
+
import { optimize } from 'svgo'
|
|
6
|
+
import { probe } from '@kerf-js/core/media-probe'
|
|
7
|
+
import { hex, isPhoto, MIME } from '../shared.mjs'
|
|
8
|
+
import { unsafeSvg } from '../svg.mjs'
|
|
9
|
+
import { sniff } from '../upload.mjs'
|
|
10
|
+
|
|
11
|
+
export function imageIngest({ limit, metaOf, dir, encode, timed, url, store, refuse, o }) {
|
|
12
|
+
return async function ingest(bytes, { name = 'upload' } = {}) {
|
|
13
|
+
if (bytes.length > limit)
|
|
14
|
+
refuse(
|
|
15
|
+
'M018',
|
|
16
|
+
`${name} is ${Math.round(bytes.length / 1048576)} MB, over the ${Math.round(limit / 1048576)} MB limit.`,
|
|
17
|
+
)
|
|
18
|
+
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 32)
|
|
19
|
+
const known = metaOf(hash)
|
|
20
|
+
if (known) return { ...known.asset, name }
|
|
21
|
+
const kind = sniff(bytes)
|
|
22
|
+
if (kind) {
|
|
23
|
+
if (!encode['video/h264'])
|
|
24
|
+
refuse(
|
|
25
|
+
'M018',
|
|
26
|
+
`${name} is ${kind}, and nothing here encodes it: add \`mediaFfmpeg()\` from @kerf-js/media-ffmpeg to \`plugins\`, with ffmpeg on the server.`,
|
|
27
|
+
)
|
|
28
|
+
mkdirSync(join(dir, hash), { recursive: true })
|
|
29
|
+
return timed.ingest(hash, bytes, name, kind)
|
|
30
|
+
}
|
|
31
|
+
const size = probe(bytes, name)
|
|
32
|
+
if (size?.type === 'image/svg+xml')
|
|
33
|
+
return storeSvg(hash, bytes, name, size, { refuse, url, store })
|
|
34
|
+
let meta
|
|
35
|
+
try {
|
|
36
|
+
meta = await sharp(bytes, { animated: true }).metadata()
|
|
37
|
+
} catch {
|
|
38
|
+
refuse('M018', `${name} isn't an image kerf can read (PNG, JPEG, GIF, WebP, AVIF, SVG).`)
|
|
39
|
+
}
|
|
40
|
+
const turned = (meta.orientation ?? 1) >= 5
|
|
41
|
+
const tall = meta.pageHeight ?? meta.height
|
|
42
|
+
const width = turned ? tall : meta.width
|
|
43
|
+
const height = turned ? meta.width : tall
|
|
44
|
+
if (meta.format === 'gif' && (meta.pages ?? 1) > 1) {
|
|
45
|
+
// Animated: video when that's a saving, else as it is.
|
|
46
|
+
mkdirSync(join(dir, hash), { recursive: true })
|
|
47
|
+
const video = await timed.gif(hash, bytes, name, meta)
|
|
48
|
+
if (video) return video
|
|
49
|
+
return store(
|
|
50
|
+
hash,
|
|
51
|
+
bytes,
|
|
52
|
+
{
|
|
53
|
+
kind: 'graphic',
|
|
54
|
+
src: url(hash, width),
|
|
55
|
+
width,
|
|
56
|
+
height,
|
|
57
|
+
type: MIME.gif,
|
|
58
|
+
sources: [],
|
|
59
|
+
name,
|
|
60
|
+
quality: 'original',
|
|
61
|
+
},
|
|
62
|
+
{ ladder: [width], type: MIME.gif },
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
return storeRaster({ meta, width, height, o, url, hash, name, bytes, store })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function storeSvg(hash, bytes, name, size, { refuse, url, store }) {
|
|
70
|
+
const text = new TextDecoder().decode(bytes)
|
|
71
|
+
const unsafe = unsafeSvg(text)
|
|
72
|
+
if (unsafe.length)
|
|
73
|
+
refuse(
|
|
74
|
+
'M012',
|
|
75
|
+
`${name} has ${unsafe.join(', ')}: an image with active content or external references is not stored.`,
|
|
76
|
+
)
|
|
77
|
+
const svg = new TextEncoder().encode(optimize(text, { multipass: true }).data)
|
|
78
|
+
return store(
|
|
79
|
+
hash,
|
|
80
|
+
svg,
|
|
81
|
+
{
|
|
82
|
+
kind: 'vector',
|
|
83
|
+
src: url(hash, size.width),
|
|
84
|
+
width: size.width,
|
|
85
|
+
height: size.height,
|
|
86
|
+
type: MIME.svg,
|
|
87
|
+
sources: [],
|
|
88
|
+
name,
|
|
89
|
+
quality: 'original',
|
|
90
|
+
},
|
|
91
|
+
{ ladder: [size.width], type: MIME.svg },
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function storeRaster({ meta, width, height, o, url, hash, name, bytes, store }) {
|
|
96
|
+
const photo = isPhoto(meta)
|
|
97
|
+
const fallback = photo ? 'jpeg' : 'png'
|
|
98
|
+
const largest = Math.min(width, o.widths.at(-1))
|
|
99
|
+
const ladder = [...new Set([...o.widths.filter((w) => w < largest), largest])]
|
|
100
|
+
const asset = {
|
|
101
|
+
kind: photo ? 'photo' : 'graphic',
|
|
102
|
+
src: url(hash, largest),
|
|
103
|
+
width,
|
|
104
|
+
height,
|
|
105
|
+
type: MIME[fallback],
|
|
106
|
+
sources: [
|
|
107
|
+
{ type: MIME[fallback], srcset: ladder.map((w) => `${url(hash, w)} ${w}w`).join(', ') },
|
|
108
|
+
],
|
|
109
|
+
name,
|
|
110
|
+
quality: 'fixed',
|
|
111
|
+
}
|
|
112
|
+
if (o.placeholder) {
|
|
113
|
+
const base = () => sharp(bytes).rotate()
|
|
114
|
+
asset.dominant = hex((await base().stats()).dominant)
|
|
115
|
+
asset.placeholder = `data:image/webp;base64,${(await base().resize(16, 16, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()).toString('base64')}`
|
|
116
|
+
}
|
|
117
|
+
return store(hash, bytes, asset, { ladder, fallback })
|
|
118
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import sharp from 'sharp'
|
|
4
|
+
import { FIXED, encoders, MIME } from '../shared.mjs'
|
|
5
|
+
|
|
6
|
+
const FORMATS_TIMED = new Set(['mp4', 'webm', 'm4a', 'gif', 'webp'])
|
|
7
|
+
const EXT = { avif: 'avif', webp: 'webp', jpeg: 'jpg', png: 'png' }
|
|
8
|
+
const FORMAT = { avif: 'avif', webp: 'webp', jpg: 'jpeg', png: 'png' }
|
|
9
|
+
|
|
10
|
+
export function imageServe({ dir, flight, metaOf, timed, o, negotiate }) {
|
|
11
|
+
/** One variant, encoded once: concurrent requests share the encode, and the file lands whole or not at all. */
|
|
12
|
+
function variant(hash, width, format) {
|
|
13
|
+
const file = join(dir, hash, `${width}.${EXT[format]}`)
|
|
14
|
+
if (existsSync(file)) return readFileSync(file)
|
|
15
|
+
const key = `${hash}/${width}.${format}`
|
|
16
|
+
if (!flight.has(key)) {
|
|
17
|
+
const work = (async () => {
|
|
18
|
+
const img = sharp(readFileSync(join(dir, hash, 'source')))
|
|
19
|
+
.rotate()
|
|
20
|
+
.resize({ width })
|
|
21
|
+
const bytes = await encoders[format](img, FIXED[format]).toBuffer()
|
|
22
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
23
|
+
writeFileSync(tmp, bytes)
|
|
24
|
+
renameSync(tmp, file)
|
|
25
|
+
return bytes
|
|
26
|
+
})().finally(() => flight.delete(key))
|
|
27
|
+
flight.set(key, work)
|
|
28
|
+
}
|
|
29
|
+
return flight.get(key)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function serve({ hash, width, format, accept }) {
|
|
33
|
+
const meta = /^[0-9a-f]{32}$/.test(hash) ? metaOf(hash) : null
|
|
34
|
+
if (meta?.timed)
|
|
35
|
+
return FORMATS_TIMED.has(format) ? timed.serve(hash, meta, width, format) : null
|
|
36
|
+
if (!meta?.ladder.includes(width)) return null
|
|
37
|
+
const negotiated = format === 'auto'
|
|
38
|
+
if (meta.type)
|
|
39
|
+
return negotiated
|
|
40
|
+
? {
|
|
41
|
+
bytes: readFileSync(join(dir, hash, 'source')),
|
|
42
|
+
type: meta.type,
|
|
43
|
+
width,
|
|
44
|
+
format: 'source',
|
|
45
|
+
negotiated: false,
|
|
46
|
+
}
|
|
47
|
+
: null
|
|
48
|
+
const fmt = negotiated ? negotiate(accept, o.formats, meta.fallback) : FORMAT[format]
|
|
49
|
+
if (!fmt || !(fmt === meta.fallback || o.formats.includes(fmt))) return null
|
|
50
|
+
return {
|
|
51
|
+
bytes: new Uint8Array(await variant(hash, width, fmt)),
|
|
52
|
+
type: MIME[fmt],
|
|
53
|
+
width,
|
|
54
|
+
format: fmt,
|
|
55
|
+
negotiated,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return serve
|
|
60
|
+
}
|
package/src/server.mjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// `ingest` stores an original under its hash and returns a `z.media()` record; `serve` answers `/_kerf/m/<hash>/<w>.<fmt>`,
|
|
2
|
+
// encoding each variant once and keeping it next to the original. `auto` negotiates on `Accept`. Only widths on the
|
|
3
|
+
// ladder and formats in the config are served, so a URL can't ask for unbounded work. Video, audio and animated GIFs go
|
|
4
|
+
// through src/upload.mjs when media.encode@1 is bound.
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { join, resolve } from 'node:path'
|
|
7
|
+
import { DEFAULTS, MIME } from './shared.mjs'
|
|
8
|
+
import { uploads } from './upload.mjs'
|
|
9
|
+
import { imageIngest } from './server/ingest.mjs'
|
|
10
|
+
import { imageServe } from './server/serve.mjs'
|
|
11
|
+
|
|
12
|
+
const ROUTE = '/_kerf/m'
|
|
13
|
+
const MAX_BYTES = 20 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
const refuse = (code, message) => {
|
|
16
|
+
throw Object.assign(new Error(message), { code })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The first of `formats` the client names with a q above 0, else `fallback`. `*` promises nothing: only names count. */
|
|
20
|
+
export function negotiate(accept, formats, fallback) {
|
|
21
|
+
const q = new Map()
|
|
22
|
+
for (const part of accept.split(',')) {
|
|
23
|
+
const [type, ...params] = part.trim().toLowerCase().split(';')
|
|
24
|
+
const v = params.map((p) => /^\s*q=([\d.]+)/.exec(p)?.[1]).find(Boolean)
|
|
25
|
+
q.set(type.trim(), v === undefined ? 1 : Number(v))
|
|
26
|
+
}
|
|
27
|
+
return formats.find((f) => q.get(MIME[f]) > 0) ?? fallback
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The media.server@1 provider: `at(root, encode)` is the store for one app, its `ingest` and its `serve`. */
|
|
31
|
+
export function createMediaServer(input = {}) {
|
|
32
|
+
const o = { ...DEFAULTS, ...input, video: { ...DEFAULTS.video, ...input.video } }
|
|
33
|
+
return { at: (root, encode = {}) => storage(o, root, encode) }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function storage(o, root, encode) {
|
|
37
|
+
const dir = process.env.KERF_MEDIA_DIR
|
|
38
|
+
? resolve(process.env.KERF_MEDIA_DIR)
|
|
39
|
+
: resolve(root ?? process.cwd(), o.server?.dir ?? '.kerf/media')
|
|
40
|
+
const limit = o.server?.maxBytes ?? MAX_BYTES
|
|
41
|
+
const flight = new Map()
|
|
42
|
+
const url = (hash, width, format = 'auto') => `${ROUTE}/${hash}/${width}.${format}`
|
|
43
|
+
const metaOf = (hash) => {
|
|
44
|
+
const file = join(dir, hash, 'meta.json')
|
|
45
|
+
return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The record and what `serve` needs; written last, so a meta.json means the original is whole. */
|
|
49
|
+
function store(hash, bytes, asset, meta) {
|
|
50
|
+
mkdirSync(join(dir, hash), { recursive: true })
|
|
51
|
+
writeFileSync(join(dir, hash, 'source'), bytes)
|
|
52
|
+
const tmp = join(dir, hash, `meta.${process.pid}.tmp`)
|
|
53
|
+
writeFileSync(tmp, JSON.stringify({ ...meta, asset }))
|
|
54
|
+
renameSync(tmp, join(dir, hash, 'meta.json'))
|
|
55
|
+
return asset
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const timed = uploads({ o, dir, encode, url, store, refuse })
|
|
59
|
+
|
|
60
|
+
const ingest = imageIngest({ limit, metaOf, dir, encode, timed, url, store, refuse, o })
|
|
61
|
+
|
|
62
|
+
const serve = imageServe({ dir, flight, metaOf, timed, o, negotiate })
|
|
63
|
+
|
|
64
|
+
return { ingest, serve, settled: timed.settled }
|
|
65
|
+
}
|
package/src/shared.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// What build.mjs and server.mjs both need: the defaults, the encoder calls and the MIME table. It lives apart so the build
|
|
2
|
+
// can call the server for `encoder: 'server'` without the two importing each other.
|
|
3
|
+
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
|
|
6
|
+
/** Every option's default: the width ladder, the quality search, the placeholder, the GIF limit, the video ladder. */
|
|
7
|
+
export const DEFAULTS = {
|
|
8
|
+
formats: ['avif'],
|
|
9
|
+
widths: [320, 640, 960, 1280, 1920, 2560],
|
|
10
|
+
quality: { target: 80, scorer: 'ssimulacra2' },
|
|
11
|
+
placeholder: true,
|
|
12
|
+
gifLimit: 256 * 1024,
|
|
13
|
+
video: { codecs: ['av1'], widths: [640, 960, 1280, 1920] },
|
|
14
|
+
}
|
|
15
|
+
/** Encoder settings without a scorer. */
|
|
16
|
+
export const FIXED = { avif: 50, webp: 75, jpeg: 78 }
|
|
17
|
+
/** Content types of the formats this package writes. */
|
|
18
|
+
export const MIME = {
|
|
19
|
+
avif: 'image/avif',
|
|
20
|
+
webp: 'image/webp',
|
|
21
|
+
jpeg: 'image/jpeg',
|
|
22
|
+
png: 'image/png',
|
|
23
|
+
gif: 'image/gif',
|
|
24
|
+
svg: 'image/svg+xml',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One sharp call per format: quality in, a configured pipeline out. PNG takes no quality. */
|
|
28
|
+
export const encoders = {
|
|
29
|
+
avif: (img, q) => img.avif({ quality: q, effort: 4, chromaSubsampling: '4:2:0' }),
|
|
30
|
+
webp: (img, q) => img.webp({ quality: q, effort: 5 }),
|
|
31
|
+
jpeg: (img, q) => img.jpeg({ quality: q, mozjpeg: true }),
|
|
32
|
+
png: (img) => img.png({ compressionLevel: 9, effort: 8 }),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A sharp `dominant` colour as `#rrggbb`. */
|
|
36
|
+
export const hex = ({ r, g, b }) =>
|
|
37
|
+
`#${[r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('')}`
|
|
38
|
+
/** Lossy sources get a lossy fallback; a WebP with alpha is a graphic. */
|
|
39
|
+
export const isPhoto = (meta) =>
|
|
40
|
+
['jpeg', 'jpg', 'avif', 'heif', 'tiff', 'webp'].includes(meta.format) &&
|
|
41
|
+
!(meta.format === 'webp' && meta.hasAlpha)
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Adds the 16 px placeholder from `img` (a sharp pipeline) to `asset`. Inline it's a `data:` URL; with
|
|
45
|
+
* `placeholder: 'file'` it's a file of its own pushed to `files`, for a CSP whose `img-src` has no `data:`.
|
|
46
|
+
*/
|
|
47
|
+
export async function withPlaceholder(asset, files, img, stem, o) {
|
|
48
|
+
const tiny = await img.resize(16, 16, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
|
|
49
|
+
if (o.placeholder !== 'file') {
|
|
50
|
+
asset.placeholder = `data:image/webp;base64,${tiny.toString('base64')}`
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
asset.placeholder = `${stem}-placeholder-${createHash('sha256').update(tiny).digest('hex').slice(0, 8)}.webp`
|
|
54
|
+
files.push({ name: asset.placeholder, bytes: new Uint8Array(tiny) })
|
|
55
|
+
}
|
package/src/svg.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// M012 (research 15 §7.5): SVG content that can run code or fetch something, which an image must not carry.
|
|
2
|
+
|
|
3
|
+
const RULES = [
|
|
4
|
+
[/<script[\s>/]/i, '<script>'],
|
|
5
|
+
[/<foreignObject[\s>/]/i, '<foreignObject>'],
|
|
6
|
+
[/\son[a-z]+\s*=/i, 'an on* event handler'],
|
|
7
|
+
[/\s(?:xlink:)?href\s*=\s*["'](?!#|data:)[^"']/i, 'an external href'],
|
|
8
|
+
[/url\(\s*['"]?(?!#|data:)[a-z]+:/i, 'an external url()'],
|
|
9
|
+
[/@import\b/i, 'a CSS @import'],
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
/** What makes this SVG unsafe as an image, or [] when nothing does. */
|
|
13
|
+
export function unsafeSvg(text) {
|
|
14
|
+
return RULES.filter(([re]) => re.test(text)).map(([, what]) => what)
|
|
15
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs'
|
|
2
|
+
import sharp from 'sharp'
|
|
3
|
+
|
|
4
|
+
export function createGif({
|
|
5
|
+
encode,
|
|
6
|
+
o,
|
|
7
|
+
sourceOf,
|
|
8
|
+
video,
|
|
9
|
+
rung,
|
|
10
|
+
hasCopy,
|
|
11
|
+
url,
|
|
12
|
+
enqueue,
|
|
13
|
+
store,
|
|
14
|
+
COMPATIBLE,
|
|
15
|
+
SMALLER,
|
|
16
|
+
}) {
|
|
17
|
+
/** An animated GIF: null when it should stay one (the rules in src/video.mjs, on the top H.264 rung). */
|
|
18
|
+
return async function gif(hash, bytes, name, meta) {
|
|
19
|
+
if (
|
|
20
|
+
!encode[COMPATIBLE] ||
|
|
21
|
+
bytes.length < (o.gif?.keepUnder ?? 8192) ||
|
|
22
|
+
(meta.pages ?? 1) < 4 ||
|
|
23
|
+
o.gif?.toVideo === 'never'
|
|
24
|
+
)
|
|
25
|
+
return null
|
|
26
|
+
if (!(await sharp(bytes, { animated: true }).stats()).isOpaque) return null
|
|
27
|
+
writeFileSync(sourceOf(hash), bytes)
|
|
28
|
+
const info = await encode[COMPATIBLE].info(sourceOf(hash))
|
|
29
|
+
const width = meta.width
|
|
30
|
+
const height = meta.pageHeight ?? meta.height
|
|
31
|
+
const delays = meta.delay ?? []
|
|
32
|
+
const duration = delays.length
|
|
33
|
+
? delays.reduce((a, b) => a + (b < 20 ? 100 : b), 0) / 1000
|
|
34
|
+
: info.duration
|
|
35
|
+
const full = { ...info, duration, video: { ...info.video, width, height } }
|
|
36
|
+
const { asset, meta: plan } = await video(hash, bytes, name, full)
|
|
37
|
+
const top = plan.rungs.at(-1)[0]
|
|
38
|
+
if ((await rung(hash, plan, top, 'mp4')).length > bytes.length * SMALLER) return null
|
|
39
|
+
Object.assign(asset, { animated: true, audio: false, loop: meta.loop ?? 0 })
|
|
40
|
+
if (hasCopy())
|
|
41
|
+
asset.copy = { src: url(hash, width, 'gif'), type: 'image/gif', bytes: bytes.length }
|
|
42
|
+
plan.gif = width
|
|
43
|
+
enqueue(hash, plan)
|
|
44
|
+
return store(hash, bytes, asset, plan)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs'
|
|
2
|
+
|
|
3
|
+
export function createIngest({
|
|
4
|
+
encode,
|
|
5
|
+
sourceOf,
|
|
6
|
+
refuse,
|
|
7
|
+
record,
|
|
8
|
+
url,
|
|
9
|
+
enqueue,
|
|
10
|
+
store,
|
|
11
|
+
video,
|
|
12
|
+
COMPATIBLE,
|
|
13
|
+
}) {
|
|
14
|
+
return async function ingest(hash, bytes, name, kind) {
|
|
15
|
+
const enc = encode[COMPATIBLE]
|
|
16
|
+
writeFileSync(sourceOf(hash), bytes)
|
|
17
|
+
const info = await enc.info(sourceOf(hash)).catch(() => null)
|
|
18
|
+
if (kind === 'audio') {
|
|
19
|
+
if (!info?.audio) refuse('M018', `${name} has no audio track kerf can read.`)
|
|
20
|
+
const rungs = [...(encode['audio/opus'] ? [[0, 'webm']] : []), [0, 'm4a']]
|
|
21
|
+
const asset = {
|
|
22
|
+
kind: 'audio',
|
|
23
|
+
src: url(hash, 0, 'm4a'),
|
|
24
|
+
width: 0,
|
|
25
|
+
height: 0,
|
|
26
|
+
type: 'audio/mp4',
|
|
27
|
+
sources: record(hash, rungs, {
|
|
28
|
+
webm: 'audio/webm; codecs="opus"',
|
|
29
|
+
m4a: 'audio/mp4; codecs="mp4a.40.2"',
|
|
30
|
+
}),
|
|
31
|
+
name,
|
|
32
|
+
quality: 'fixed',
|
|
33
|
+
duration: info.duration,
|
|
34
|
+
audio: true,
|
|
35
|
+
}
|
|
36
|
+
const meta = { kind, timed: true, rungs }
|
|
37
|
+
enqueue(hash, meta)
|
|
38
|
+
return store(hash, bytes, asset, meta)
|
|
39
|
+
}
|
|
40
|
+
if (!info?.video) refuse('M018', `${name} has no video track kerf can read.`)
|
|
41
|
+
const { asset, meta } = await video(hash, bytes, name, info)
|
|
42
|
+
enqueue(hash, meta)
|
|
43
|
+
return store(hash, bytes, asset, meta)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export function createRecord(url) {
|
|
2
|
+
return (hash, rungs, types) =>
|
|
3
|
+
[...new Set(rungs.map((r) => r[1]))].map((format) => ({
|
|
4
|
+
type: types[format],
|
|
5
|
+
srcset: rungs
|
|
6
|
+
.filter((r) => r[1] === format)
|
|
7
|
+
.map(([w]) => `${url(hash, w, format)} ${w || 1}w`)
|
|
8
|
+
.join(', '),
|
|
9
|
+
}))
|
|
10
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export function createRung(dir, encode, sourceOf, flight, COMPATIBLE) {
|
|
5
|
+
/** One rung, encoded once: the queue and a waiting request share the work, and the file lands whole or not at all. */
|
|
6
|
+
return function rung(hash, meta, width, format) {
|
|
7
|
+
const file = join(dir, hash, `${width}.${format}`)
|
|
8
|
+
if (existsSync(file)) return readFileSync(file)
|
|
9
|
+
const key = `${hash}/${width}.${format}`
|
|
10
|
+
if (!flight.has(key)) {
|
|
11
|
+
const work = (async () => {
|
|
12
|
+
const audio = meta.kind === 'audio'
|
|
13
|
+
const enc =
|
|
14
|
+
encode[
|
|
15
|
+
audio
|
|
16
|
+
? format === 'webm'
|
|
17
|
+
? 'audio/opus'
|
|
18
|
+
: 'audio/aac'
|
|
19
|
+
: format === 'webm'
|
|
20
|
+
? meta.webm
|
|
21
|
+
: COMPATIBLE
|
|
22
|
+
]
|
|
23
|
+
const copy = meta.keepTop === width && format === 'mp4'
|
|
24
|
+
const bytes = await enc.encode(
|
|
25
|
+
sourceOf(hash),
|
|
26
|
+
audio ? {} : copy ? { copy } : { width, knob: enc.knob.fixed },
|
|
27
|
+
)
|
|
28
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
29
|
+
writeFileSync(tmp, bytes)
|
|
30
|
+
renameSync(tmp, file)
|
|
31
|
+
return bytes
|
|
32
|
+
})().finally(() => flight.delete(key))
|
|
33
|
+
flight.set(key, work)
|
|
34
|
+
}
|
|
35
|
+
return flight.get(key)
|
|
36
|
+
}
|
|
37
|
+
}
|