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