serve.mjs
Unchanged pinned projection of Photography Services’ loopback SceneBench server.
// Serves a scene bench folder on localhost and records every rating to <bench>/ratings.jsonl (append-only),
// so scores, votes, tags and feedback reach the system instead of living only in one browser.
// Usage: node scripts/scene-bench/serve.mjs <benchDir> [port]
// GET / the bench's index.html (and any file under the bench folder)
// GET /api/ratings latest rating per frame id, from ratings.jsonl
// POST /api/rating { id, score?: 0..100|null, vote?: "heart"|"high"|"low"|"no"|null, tags: [], note: "" }
// Score-bearing requests derive the four-point vote; vote-only requests stay compatible.
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
const benchDir = path.resolve(process.argv[2] || '.');
const port = Number(process.argv[3] || 4321);
const log = path.join(benchDir, 'ratings.jsonl');
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.json': 'application/json', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.css': 'text/css' };
// Founder scale since 2026-09-27: no, low (mid-low), high (mid-high), heart. "meh" is kept for older rows.
const VOTES = new Set(['heart', 'high', 'low', 'meh', 'no', null]);
const HOSTS = new Set([`localhost:${port}`, `127.0.0.1:${port}`]);
const ORIGINS = new Set([...HOSTS].map(host => `http://${host}`));
function latest() {
const out = {};
if (!fs.existsSync(log)) return out;
for (const line of fs.readFileSync(log, 'utf8').split('\n')) {
if (!line.trim()) continue;
try {
const r = JSON.parse(line);
out[r.id] = r;
} catch {
// A torn last line from a crash is skipped, not fatal.
}
}
return out;
}
function send(res, status, body, type = 'application/json') {
res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
}
http
.createServer((req, res) => {
if (!HOSTS.has(req.headers.host?.toLowerCase())) return send(res, 403, { error: 'local host required' });
const url = new URL(req.url, `http://localhost:${port}`);
if (url.pathname === '/api/ratings' && req.method === 'GET') return send(res, 200, latest());
if (url.pathname === '/api/rating' && req.method === 'POST') {
if (req.headers.origin && !ORIGINS.has(req.headers.origin)) return send(res, 403, { error: 'origin not allowed' });
let body = '';
req.on('data', (c) => {
body += c;
if (body.length > 20000) req.destroy();
});
req.on('end', () => {
try {
const r = JSON.parse(body);
if (typeof r.id !== 'string' || !r.id || r.id.length > 200) throw new Error('id');
if (!VOTES.has(r.vote ?? null)) throw new Error('vote');
const hasScore = Object.hasOwn(r, 'score');
if (hasScore && r.score !== null && (!Number.isInteger(r.score) || r.score < 0 || r.score > 100)) throw new Error('score');
const score = hasScore ? r.score : undefined;
const vote = hasScore ? (score === null ? null : ['no', 'low', 'high', 'heart'][Math.min(3, Math.floor(score / 25))]) : (r.vote ?? null);
const tags = Array.isArray(r.tags) ? r.tags.filter((t) => typeof t === 'string').slice(0, 20).map((t) => t.slice(0, 40)) : [];
const note = typeof r.note === 'string' ? r.note.slice(0, 2000) : '';
const row = { id: r.id, ...(hasScore ? { score } : {}), vote, tags, note, at: new Date().toISOString() };
fs.appendFileSync(log, JSON.stringify(row) + '\n');
send(res, 200, row);
} catch (e) {
send(res, 400, { error: `bad rating: ${e.message}` });
}
});
return;
}
let rel;
try { rel = decodeURIComponent(url.pathname === '/' ? '/index.html' : url.pathname); }
catch { return send(res, 400, 'invalid path', 'text/plain'); }
const file = path.join(benchDir, rel);
const relative = path.relative(benchDir, file);
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) return send(res, 404, 'not found', 'text/plain');
send(res, 200, fs.readFileSync(file), TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream');
})
.listen(port, '127.0.0.1', () => console.log(`bench: http://localhost:${port}/ ratings -> ${log}`));