Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139import { createServer } from 'node:http';import { readFile, stat } from 'node:fs/promises';import { join, normalize, extname } from 'node:path';import { webRoot, home } from './paths.js';import { publicConfig, saveConfig, setSecret, addRecent, loadConfig } from './config.js';import { chat, listModels, providerStatus } from './llm.js';import * as files from './fs.js';import { systemFonts, fontFile, googleFont } from './fonts.js';import { rasterizers, rasterize } from './raster.js';
const STATIC_MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json', '.woff2': 'font/woff2', '.ico': 'image/x-icon',};
function json (res, status, body) { const data = JSON.stringify(body); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(data) }); res.end(data);}
async function readBody (req, limit = 256 * 1024 * 1024) { const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size > limit) throw Object.assign(new Error('Body too large'), { status: 413 }); chunks.push(chunk); } const text = Buffer.concat(chunks).toString('utf-8'); return text ? JSON.parse(text) : {};}
async function serveStatic (req, res, pathname) { let rel = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, ''); if (rel === '/' || rel === '') rel = '/index.html'; const file = join(webRoot, rel); if (!file.startsWith(webRoot)) { res.writeHead(403); return res.end(); } try { const s = await stat(file); if (!s.isFile()) throw new Error('not a file'); const data = await readFile(file); res.writeHead(200, { 'Content-Type': STATIC_MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' }); res.end(data); } catch { res.writeHead(404); res.end('Not found'); }}
// Server-sent events for the LLM stream.function sse (res) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' }); return (type, payload) => res.write(`data: ${JSON.stringify({ type, ...payload })}\n\n`);}
const routes = { 'GET /api/status': async () => { const cfg = await loadConfig(); return { home, providers: await providerStatus(), rasterizers: await rasterizers(), recent: cfg.files.recent, lastDir: cfg.files.lastDir }; }, 'GET /api/config': () => publicConfig(), 'PUT /api/config': async ({ body }) => { await saveConfig(body); return publicConfig(); }, 'PUT /api/secrets': async ({ body }) => { for (const [k, v] of Object.entries(body)) { if (!['anthropicApiKey', 'halfmindToken'].includes(k)) throw Object.assign(new Error(`Unknown secret ${k}`), { status: 400 }); await setSecret(k, v); } return publicConfig(); }, 'GET /api/llm/models': async ({ url }) => ({ models: await listModels(url.searchParams.get('provider')) }), 'GET /api/llm/status': () => providerStatus(), 'POST /api/llm/chat': async ({ req, res, body }) => { const send = sse(res); const ac = new AbortController(); req.on('close', () => ac.abort()); try { const r = await chat({ ...body, signal: ac.signal, onDelta: text => send('delta', { text }) }); send('done', { provider: r.provider, model: r.model, text: r.text, usage: r.usage || null }); } catch (err) { if (!ac.signal.aborted) send('error', { message: err.message || String(err) }); } res.end(); return null; // already responded }, 'GET /api/fs/list': ({ url }) => files.list(url.searchParams.get('path') || home, url.searchParams.get('filter')), 'GET /api/fs/read': ({ url }) => files.read(url.searchParams.get('path')), 'PUT /api/fs/write': async ({ body }) => { const r = await files.write(body.path, body); if (body.remember !== false) { await addRecent(r.path); await saveConfig({ files: { lastDir: join(r.path, '..') } }); } return r; }, 'POST /api/fs/recent': async ({ body }) => { await addRecent(body.path); await saveConfig({ files: { lastDir: join(body.path, '..') } }); return { ok: true }; }, 'GET /api/fonts/system': async () => ({ families: await systemFonts() }), 'GET /api/fonts/file': ({ url }) => fontFile(url.searchParams.get('path')), 'GET /api/fonts/google': ({ url }) => googleFont(url.searchParams.get('family'), { weights: (url.searchParams.get('weights') || '400;700').split(/[;,]/).filter(Boolean), italics: url.searchParams.get('italics') === '1', }), // Fetch a remote image so it can be embedded (the browser's CORS rules would block it). 'GET /api/fetch': async ({ url }) => { const target = url.searchParams.get('url') || ''; if (!/^https?:\/\//i.test(target)) throw Object.assign(new Error('Only http(s) URLs can be fetched'), { status: 400 }); const r = await fetch(target, { signal: AbortSignal.timeout(20000), headers: { 'User-Agent': 'kavu/0.1' } }); if (!r.ok) throw Object.assign(new Error(`Fetch failed: ${r.status}`), { status: 502 }); const buf = Buffer.from(await r.arrayBuffer()); if (buf.length > 64 * 1024 * 1024) throw Object.assign(new Error('File too large'), { status: 413 }); return { mime: r.headers.get('content-type')?.split(';')[0] || 'application/octet-stream', base64: buf.toString('base64'), size: buf.length }; }, 'POST /api/raster': async ({ res, body }) => { const buf = await rasterize(body); const mime = body.format === 'jpeg' ? 'image/jpeg' : body.format === 'webp' ? 'image/webp' : 'image/png'; res.writeHead(200, { 'Content-Type': mime, 'Content-Length': buf.length }); res.end(buf); return null; },};
export function createApp () { return createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost'); if (!url.pathname.startsWith('/api/')) return serveStatic(req, res, url.pathname); const handler = routes[`${req.method} ${url.pathname}`]; if (!handler) return json(res, 404, { error: `No route ${req.method} ${url.pathname}` }); try { const body = req.method === 'GET' ? null : await readBody(req); const result = await handler({ req, res, url, body }); if (result !== null && !res.headersSent) json(res, 200, result); } catch (err) { const status = err.status || 500; if (!res.headersSent) json(res, status, { error: err.message || String(err) }); else res.end(); if (status >= 500) console.error(err); } });}