Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

server.mjs

330 lines12.0 KB

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