@skilldeck/studio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,466 @@
1
+ #!/usr/bin/env node
2
+ // studio / lint-comp.mjs
3
+ //
4
+ // Static checks for an HTML video composition before it is rendered: the timeline
5
+ // (gaps, overlaps, scenes past the end, off-frame cuts), local assets that do not
6
+ // exist, remote assets and webfonts, non-deterministic script (Math.random,
7
+ // Date.now, performance.now, timers, network), unseekable CSS transitions,
8
+ // unpreloaded @font-face files, and malformed SRT/VTT captions.
9
+ //
10
+ // node lint-comp.mjs <composition.html> [--strict] [--json]
11
+ //
12
+ // Exit 0 when there are no errors (warnings allowed unless --strict), 1 when the
13
+ // composition has findings that fail, 2 on bad usage or an unreadable file.
14
+ // Zero dependencies. Node 22+.
15
+
16
+ import { realpathSync } from 'node:fs'
17
+ import { fileURLToPath } from 'node:url'
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+
21
+ const HELP = `lint-comp: check an HTML video composition before rendering
22
+
23
+ node lint-comp.mjs <composition.html> [options]
24
+
25
+ --strict warnings fail too (exit 1)
26
+ --json machine-readable output
27
+
28
+ Exit codes: 0 clean, 1 findings that fail, 2 usage error or unreadable file.
29
+ `
30
+
31
+ const EPS = 1e-6
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Light HTML parsing (regex based, line-preserving)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /** Replace a span with spaces but keep newlines, so offsets and line numbers survive. */
38
+ const blank = (s) => s.replace(/[^\n]/g, ' ')
39
+
40
+ /** 1-based line number of a character offset. */
41
+ export function lineOf(text, index) {
42
+ let n = 1
43
+ for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++
44
+ return n
45
+ }
46
+
47
+ /** Parse a tag's attribute string into a lower-cased name -> value map ('' for bare attributes). */
48
+ export function parseAttrs(s) {
49
+ const out = {}
50
+ const re = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g
51
+ let m
52
+ while ((m = re.exec(s))) out[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? ''
53
+ return out
54
+ }
55
+
56
+ /**
57
+ * Split an HTML document into tags, inline scripts and inline styles.
58
+ * Comments are ignored; script/style bodies are not scanned as markup.
59
+ */
60
+ export function parseHtml(html) {
61
+ let text = html.replace(/<!--[\s\S]*?-->/g, blank)
62
+ const scripts = []
63
+ const styles = []
64
+ text = text.replace(/<(script|style)\b([^>]*)>([\s\S]*?)<\/\1\s*>/gi, (all, tag, attrs, body, offset) => {
65
+ const bodyOffset = offset + all.indexOf('>') + 1
66
+ const entry = { attrs: parseAttrs(attrs), content: body, line: lineOf(html, bodyOffset), tagLine: lineOf(html, offset) }
67
+ ;(tag.toLowerCase() === 'script' ? scripts : styles).push(entry)
68
+ // keep the opening tag visible to the tag scanner, blank the body
69
+ return all.slice(0, all.indexOf('>') + 1) + blank(body) + all.slice(all.indexOf('>') + 1 + body.length)
70
+ })
71
+ const tags = []
72
+ const re = /<([a-zA-Z][\w-]*)\b((?:[^>"']|"[^"]*"|'[^']*')*)>/g
73
+ let m
74
+ while ((m = re.exec(text))) tags.push({ tag: m[1].toLowerCase(), attrs: parseAttrs(m[2]), line: lineOf(html, m.index) })
75
+ return { tags, scripts, styles }
76
+ }
77
+
78
+ const num = (v) => (v === undefined || v === '' ? NaN : Number(v))
79
+
80
+ /** Read the composition root and its scenes from the markup. */
81
+ export function parseComposition(html) {
82
+ const { tags, scripts, styles } = parseHtml(html)
83
+ const rootTag = tags.find((t) => 'data-composition' in t.attrs)
84
+ const root = rootTag
85
+ ? {
86
+ line: rootTag.line,
87
+ width: num(rootTag.attrs['data-width']),
88
+ height: num(rootTag.attrs['data-height']),
89
+ fps: num(rootTag.attrs['data-fps']),
90
+ duration: num(rootTag.attrs['data-duration']),
91
+ }
92
+ : null
93
+ const scenes = tags
94
+ .filter((t) => 'data-scene' in t.attrs)
95
+ .map((t, i) => ({
96
+ id: t.attrs.id || t.attrs['data-scene'] || `scene#${i + 1}`,
97
+ start: num(t.attrs['data-start']),
98
+ duration: num(t.attrs['data-duration']),
99
+ track: t.attrs['data-track'] === undefined ? 0 : num(t.attrs['data-track']),
100
+ line: t.line,
101
+ }))
102
+ const captions = scripts
103
+ .filter((s) => 'data-captions' in s.attrs)
104
+ .map((s) => ({ format: s.attrs['data-captions'] || 'auto', text: s.content, line: s.line }))
105
+ return { root, scenes, tags, scripts, styles, captions }
106
+ }
107
+
108
+ // ---------------------------------------------------------------------------
109
+ // Timeline
110
+ // ---------------------------------------------------------------------------
111
+
112
+ const fmt = (t) => `${Number(t.toFixed(3))}s`
113
+
114
+ /** Gaps (track 0 only), overlaps (per track), scenes past the end, off-frame cuts. */
115
+ export function lintTimeline(root, scenes) {
116
+ const findings = []
117
+ const add = (severity, rule, message, line) => findings.push({ severity, rule, message, line })
118
+ const { duration, fps } = root
119
+ const valid = []
120
+ for (const s of scenes) {
121
+ if (!Number.isFinite(s.start) || s.start < 0) add('error', 'scene-timing', `${s.id}: data-start must be a number >= 0`, s.line)
122
+ else if (!Number.isFinite(s.duration) || s.duration <= 0) add('error', 'scene-timing', `${s.id}: data-duration must be a number > 0`, s.line)
123
+ else if (!Number.isInteger(s.track) || s.track < 0) add('error', 'scene-timing', `${s.id}: data-track must be a whole number >= 0`, s.line)
124
+ else valid.push(s)
125
+ }
126
+ if (Number.isFinite(duration)) {
127
+ for (const s of valid) {
128
+ const end = s.start + s.duration
129
+ if (end > duration + EPS) add('error', 'scene-past-end', `${s.id} ends at ${fmt(end)}, after the composition ends at ${fmt(duration)}`, s.line)
130
+ }
131
+ }
132
+ if (Number.isFinite(fps) && fps > 0) {
133
+ for (const s of valid) {
134
+ for (const [label, t] of [['starts', s.start], ['ends', s.start + s.duration]]) {
135
+ const f = t * fps
136
+ if (Math.abs(f - Math.round(f)) > 1e-4) add('warn', 'off-frame', `${s.id} ${label} at ${fmt(t)}, between frames at ${fps} fps (nearest ${fmt(Math.round(f) / fps)})`, s.line)
137
+ }
138
+ }
139
+ }
140
+ const tracks = new Map()
141
+ for (const s of valid) tracks.set(s.track, [...(tracks.get(s.track) ?? []), s])
142
+ if (!tracks.has(0)) add('error', 'no-scenes', 'no scenes on the main track: add elements with data-scene, data-start and data-duration', root.line)
143
+ for (const [track, list] of [...tracks].sort((a, b) => a[0] - b[0])) {
144
+ list.sort((a, b) => a.start - b.start || a.line - b.line)
145
+ let covered = 0
146
+ let last = null
147
+ for (const s of list) {
148
+ if (last && s.start < covered - EPS) {
149
+ add('error', 'overlap', `${s.id} (${fmt(s.start)}-${fmt(s.start + s.duration)}) overlaps ${last.id} until ${fmt(covered)} on track ${track}; move one to another data-track if the layering is intended`, s.line)
150
+ } else if (track === 0 && s.start > covered + EPS) {
151
+ add('error', 'gap', `gap ${fmt(covered)}-${fmt(s.start)} before ${s.id}: nothing is on screen`, s.line)
152
+ }
153
+ if (s.start + s.duration > covered) {
154
+ covered = s.start + s.duration
155
+ last = s
156
+ }
157
+ }
158
+ if (track === 0 && Number.isFinite(duration) && covered < duration - EPS) {
159
+ add('error', 'gap', `gap ${fmt(covered)}-${fmt(duration)} at the end: the last scene ends before the composition`, last?.line ?? root.line)
160
+ }
161
+ }
162
+ return findings
163
+ }
164
+
165
+ // ---------------------------------------------------------------------------
166
+ // Captions (SRT / WebVTT)
167
+ // ---------------------------------------------------------------------------
168
+
169
+ /** Parse "01:02:03,456", "02:03.456" or "02:03.5" into seconds; NaN if malformed. */
170
+ export function parseTimestamp(s) {
171
+ const m = /^(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})$/.exec(String(s).trim())
172
+ if (!m) return NaN
173
+ return Number(m[1] ?? 0) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number((m[4] + '00').slice(0, 3)) / 1000
174
+ }
175
+
176
+ /** Parse SRT or WebVTT text into cues. Returns { format, cues, errors }. */
177
+ export function parseCaptions(text, format = 'auto') {
178
+ const src = String(text).replace(/\r\n?/g, '\n').replace(/^/, '').trim()
179
+ const fmtName = format === 'auto' ? (/^WEBVTT\b/.test(src) ? 'vtt' : 'srt') : format
180
+ const cues = []
181
+ const errors = []
182
+ let lineNo = 1
183
+ for (const block of src.split(/\n[ \t]*\n/)) {
184
+ const lines = block.split('\n')
185
+ const blockLine = lineNo
186
+ lineNo += lines.length + 1
187
+ const i = lines.findIndex((l) => l.includes('-->'))
188
+ if (i < 0) {
189
+ if (/^(WEBVTT|NOTE|STYLE|REGION)\b/.test(lines[0]) || !block.trim()) continue
190
+ errors.push({ line: blockLine, message: `no "-->" timing line in cue "${lines[0].slice(0, 40)}"` })
191
+ continue
192
+ }
193
+ const [a, b = ''] = lines[i].split('-->')
194
+ const start = parseTimestamp(a)
195
+ const end = parseTimestamp(b.trim().split(/\s+/)[0])
196
+ if (!Number.isFinite(start) || !Number.isFinite(end)) {
197
+ errors.push({ line: blockLine + i, message: `malformed timing "${lines[i].trim()}"` })
198
+ continue
199
+ }
200
+ if (end <= start) {
201
+ errors.push({ line: blockLine + i, message: `cue ends (${fmt(end)}) before it starts (${fmt(start)})` })
202
+ continue
203
+ }
204
+ const body = lines
205
+ .slice(i + 1)
206
+ .join('\n')
207
+ .replace(/<[^>]+>/g, '')
208
+ .trim()
209
+ cues.push({ start, end, text: body, line: blockLine + i })
210
+ }
211
+ return { format: fmtName, cues, errors }
212
+ }
213
+
214
+ export function lintCaptions(captions, root, { hasTarget }) {
215
+ const findings = []
216
+ for (const c of captions) {
217
+ const { cues, errors } = parseCaptions(c.text, c.format)
218
+ for (const e of errors) findings.push({ severity: 'error', rule: 'caption-parse', message: e.message, line: c.line + e.line - 1 })
219
+ const sorted = [...cues].sort((x, y) => x.start - y.start)
220
+ for (let i = 1; i < sorted.length; i++) {
221
+ if (sorted[i].start < sorted[i - 1].end - EPS) findings.push({ severity: 'warn', rule: 'caption-overlap', message: `cue at ${fmt(sorted[i].start)} starts before the previous cue ends (${fmt(sorted[i - 1].end)})`, line: c.line + sorted[i].line - 1 })
222
+ }
223
+ for (const q of cues) {
224
+ if (Number.isFinite(root.duration) && q.end > root.duration + EPS) findings.push({ severity: 'warn', rule: 'caption-past-end', message: `cue "${q.text.slice(0, 30)}" ends at ${fmt(q.end)}, after the composition ends`, line: c.line + q.line - 1 })
225
+ }
226
+ if (!cues.length && !errors.length) findings.push({ severity: 'warn', rule: 'caption-parse', message: 'captions block has no cues', line: c.line })
227
+ }
228
+ if (captions.length && !hasTarget) findings.push({ severity: 'warn', rule: 'caption-target', message: 'captions are defined but no element has data-caption-target, so they never show', line: captions[0].line })
229
+ return findings
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Script and CSS determinism
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /** Remove JS comments while keeping offsets (good enough for a lint, not a parser). */
237
+ export function stripJsComments(code) {
238
+ return code.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:\\"'`])\/\/[^\n]*/g, (m, pre) => pre + blank(m.slice(pre.length)))
239
+ }
240
+
241
+ const SCRIPT_RULES = [
242
+ { rule: 'math-random', severity: 'error', re: /\bMath\.random\s*\(/g, message: 'Math.random() gives different frames on every render; use __studio.random(seed)' },
243
+ { rule: 'wall-clock', severity: 'error', re: /\bDate\.now\s*\(|\bnew\s+Date\s*\(\s*\)/g, message: 'wall-clock time differs per render; derive everything from the seek time t' },
244
+ { rule: 'wall-clock', severity: 'error', re: /\bperformance\.now\s*\(/g, message: 'performance.now() is wall-clock time; derive everything from the seek time t' },
245
+ { rule: 'timer-animation', severity: 'error', re: /\bsetInterval\s*\(/g, message: 'setInterval-driven animation cannot be seeked; move it into __studio.onSeek(fn)' },
246
+ { rule: 'timer-animation', severity: 'warn', re: /\bsetTimeout\s*\(/g, message: 'setTimeout runs on wall-clock time, not the composition clock; prefer __studio.onSeek(fn)' },
247
+ { rule: 'raf-animation', severity: 'warn', re: /\brequestAnimationFrame\s*\(/g, message: 'requestAnimationFrame loops run on wall-clock time; drive state from __studio.onSeek(fn)' },
248
+ ]
249
+
250
+ /** Scan JS for non-deterministic calls and network access. `line` is the line the code starts on. */
251
+ export function scanScript(code, line = 1) {
252
+ const src = stripJsComments(code)
253
+ const findings = []
254
+ const at = (i) => line + lineOf(src, i) - 1
255
+ for (const r of SCRIPT_RULES) {
256
+ for (const m of src.matchAll(r.re)) findings.push({ severity: r.severity, rule: r.rule, message: r.message, line: at(m.index) })
257
+ }
258
+ for (const m of src.matchAll(/\bfetch\s*\(\s*(['"`]?)([^'"`)\s]*)\1|\bnew\s+(XMLHttpRequest|WebSocket|EventSource)\b|\bimport\s*\(\s*['"](https?:[^'"]+)/g)) {
259
+ const url = m[2] ?? m[4] ?? ''
260
+ const remote = /^(https?:|wss?:)?\/\//.test(url) || /WebSocket|EventSource/.test(m[3] ?? '') || Boolean(m[4])
261
+ findings.push({
262
+ severity: 'error',
263
+ rule: 'network',
264
+ message: remote
265
+ ? `network access at render time (${url || m[3]}) makes frames depend on the network; vendor the data next to the composition and inline it`
266
+ : `${m[3] ?? 'fetch'}${url ? ` of "${url}"` : ''} fails over file:// in headless Chrome; inline the data in <script type="application/json">`,
267
+ line: at(m.index),
268
+ })
269
+ }
270
+ return findings
271
+ }
272
+
273
+ const isRemote = (u) => /^(https?:)?\/\//i.test(u)
274
+ const isSkippable = (u) => !u || /^(data:|blob:|about:|javascript:|mailto:|#|\$\{|\{\{)/i.test(u)
275
+
276
+ /** url(...) references in CSS with their offsets. */
277
+ export function cssUrls(css) {
278
+ const out = []
279
+ for (const m of css.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g)) out.push({ url: m[2].trim(), index: m.index })
280
+ for (const m of css.matchAll(/@import\s+(['"])([^'"]+)\1/g)) out.push({ url: m[2].trim(), index: m.index })
281
+ return out
282
+ }
283
+
284
+ /** Unseekable transitions and @font-face sources in a stylesheet. */
285
+ export function scanCss(css, line = 1) {
286
+ const findings = []
287
+ const fonts = []
288
+ for (const m of css.matchAll(/(?:^|[;{\s])transition(?:-property)?\s*:\s*([^;}]*)/g)) {
289
+ if (/^\s*(none|initial|unset)\s*$/.test(m[1])) continue
290
+ findings.push({ severity: 'warn', rule: 'css-transition', message: 'CSS transitions start when state changes and are not seekable; use @keyframes animations', line: line + lineOf(css, m.index) - 1 })
291
+ }
292
+ for (const m of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
293
+ for (const u of cssUrls(m[1])) fonts.push({ url: u.url, line: line + lineOf(css, m.index) - 1 })
294
+ }
295
+ return { findings, fonts }
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // The whole composition
300
+ // ---------------------------------------------------------------------------
301
+
302
+ const ASSET_ATTRS = { src: ['img', 'video', 'audio', 'source', 'script', 'iframe', 'embed', 'track', 'input'], poster: ['video'], href: ['link'], 'xlink:href': ['image', 'use'] }
303
+
304
+ /**
305
+ * Lint composition HTML. `baseDir` resolves relative assets; `exists` and
306
+ * `readFile` are injectable for tests.
307
+ */
308
+ export function lintComposition(html, { baseDir = '.', file = 'composition.html', exists = fs.existsSync, readFile = (p) => fs.readFileSync(p, 'utf8') } = {}) {
309
+ const comp = parseComposition(html)
310
+ const findings = []
311
+ const add = (severity, rule, message, line, where = file) => findings.push({ severity, rule, message, line, file: where })
312
+ const push = (list, where = file) => list.forEach((f) => findings.push({ file: where, ...f }))
313
+
314
+ // root and clock
315
+ const { root } = comp
316
+ if (!root) {
317
+ add('error', 'no-root', 'no composition root: add data-composition with data-width, data-height, data-fps and data-duration', 1)
318
+ } else {
319
+ for (const k of ['width', 'height']) if (!Number.isInteger(root[k]) || root[k] <= 0) add('error', 'root-config', `data-${k} must be a positive whole number of pixels`, root.line)
320
+ if (!Number.isFinite(root.fps) || root.fps <= 0 || root.fps > 240) add('error', 'root-config', 'data-fps must be a number between 1 and 240', root.line)
321
+ if (!Number.isFinite(root.duration) || root.duration <= 0) add('error', 'root-config', 'data-duration must be a positive number of seconds', root.line)
322
+ if ((root.width % 2 || root.height % 2) && Number.isInteger(root.width) && Number.isInteger(root.height)) add('warn', 'odd-dimensions', `${root.width}x${root.height} has an odd side; H.264 (yuv420p) needs even dimensions`, root.line)
323
+ push(lintTimeline(root, comp.scenes))
324
+ }
325
+ const hasRuntime = comp.scripts.some((s) => 'data-studio-runtime' in s.attrs || /window\.__studio\s*=/.test(s.content))
326
+ if (!hasRuntime) add('error', 'no-clock', 'no seekable clock: include the studio runtime (<script data-studio-runtime>) or define window.__studio.seek(t)', root?.line ?? 1)
327
+
328
+ // captions
329
+ if (root) push(lintCaptions(comp.captions, root, { hasTarget: comp.tags.some((t) => 'data-caption-target' in t.attrs) }))
330
+
331
+ // inline scripts (skip the runtime and data blocks)
332
+ for (const s of comp.scripts) {
333
+ const type = (s.attrs.type || 'text/javascript').toLowerCase()
334
+ if ('data-studio-runtime' in s.attrs || 'data-captions' in s.attrs) continue
335
+ if (!/javascript|module|^$/.test(type)) continue
336
+ push(scanScript(s.content, s.line))
337
+ }
338
+
339
+ // assets, fonts, stylesheets
340
+ const preloadedFonts = new Set()
341
+ const fontFaces = []
342
+ const checkRef = (ref, line, where, dir, kind = 'asset') => {
343
+ if (isSkippable(ref)) return null
344
+ if (isRemote(ref)) {
345
+ const font = kind === 'font' || /fonts\.(googleapis|gstatic)\.com|use\.typekit|fonts\.bunny/.test(ref)
346
+ add('error', font ? 'remote-font' : 'remote-asset', `${ref} loads over the network at render time; download it next to the composition and reference it relatively`, line, where)
347
+ return null
348
+ }
349
+ const clean = decodeURI(ref.split(/[?#]/)[0])
350
+ if (clean.startsWith('/')) {
351
+ add('error', 'absolute-asset', `${ref} is root-absolute and resolves to the filesystem root under file://; use a relative path`, line, where)
352
+ return null
353
+ }
354
+ const abs = path.resolve(dir, clean)
355
+ if (!exists(abs)) {
356
+ add('error', 'missing-asset', `${ref} not found (looked for ${path.relative(process.cwd(), abs) || abs})`, line, where)
357
+ return null
358
+ }
359
+ return abs
360
+ }
361
+
362
+ const scanStylesheet = (css, line, where, dir) => {
363
+ const { findings: f, fonts } = scanCss(css, line)
364
+ push(f, where)
365
+ for (const font of fonts) fontFaces.push({ ...font, where, dir })
366
+ const fontUrls = new Set(fonts.map((x) => x.url))
367
+ for (const u of cssUrls(css)) if (!fontUrls.has(u.url)) checkRef(u.url, line + lineOf(css, u.index) - 1, where, dir)
368
+ }
369
+
370
+ for (const t of comp.tags) {
371
+ for (const [attr, tagNames] of Object.entries(ASSET_ATTRS)) {
372
+ if (!(attr in t.attrs) || !tagNames.includes(t.tag)) continue
373
+ const ref = t.attrs[attr]
374
+ if (t.tag === 'link') {
375
+ const rel = (t.attrs.rel || '').toLowerCase()
376
+ if (!/stylesheet|preload|icon|modulepreload/.test(rel)) continue
377
+ const isFont = rel.includes('preload') && t.attrs.as === 'font'
378
+ const abs = checkRef(ref, t.line, file, baseDir, isFont || /fonts\./.test(ref) ? 'font' : 'asset')
379
+ if (isFont && abs) preloadedFonts.add(abs)
380
+ if (abs && rel.includes('stylesheet')) {
381
+ try {
382
+ scanStylesheet(readFile(abs), 1, path.relative(baseDir, abs), path.dirname(abs))
383
+ } catch {}
384
+ }
385
+ continue
386
+ }
387
+ const abs = checkRef(ref, t.line, file, baseDir)
388
+ if (abs && t.tag === 'script') {
389
+ try {
390
+ push(scanScript(readFile(abs), 1), path.relative(baseDir, abs))
391
+ } catch {}
392
+ }
393
+ }
394
+ if (t.attrs.srcset) for (const part of t.attrs.srcset.split(',')) checkRef(part.trim().split(/\s+/)[0], t.line, file, baseDir)
395
+ if (t.attrs.style) for (const u of cssUrls(t.attrs.style)) checkRef(u.url, t.line, file, baseDir)
396
+ if (t.tag === 'video' && 'autoplay' in t.attrs) add('warn', 'autoplay', '<video autoplay> plays on wall-clock time; the runtime seeks media itself, remove autoplay', t.line)
397
+ }
398
+ for (const s of comp.styles) scanStylesheet(s.content, s.line, file, baseDir)
399
+
400
+ for (const f of fontFaces) {
401
+ if (isRemote(f.url)) {
402
+ add('error', 'remote-font', `@font-face loads ${f.url} over the network; download the font file and reference it relatively`, f.line, f.where)
403
+ continue
404
+ }
405
+ const abs = checkRef(f.url, f.line, f.where, f.dir, 'font')
406
+ if (abs && !preloadedFonts.has(abs)) add('warn', 'font-not-preloaded', `${f.url} is not preloaded; first frames can render in a fallback font. Add <link rel="preload" as="font" href="${f.url}" crossorigin>`, f.line, f.where)
407
+ }
408
+
409
+ findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1) || (a.file === b.file ? (a.line ?? 0) - (b.line ?? 0) : 0))
410
+ const errors = findings.filter((f) => f.severity === 'error').length
411
+ return {
412
+ file,
413
+ config: root && { width: root.width, height: root.height, fps: root.fps, duration: root.duration, frames: Number.isFinite(root.fps * root.duration) ? Math.round(root.fps * root.duration) : null },
414
+ scenes: comp.scenes.map(({ id, start, duration, track, line }) => ({ id, start, duration, end: start + duration, track, line })),
415
+ captions: comp.captions.reduce((n, c) => n + parseCaptions(c.text, c.format).cues.length, 0),
416
+ findings,
417
+ errors,
418
+ warnings: findings.length - errors,
419
+ ok: errors === 0,
420
+ }
421
+ }
422
+
423
+ export function lintFile(file, opts = {}) {
424
+ const html = fs.readFileSync(file, 'utf8')
425
+ return lintComposition(html, { baseDir: path.dirname(path.resolve(file)), file: path.basename(file), ...opts })
426
+ }
427
+
428
+ export function formatReport(r) {
429
+ const out = []
430
+ if (r.config) out.push(`${r.file}: ${r.config.width}x${r.config.height} @ ${r.config.fps} fps, ${r.config.duration}s (${r.config.frames} frames), ${r.scenes.length} scenes, ${r.captions} caption cues`)
431
+ else out.push(`${r.file}`)
432
+ for (const f of r.findings) out.push(` ${f.severity === 'error' ? 'error' : 'warn '} ${f.file}:${f.line ?? '?'} ${f.rule.padEnd(18)} ${f.message}`)
433
+ out.push(r.findings.length ? `${r.errors} error(s), ${r.warnings} warning(s)` : 'clean: no findings')
434
+ return out.join('\n')
435
+ }
436
+
437
+ function main(argv) {
438
+ if (argv.includes('--help') || argv.includes('-h')) {
439
+ process.stdout.write(HELP)
440
+ return 0
441
+ }
442
+ const [file] = argv.filter((a) => !a.startsWith('--'))
443
+ if (!file) {
444
+ process.stderr.write(HELP)
445
+ return 2
446
+ }
447
+ let report
448
+ try {
449
+ report = lintFile(file)
450
+ } catch (err) {
451
+ process.stderr.write(`lint-comp: cannot read ${file}: ${err.message}\n`)
452
+ return 2
453
+ }
454
+ if (argv.includes('--json')) console.log(JSON.stringify(report, null, 2))
455
+ else console.log(formatReport(report))
456
+ return report.errors || (argv.includes('--strict') && report.warnings) ? 1 : 0
457
+ }
458
+
459
+ // Run only when this file is the entry point. Real paths are compared because
460
+ // the path Node was given can be a symlink (macOS /tmp and /var, a linked
461
+ // skills folder), and then it never equals the module's own URL.
462
+ function isEntryPoint(url) {
463
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)) } catch { return false }
464
+ }
465
+
466
+ if (isEntryPoint(import.meta.url)) process.exitCode = main(process.argv.slice(2))