Open History to see the last commit
1// HTTP server: serves the player, the latest .riv build and its metadata,
2// and pushes rebuild / seek notifications over Server-Sent Events.
3import http from 'node:http';
4import { createReadStream, watch, existsSync, readFileSync } from 'node:fs';
5import { readFile, stat } from 'node:fs/promises';
6import { createRequire } from 'node:module';
7import path from 'node:path';
8import { fileURLToPath } from 'node:url';
9import { buildProject, inspectProject } from './build.mjs';
10import { FeedbackStore } from './feedback.mjs';
11import { listListeners } from './listeners.mjs';
12import { MixStore } from './mix.mjs';
13import { rivMeta } from './riv-audio.mjs';
14
15const HERE = path.dirname(fileURLToPath(import.meta.url));
16const PLAYER_DIR = path.join(HERE, '..', 'player');
17
18function riveRuntimeDir() {
19 const require = createRequire(import.meta.url);
20 try {
21 return path.dirname(require.resolve('@rive-app/webgl2-advanced'));
22 } catch {
23 return path.join(HERE, '..', 'node_modules', '@rive-app', 'webgl2-advanced');
24 }
25}
26
27const MIME = {
28 '.html': 'text/html; charset=utf-8',
29 '.js': 'text/javascript; charset=utf-8',
30 '.mjs': 'text/javascript; charset=utf-8',
31 '.css': 'text/css; charset=utf-8',
32 '.wasm': 'application/wasm',
33 '.json': 'application/json; charset=utf-8',
34 '.svg': 'image/svg+xml',
35 '.png': 'image/png',
36};
37
38const MAX_BODY = 64 * 1024 * 1024;
39
40function readBody(req) {
41 return new Promise((resolve, reject) => {
42 const chunks = [];
43 let size = 0;
44 req.on('data', (d) => {
45 size += d.length;
46 if (size > MAX_BODY) {
47 reject(new Error('request too large'));
48 req.destroy();
49 } else chunks.push(d);
50 });
51 req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
52 req.on('error', reject);
53 });
54}
55
56async function readJson(req) {
57 const body = await readBody(req);
58 return body ? JSON.parse(body) : {};
59}
60
61function sendJson(res, data, status = 200) {
62 res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
63 res.end(JSON.stringify(data));
64}
65
66const IGNORED_DIRS = new Set(['build', 'node_modules', '.git']);
67const IGNORED_EXT = new Set(['.log', '.riv', '.rev', '.png.tmp', '.swp']);
68
69function isIgnored(rel) {
70 if (!rel) return true;
71 const parts = rel.split(path.sep);
72 if (parts.some((p) => IGNORED_DIRS.has(p) || (p.startsWith('.') && p.length > 1))) return true;
73 const base = parts[parts.length - 1];
74 if (base.endsWith('~') || base.startsWith('#')) return true;
75 return IGNORED_EXT.has(path.extname(base).toLowerCase());
76}
77
78function projectName(dir) {
79 try {
80 const m = readFileSync(path.join(dir, 'rive.yaml'), 'utf8').match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
81 if (m) return m[1];
82 } catch {}
83 return path.basename(dir);
84}
85
86export class PreviewServer {
87 constructor({ target, mode, watch = true, log = console.log }) {
88 this.target = target; // project dir, or a .riv file
89 this.mode = mode; // 'project' | 'riv'
90 this.watchEnabled = watch;
91 this.log = log;
92 this.clients = new Set();
93 this.version = 0;
94 this.riv = null;
95 this.meta = null;
96 this.lastError = null;
97 this.building = false;
98 this.pending = false;
99 this.runtimeDir = riveRuntimeDir();
100 this.name = mode === 'project' ? projectName(target) : path.basename(target, '.riv');
101 this.feedback = new FeedbackStore(target, { project: this.name });
102 this.mix = new MixStore(target);
103 }
104
105 async handleFeedback(req, res, p) {
106 const fb = this.feedback;
107 const withUrl = (s) => ({ ...s, url: `/shots/${s.id}.png` });
108 let m;
109 if (p === '/api/shots' && req.method === 'GET') return sendJson(res, { shots: (await fb.listDrafts()).map(withUrl) });
110 if (p === '/api/shots' && req.method === 'POST') {
111 const { image, ...meta } = await readJson(req);
112 const b64 = String(image || '').replace(/^data:image\/png;base64,/, '');
113 if (!b64) return sendJson(res, { error: 'missing image' }, 400);
114 const shot = await fb.addDraft({ png: Buffer.from(b64, 'base64'), ...meta });
115 this.log(`screenshot ${shot.timecode}${shot.artboard ? ` · ${shot.artboard}` : ''}`);
116 this.broadcast({ type: 'shots' });
117 return sendJson(res, withUrl(shot));
118 }
119 if ((m = p.match(/^\/api\/shots\/([a-z0-9-]+)$/))) {
120 if (req.method === 'PATCH') {
121 const shot = await fb.updateDraft(m[1], await readJson(req));
122 if (!shot) return sendJson(res, { error: 'not found' }, 404);
123 this.broadcast({ type: 'shots', from: req.headers['x-client'] });
124 return sendJson(res, withUrl(shot));
125 }
126 if (req.method === 'DELETE') {
127 await fb.deleteDraft(m[1]);
128 this.broadcast({ type: 'shots' });
129 return sendJson(res, { ok: true });
130 }
131 }
132 if ((m = p.match(/^\/shots\/([a-z0-9-]+)\.png$/))) return this.serveFile(res, fb.draftPng(m[1]));
133 if (p === '/api/share' && req.method === 'POST') {
134 const { message } = await readJson(req);
135 let bundle;
136 try {
137 bundle = await fb.share({ message: message || '' });
138 } catch (err) {
139 return sendJson(res, { error: err.message }, 400);
140 }
141 this.log(`sent ${bundle.shots.length} screenshot(s) to the agent: ${bundle.markdown}`);
142 this.broadcast({ type: 'shots' });
143 return sendJson(res, { ...bundle, ...this.listening() });
144 }
145 if (p === '/api/feedback' && req.method === 'GET') {
146 const bundles = await fb.listBundles();
147 return sendJson(res, { root: fb.root, ...this.listening(), bundles: bundles.slice(-10).map(({ id, createdAt, markdown, consumed, shots }) => ({ id, createdAt, markdown, consumed, count: shots.length })) });
148 }
149 return false;
150 }
151
152 /** Whether an agent is waiting for feedback right now (`wait-feedback` or MCP wait_for_feedback). */
153 listening() {
154 const listeners = listListeners(this.target);
155 return { listening: listeners.length > 0, listeners: listeners.map(({ kind, startedAt }) => ({ kind, startedAt })) };
156 }
157
158 async rebuild(reason) {
159 if (this.building) {
160 this.pending = true;
161 return;
162 }
163 this.building = true;
164 this.broadcast({ type: 'building', reason });
165 try {
166 if (this.mode === 'riv') {
167 this.riv = await readFile(this.target);
168 try {
169 this.meta = rivMeta(this.riv);
170 } catch (err) {
171 this.meta = null; // the player falls back to measuring the animation, without audio timing
172 this.log(`could not read the timeline from ${path.basename(this.target)}: ${err.message}`);
173 }
174 this.lastError = null;
175 this.version++;
176 this.log(`loaded ${path.basename(this.target)} (${(this.riv.length / 1024).toFixed(0)} KB)`);
177 } else {
178 const res = await buildProject(this.target);
179 if (!res.ok) {
180 this.lastError = res.error;
181 this.log(`build failed:\n${res.error}`);
182 } else {
183 const meta = await inspectProject(this.target);
184 this.riv = res.riv;
185 this.meta = meta;
186 this.lastError = null;
187 this.version++;
188 this.log(`built ${path.basename(res.rivPath)} in ${res.buildMs}ms${reason ? ` (${reason})` : ''}`);
189 if (res.warnings) this.log(`warnings:\n${res.warnings}`);
190 }
191 }
192 } catch (err) {
193 this.lastError = String(err?.stack || err);
194 this.log(`build failed: ${this.lastError}`);
195 } finally {
196 this.building = false;
197 }
198 this.broadcast(this.statusMessage());
199 if (this.pending) {
200 this.pending = false;
201 await this.rebuild('changed during build');
202 }
203 }
204
205 statusMessage() {
206 return { type: 'build', version: this.version, error: this.lastError, name: this.name };
207 }
208
209 broadcast(msg) {
210 const data = `data: ${JSON.stringify(msg)}\n\n`;
211 for (const res of this.clients) res.write(data);
212 }
213
214 startWatching() {
215 if (!this.watchEnabled) return;
216 let timer = null;
217 let changed = new Set();
218 const trigger = (rel) => {
219 changed.add(rel);
220 clearTimeout(timer);
221 timer = setTimeout(() => {
222 const files = [...changed];
223 changed = new Set();
224 this.rebuild(files.slice(0, 3).join(', ') + (files.length > 3 ? ` +${files.length - 3}` : ''));
225 }, 150);
226 };
227 if (this.mode === 'riv') {
228 watch(path.dirname(this.target), (_ev, file) => {
229 if (file && path.basename(file) === path.basename(this.target)) trigger(file);
230 });
231 } else {
232 watch(this.target, { recursive: true }, (_ev, file) => {
233 if (file && !isIgnored(file)) trigger(file);
234 });
235 }
236 }
237
238 async serveFile(res, file) {
239 try {
240 const st = await stat(file);
241 res.writeHead(200, {
242 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream',
243 'Content-Length': st.size,
244 'Cache-Control': 'no-cache',
245 });
246 createReadStream(file).pipe(res);
247 } catch {
248 res.writeHead(404).end('not found');
249 }
250 }
251
252 async handle(req, res) {
253 const url = new URL(req.url, 'http://localhost');
254 const p = url.pathname;
255
256 // Only this machine's own pages and tools may talk to the player. A site open in the
257 // browser can send requests to 127.0.0.1 (and a rebound DNS name can reach it), so
258 // reject other Host names and any cross-origin request.
259 const host = String(req.headers.host || '');
260 if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host)) return res.writeHead(403).end('forbidden host');
261 const origin = req.headers.origin;
262 if (origin && origin !== `http://${host}`) return res.writeHead(403).end('forbidden origin');
263
264 if (p === '/favicon.ico') return this.serveFile(res, path.join(PLAYER_DIR, 'icon-32.png'));
265 if (p === '/' || p === '/index.html') return this.serveFile(res, path.join(PLAYER_DIR, 'index.html'));
266 if (p === '/app.js' || p === '/style.css' || p === '/icon-32.png' || p === '/icon-192.png') return this.serveFile(res, path.join(PLAYER_DIR, p.slice(1)));
267 if (p.startsWith('/vendor/rive/')) {
268 const name = path.basename(p);
269 if (!/^[\w.-]+\.(mjs|wasm)$/.test(name)) return res.writeHead(404).end();
270 return this.serveFile(res, path.join(this.runtimeDir, name));
271 }
272 if (p === '/project.riv') {
273 if (!this.riv) return res.writeHead(404).end('no build yet');
274 res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'no-store' });
275 return res.end(this.riv);
276 }
277 if (p === '/meta.json') {
278 res.writeHead(200, { 'Content-Type': MIME['.json'], 'Cache-Control': 'no-store' });
279 return res.end(JSON.stringify({ name: this.name, mode: this.mode, version: this.version, error: this.lastError, meta: this.meta }));
280 }
281 if (p === '/events') {
282 res.writeHead(200, {
283 'Content-Type': 'text/event-stream',
284 'Cache-Control': 'no-store',
285 Connection: 'keep-alive',
286 });
287 res.write(`data: ${JSON.stringify(this.statusMessage())}\n\n`);
288 this.clients.add(res);
289 const ping = setInterval(() => res.write(': ping\n\n'), 15000);
290 req.on('close', () => {
291 clearInterval(ping);
292 this.clients.delete(res);
293 });
294 return;
295 }
296 if (p === '/api/mix') {
297 if (req.method === 'GET') return sendJson(res, await this.mix.read());
298 if (req.method === 'PUT') {
299 let body;
300 try {
301 body = await readJson(req);
302 } catch {
303 return sendJson(res, { error: 'bad json' }, 400);
304 }
305 const mix = await this.mix.write(body);
306 this.broadcast({ type: 'mix', from: req.headers['x-client'] });
307 return sendJson(res, mix);
308 }
309 }
310 if (p.startsWith('/api/shots') || p.startsWith('/shots/') || p === '/api/share' || p === '/api/feedback') {
311 if ((await this.handleFeedback(req, res, p)) !== false) return;
312 }
313 if (p === '/api/ping') {
314 res.writeHead(200, { 'Content-Type': MIME['.json'] });
315 return res.end(JSON.stringify({ app: 'rive-video-preview', target: this.target, clients: this.clients.size, version: this.version, pid: process.pid }));
316 }
317 if (p === '/api/seek' && req.method === 'POST') {
318 let body = '';
319 req.on('data', (d) => (body += d));
320 req.on('end', () => {
321 let msg = {};
322 try {
323 msg = JSON.parse(body || '{}');
324 } catch {}
325 this.broadcast({ type: 'seek', at: msg.at });
326 res.writeHead(200, { 'Content-Type': MIME['.json'] }).end(JSON.stringify({ clients: this.clients.size }));
327 });
328 return;
329 }
330 if (p === '/api/log' && req.method === 'POST') {
331 // The player reports copied timecodes so they also show up in the terminal.
332 let body = '';
333 req.on('data', (d) => (body += d));
334 req.on('end', () => {
335 try {
336 const msg = JSON.parse(body);
337 if (msg.copied) this.log(`copied: ${msg.copied}`);
338 } catch {}
339 res.writeHead(204).end();
340 });
341 return;
342 }
343 res.writeHead(404).end('not found');
344 }
345
346 listen(port) {
347 if (!existsSync(path.join(this.runtimeDir, 'webgl2_advanced.mjs'))) {
348 throw new Error(`Rive runtime not found in ${this.runtimeDir}; run pnpm install in the rive-video-preview package`);
349 }
350 return new Promise((resolve, reject) => {
351 const server = http.createServer((req, res) => {
352 this.handle(req, res).catch((err) => {
353 res.writeHead(500).end(String(err));
354 });
355 });
356 server.once('error', reject);
357 server.listen(port, '127.0.0.1', () => resolve(server));
358 });
359 }
360}