stream.ts 1.55 KB
import type { Route } from './context';

/** SSE 实时流 /api/stream:建立长连接,回放日志/状态历史并保活。 */
export const streamRoutes: Route[] = [
    {
        method: 'GET',
        path: '/api/stream',
        handle: ({ ctx, req, res }) => {
            res.writeHead(200, {
                'Content-Type': 'text/event-stream; charset=utf-8',
                'Cache-Control': 'no-cache',
                Connection: 'keep-alive',
            });
            res.write('retry: 3000\n\n'); // 告知客户端断线后 3s 重连
            ctx.sseClients.add(res);
            // 重放最近的日志历史,避免 (重)连接时终端空白
            for (const entry of ctx.recentLogs) {
                res.write(`event: log\ndata: ${JSON.stringify(entry)}\n\n`);
            }
            ctx.broadcast('jobs', ctx.store.list()); // 补全当前 jobs 快照
            res.write(`event: preview\ndata: ${JSON.stringify(ctx.preview.state)}\n\n`);
            res.write(`event: projectRun\ndata: ${JSON.stringify(ctx.projectRunner.getStatus())}\n\n`);
            // 每 15s 发一次心跳注释,保活连接
            const ping = setInterval(() => {
                try {
                    res.write(': ping\n\n');
                } catch {
                    /* 忽略写入失败 */
                }
            }, 15000);
            // 连接关闭时清理定时器与客户端集合
            req.on('close', () => {
                clearInterval(ping);
                ctx.sseClients.delete(res);
            });
        },
    },
];