@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,104 @@
1
+ #!/usr/bin/env node
2
+ // studio / doctor.mjs
3
+ //
4
+ // Check that this machine can render compositions: Node 22+ (global WebSocket),
5
+ // a local Chrome/Chromium, and ffmpeg with an H.264 encoder. --launch also starts
6
+ // headless Chrome and round-trips a CDP command to prove the whole path works.
7
+ //
8
+ // node doctor.mjs [--launch] [--json]
9
+ //
10
+ // Exit 0 when everything is ready, 1 when frames can render but ffmpeg is missing
11
+ // (render prints the command instead of encoding), 2 when rendering cannot work
12
+ // (Node too old, no Chrome, or the launch check failed).
13
+
14
+ import { realpathSync } from 'node:fs'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { spawnSync } from 'node:child_process'
17
+ import { chromeVersion, findChrome, withChrome } from './lib/cdp.mjs'
18
+ import { which } from './render.mjs'
19
+
20
+ const HELP = `doctor: can this machine render studio compositions?
21
+
22
+ node doctor.mjs [--launch] [--json]
23
+
24
+ --launch also start headless Chrome and talk CDP to it
25
+ --json machine-readable output
26
+
27
+ Exit codes: 0 ready, 1 ffmpeg missing (frames only), 2 cannot render.
28
+ `
29
+
30
+ /** Node 22+ is required for the global WebSocket the CDP client uses. */
31
+ export function checkNode(version = process.versions.node, hasWebSocket = typeof WebSocket === 'function') {
32
+ const major = Number(String(version).split('.')[0])
33
+ const ok = major >= 22 && hasWebSocket
34
+ return { name: 'node', ok, level: ok ? 'ok' : 'fatal', detail: `v${version}${hasWebSocket ? '' : ' (no global WebSocket)'}`, fix: ok ? undefined : 'install Node.js 22 or newer' }
35
+ }
36
+
37
+ export function checkChrome(env = process.env) {
38
+ const found = findChrome({ env })
39
+ if (!found.path) return { name: 'chrome', ok: false, level: 'fatal', detail: found.error, fix: 'install Google Chrome or Chromium, or set CHROME_PATH to its executable' }
40
+ const version = chromeVersion(found.path)
41
+ return { name: 'chrome', ok: true, level: 'ok', detail: `${version ?? 'version unknown'} at ${found.path}${found.source === 'CHROME_PATH' ? ' (CHROME_PATH)' : ''}`, path: found.path }
42
+ }
43
+
44
+ export function checkFfmpeg(env = process.env) {
45
+ const bin = which('ffmpeg', env)
46
+ if (!bin) return { name: 'ffmpeg', ok: false, level: 'warn', detail: 'not on PATH: render writes PNG frames and prints the ffmpeg command', fix: 'brew install ffmpeg | apt install ffmpeg | winget install ffmpeg' }
47
+ const v = spawnSync(bin, ['-hide_banner', '-version'], { encoding: 'utf8' })
48
+ const version = (v.stdout || '').split('\n')[0].replace(/^ffmpeg version\s*/, '').split(' ')[0] || 'unknown'
49
+ const enc = spawnSync(bin, ['-hide_banner', '-encoders'], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
50
+ const encoders = ['libx264', 'libvpx-vp9', 'prores_ks'].filter((e) => new RegExp(`\\b${e}\\b`).test(enc.stdout || ''))
51
+ const ok = encoders.includes('libx264')
52
+ return { name: 'ffmpeg', ok, level: ok ? 'ok' : 'warn', detail: `${version} at ${bin}; encoders: ${encoders.join(', ') || 'none of libx264/libvpx-vp9/prores_ks'}`, fix: ok ? undefined : 'install an ffmpeg build with libx264 for .mp4 output' }
53
+ }
54
+
55
+ export async function checkLaunch(chromePath) {
56
+ try {
57
+ const product = await withChrome(async ({ cdp }) => (await cdp.send('Browser.getVersion')).product, { chromePath, timeoutMs: 30000 })
58
+ return { name: 'launch', ok: true, level: 'ok', detail: `headless ${product} answered over CDP` }
59
+ } catch (e) {
60
+ return { name: 'launch', ok: false, level: 'fatal', detail: e.message.split('\n')[0], fix: 'run with CHROME_PATH pointing at a working Chrome; on Linux containers you may need --no-sandbox via a wrapper script' }
61
+ }
62
+ }
63
+
64
+ /** Exit status from a list of checks: 2 if any fatal, 1 if any warning, else 0. */
65
+ export function statusOf(checks) {
66
+ if (checks.some((c) => !c.ok && c.level === 'fatal')) return 2
67
+ if (checks.some((c) => !c.ok)) return 1
68
+ return 0
69
+ }
70
+
71
+ export async function doctor({ launch = false, env = process.env } = {}) {
72
+ const checks = [checkNode(), checkChrome(env), checkFfmpeg(env)]
73
+ if (launch && checks[0].ok && checks[1].ok) checks.push(await checkLaunch(checks[1].path))
74
+ const status = statusOf(checks)
75
+ return { ok: status === 0, status, checks }
76
+ }
77
+
78
+ async function main(argv) {
79
+ if (argv.includes('--help') || argv.includes('-h')) {
80
+ process.stdout.write(HELP)
81
+ return 0
82
+ }
83
+ const unknown = argv.filter((a) => !['--launch', '--json'].includes(a))
84
+ if (unknown.length) {
85
+ process.stderr.write(`doctor: unknown argument ${unknown[0]}\n\n${HELP}`)
86
+ return 2
87
+ }
88
+ const r = await doctor({ launch: argv.includes('--launch') })
89
+ if (argv.includes('--json')) console.log(JSON.stringify(r, null, 2))
90
+ else {
91
+ for (const c of r.checks) console.log(`${c.ok ? 'ok ' : c.level === 'fatal' ? 'FAIL' : 'warn'} ${c.name.padEnd(7)} ${c.detail}${c.fix ? `\n fix: ${c.fix}` : ''}`)
92
+ console.log(r.status === 0 ? 'ready to render' : r.status === 1 ? 'can render frames; install ffmpeg to encode video' : 'cannot render yet')
93
+ }
94
+ return r.status
95
+ }
96
+
97
+ // Run only when this file is the entry point. Real paths are compared because
98
+ // the path Node was given can be a symlink (macOS /tmp and /var, a linked
99
+ // skills folder), and then it never equals the module's own URL.
100
+ function isEntryPoint(url) {
101
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)) } catch { return false }
102
+ }
103
+
104
+ if (isEntryPoint(import.meta.url)) process.exitCode = await main(process.argv.slice(2))
@@ -0,0 +1,310 @@
1
+ // studio / lib/cdp.mjs
2
+ //
3
+ // A minimal Chrome DevTools Protocol client with no dependencies: find a local
4
+ // Chrome, launch it headless with --remote-debugging-port=0, read the browser
5
+ // WebSocket URL from stderr or DevToolsActivePort, and talk CDP over Node 22's
6
+ // global WebSocket using flattened target sessions.
7
+ //
8
+ // Nothing here touches the network beyond 127.0.0.1.
9
+
10
+ import { spawn, spawnSync } from 'node:child_process'
11
+ import fs from 'node:fs'
12
+ import os from 'node:os'
13
+ import path from 'node:path'
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Finding Chrome
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const MAC_APPS = [
20
+ 'Google Chrome.app/Contents/MacOS/Google Chrome',
21
+ 'Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
22
+ 'Chromium.app/Contents/MacOS/Chromium',
23
+ 'Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
24
+ 'Brave Browser.app/Contents/MacOS/Brave Browser',
25
+ ]
26
+ const LINUX_BINS = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'microsoft-edge-stable', 'brave-browser']
27
+ const WIN_REL = [
28
+ ['Google', 'Chrome', 'Application', 'chrome.exe'],
29
+ ['Chromium', 'Application', 'chrome.exe'],
30
+ ['Microsoft', 'Edge', 'Application', 'msedge.exe'],
31
+ ['BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'],
32
+ ]
33
+
34
+ /** Ordered list of places a Chromium browser may live on this platform. */
35
+ export function chromeCandidates(platform = process.platform, env = process.env, home = os.homedir()) {
36
+ if (platform === 'darwin') {
37
+ return [...MAC_APPS.map((a) => path.posix.join('/Applications', a)), ...MAC_APPS.map((a) => path.posix.join(home, 'Applications', a))]
38
+ }
39
+ if (platform === 'win32') {
40
+ const roots = [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean)
41
+ return roots.flatMap((r) => WIN_REL.map((rel) => path.win32.join(r, ...rel)))
42
+ }
43
+ const dirs = (env.PATH ?? '').split(':').filter(Boolean)
44
+ const onPath = LINUX_BINS.flatMap((b) => dirs.map((d) => path.posix.join(d, b)))
45
+ const fixed = ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium', '/opt/google/chrome/chrome']
46
+ return [...new Set([...onPath, ...fixed])]
47
+ }
48
+
49
+ /**
50
+ * Locate a Chromium browser. CHROME_PATH wins when set.
51
+ * Returns { path, source } or { path: null, error, tried }.
52
+ */
53
+ export function findChrome({ env = process.env, platform = process.platform, exists = fs.existsSync, home = os.homedir() } = {}) {
54
+ if (env.CHROME_PATH) {
55
+ return exists(env.CHROME_PATH)
56
+ ? { path: env.CHROME_PATH, source: 'CHROME_PATH' }
57
+ : { path: null, error: `CHROME_PATH is set to ${env.CHROME_PATH}, which does not exist`, tried: [env.CHROME_PATH] }
58
+ }
59
+ const tried = chromeCandidates(platform, env, home)
60
+ const hit = tried.find((p) => exists(p))
61
+ if (hit) return { path: hit, source: 'search' }
62
+ return { path: null, error: 'no Chrome, Chromium, Edge or Brave found; install one or set CHROME_PATH', tried }
63
+ }
64
+
65
+ /** Best-effort browser version string (Windows builds do not print one). */
66
+ export function chromeVersion(chromePath) {
67
+ try {
68
+ const r = spawnSync(chromePath, ['--version'], { encoding: 'utf8', timeout: 15000 })
69
+ return (r.stdout || '').trim() || null
70
+ } catch {
71
+ return null
72
+ }
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Launching
77
+ // ---------------------------------------------------------------------------
78
+
79
+ /** Flags for a quiet, deterministic, isolated headless browser. */
80
+ export function chromeArgs({ userDataDir, headless = true, extra = [] } = {}) {
81
+ return [
82
+ headless ? '--headless=new' : null,
83
+ '--remote-debugging-port=0',
84
+ '--remote-debugging-address=127.0.0.1',
85
+ userDataDir ? `--user-data-dir=${userDataDir}` : null,
86
+ '--no-first-run',
87
+ '--no-default-browser-check',
88
+ '--disable-extensions',
89
+ '--disable-background-networking',
90
+ '--disable-background-timer-throttling',
91
+ '--disable-backgrounding-occluded-windows',
92
+ '--disable-renderer-backgrounding',
93
+ '--disable-component-update',
94
+ '--disable-default-apps',
95
+ '--disable-sync',
96
+ '--metrics-recording-only',
97
+ '--password-store=basic',
98
+ '--use-mock-keychain',
99
+ '--hide-scrollbars',
100
+ '--mute-audio',
101
+ '--force-color-profile=srgb',
102
+ '--font-render-hinting=none',
103
+ '--allow-file-access-from-files',
104
+ ...extra,
105
+ 'about:blank',
106
+ ].filter(Boolean)
107
+ }
108
+
109
+ /** Pull the browser WebSocket URL out of Chrome's stderr. */
110
+ export function parseDevToolsUrl(text) {
111
+ const m = /DevTools listening on (ws:\/\/\S+)/.exec(String(text))
112
+ return m ? m[1] : null
113
+ }
114
+
115
+ /** DevToolsActivePort holds "<port>\n<browser path>". */
116
+ export function parseActivePort(text, host = '127.0.0.1') {
117
+ const [port, p] = String(text).trim().split(/\r?\n/)
118
+ if (!/^\d+$/.test(port ?? '') || !p) return null
119
+ return `ws://${host}:${port}${p}`
120
+ }
121
+
122
+ /**
123
+ * Launch a headless browser with a throwaway profile.
124
+ * Returns { wsUrl, proc, userDataDir, close() }.
125
+ */
126
+ export async function launchChrome({ chromePath, headless = true, extraArgs = [], timeoutMs = 30000 } = {}) {
127
+ if (!chromePath) {
128
+ const found = findChrome()
129
+ if (!found.path) throw Object.assign(new Error(found.error), { code: 'ENOCHROME' })
130
+ chromePath = found.path
131
+ }
132
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-chrome-'))
133
+ const proc = spawn(chromePath, chromeArgs({ userDataDir, headless, extra: extraArgs }), { stdio: ['ignore', 'ignore', 'pipe'] })
134
+ let stderr = ''
135
+ const wsUrl = await new Promise((resolve, reject) => {
136
+ const portFile = path.join(userDataDir, 'DevToolsActivePort')
137
+ const done = (err, url) => {
138
+ clearInterval(poll)
139
+ clearTimeout(timer)
140
+ proc.stderr.off('data', onData)
141
+ proc.off('exit', onExit)
142
+ err ? reject(err) : resolve(url)
143
+ }
144
+ const onData = (d) => {
145
+ stderr += d
146
+ const url = parseDevToolsUrl(stderr)
147
+ if (url) done(null, url)
148
+ }
149
+ const onExit = (code) => done(new Error(`Chrome exited (code ${code}) before DevTools was ready\n${stderr.slice(-2000)}`))
150
+ const poll = setInterval(() => {
151
+ try {
152
+ const url = parseActivePort(fs.readFileSync(portFile, 'utf8'))
153
+ if (url) done(null, url)
154
+ } catch {}
155
+ }, 100)
156
+ const timer = setTimeout(() => done(new Error(`Chrome did not expose DevTools within ${timeoutMs}ms\n${stderr.slice(-2000)}`)), timeoutMs)
157
+ proc.stderr.on('data', onData)
158
+ proc.on('exit', onExit)
159
+ proc.on('error', (e) => done(e))
160
+ })
161
+ proc.stderr.resume()
162
+ let closed = false
163
+ const close = async () => {
164
+ if (closed) return
165
+ closed = true
166
+ if (proc.exitCode === null) {
167
+ const exited = new Promise((res) => proc.once('exit', res))
168
+ proc.kill('SIGTERM')
169
+ const t = setTimeout(() => proc.kill('SIGKILL'), 3000)
170
+ await exited
171
+ clearTimeout(t)
172
+ }
173
+ for (let i = 0; i < 5; i++) {
174
+ try {
175
+ fs.rmSync(userDataDir, { recursive: true, force: true })
176
+ break
177
+ } catch {
178
+ await new Promise((r) => setTimeout(r, 200))
179
+ }
180
+ }
181
+ }
182
+ return { wsUrl, proc, userDataDir, close }
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // The protocol client
187
+ // ---------------------------------------------------------------------------
188
+
189
+ export class CDP {
190
+ constructor(ws) {
191
+ this.ws = ws
192
+ this.nextId = 1
193
+ this.pending = new Map()
194
+ this.listeners = new Set()
195
+ ws.addEventListener('message', (e) => this.#onMessage(e.data))
196
+ ws.addEventListener('close', () => {
197
+ for (const p of this.pending.values()) p.reject(new Error('CDP connection closed'))
198
+ this.pending.clear()
199
+ })
200
+ }
201
+
202
+ static async connect(wsUrl, { timeoutMs = 15000 } = {}) {
203
+ if (typeof WebSocket !== 'function') throw Object.assign(new Error('global WebSocket is missing: Node 22 or newer is required'), { code: 'ENODE' })
204
+ const ws = new WebSocket(wsUrl)
205
+ await new Promise((resolve, reject) => {
206
+ const t = setTimeout(() => reject(new Error(`could not connect to ${wsUrl}`)), timeoutMs)
207
+ ws.addEventListener('open', () => (clearTimeout(t), resolve()), { once: true })
208
+ ws.addEventListener('error', () => (clearTimeout(t), reject(new Error(`could not connect to ${wsUrl}`))), { once: true })
209
+ })
210
+ return new CDP(ws)
211
+ }
212
+
213
+ #onMessage(data) {
214
+ const msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8'))
215
+ if (msg.id !== undefined) {
216
+ const p = this.pending.get(msg.id)
217
+ if (!p) return
218
+ this.pending.delete(msg.id)
219
+ if (msg.error) p.reject(new Error(`${p.method}: ${msg.error.message}${msg.error.data ? ` (${msg.error.data})` : ''}`))
220
+ else p.resolve(msg.result ?? {})
221
+ return
222
+ }
223
+ for (const l of this.listeners) if (l.method === msg.method && (l.sessionId === undefined || l.sessionId === msg.sessionId)) l.fn(msg.params ?? {})
224
+ }
225
+
226
+ /** Send a command; `sessionId` targets an attached page. */
227
+ send(method, params = {}, sessionId) {
228
+ const id = this.nextId++
229
+ const payload = { id, method, params }
230
+ if (sessionId) payload.sessionId = sessionId
231
+ return new Promise((resolve, reject) => {
232
+ this.pending.set(id, { resolve, reject, method })
233
+ this.ws.send(JSON.stringify(payload))
234
+ })
235
+ }
236
+
237
+ /** Subscribe to an event; returns an unsubscribe function. */
238
+ on(method, fn, sessionId) {
239
+ const l = { method, fn, sessionId }
240
+ this.listeners.add(l)
241
+ return () => this.listeners.delete(l)
242
+ }
243
+
244
+ /** Resolve with the next matching event, or reject after `timeoutMs`. */
245
+ once(method, { sessionId, timeoutMs = 30000, predicate = () => true } = {}) {
246
+ return new Promise((resolve, reject) => {
247
+ const t = setTimeout(() => (off(), reject(new Error(`timed out waiting for ${method}`))), timeoutMs)
248
+ const off = this.on(
249
+ method,
250
+ (p) => {
251
+ if (!predicate(p)) return
252
+ clearTimeout(t)
253
+ off()
254
+ resolve(p)
255
+ },
256
+ sessionId,
257
+ )
258
+ })
259
+ }
260
+
261
+ close() {
262
+ try {
263
+ this.ws.close()
264
+ } catch {}
265
+ }
266
+ }
267
+
268
+ /** Create a new tab and attach to it with a flattened session. */
269
+ export async function openPage(cdp) {
270
+ const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' })
271
+ const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true })
272
+ return {
273
+ targetId,
274
+ sessionId,
275
+ send: (method, params) => cdp.send(method, params, sessionId),
276
+ on: (method, fn) => cdp.on(method, fn, sessionId),
277
+ once: (method, opts = {}) => cdp.once(method, { ...opts, sessionId }),
278
+ /** Evaluate an expression, awaiting promises, and return its JSON value. */
279
+ async evaluate(expression, { timeoutMs = 60000 } = {}) {
280
+ let timer
281
+ const r = await Promise.race([
282
+ cdp.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, sessionId),
283
+ new Promise((_, rej) => (timer = setTimeout(() => rej(new Error(`evaluation timed out after ${timeoutMs}ms`)), timeoutMs))),
284
+ ]).finally(() => clearTimeout(timer))
285
+ if (r.exceptionDetails) {
286
+ const d = r.exceptionDetails
287
+ throw new Error(d.exception?.description ?? d.exception?.value ?? d.text ?? 'evaluation failed')
288
+ }
289
+ return r.result?.value
290
+ },
291
+ }
292
+ }
293
+
294
+ /** Launch, connect, run `fn({ cdp, browser })`, and always tear the browser down. */
295
+ export async function withChrome(fn, opts = {}) {
296
+ const browser = await launchChrome(opts)
297
+ let cdp
298
+ try {
299
+ cdp = await CDP.connect(browser.wsUrl)
300
+ return await fn({ cdp, browser })
301
+ } finally {
302
+ if (cdp) {
303
+ let t
304
+ await Promise.race([cdp.send('Browser.close').catch(() => {}), new Promise((r) => (t = setTimeout(r, 2000)))])
305
+ clearTimeout(t)
306
+ cdp.close()
307
+ }
308
+ await browser.close()
309
+ }
310
+ }