diff --git a/whatsapp-router/src/index.ts b/whatsapp-router/src/index.ts index 7301bac..4b9f765 100644 --- a/whatsapp-router/src/index.ts +++ b/whatsapp-router/src/index.ts @@ -1,7 +1,8 @@ import express from 'express'; import dotenv from 'dotenv'; import { registerConversationRoutes } from './routes/conversationActions'; -import whatsappActionsRouter from './routes/whatsappActions'; // New import +import whatsappActionsRouter from './routes/whatsappActions'; +import { registerLogSse } from './sse/logSse'; import { registerWebhookRoutes, clearWebhooks, @@ -39,6 +40,8 @@ if ( const app = express(); app.use(express.json()); +registerLogSse(app); + const port = Number(process.env.PORT) || 3001; const agentUrl = process.env.LLM_AGENT_URL as string | undefined; const openWaUrl = process.env.OPEN_WA_URL as string | undefined; diff --git a/whatsapp-router/src/sse/logSse.ts b/whatsapp-router/src/sse/logSse.ts new file mode 100644 index 0000000..734edd6 --- /dev/null +++ b/whatsapp-router/src/sse/logSse.ts @@ -0,0 +1,49 @@ +import { Express, Response } from 'express'; + +export function registerLogSse(app: Express) { + const clients: Response[] = []; + + app.get('/logs/sse', (req, res) => { + res.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + 'X-Accel-Buffering': 'no', + }); + + res.flushHeaders(); + + res.write('event: connected\ndata: {}\n\n'); + + const keepAlive = setInterval(() => { + res.write(':\n\n'); + }, 15000); + + clients.push(res); + console.log('🟢 SSE log client connected (%d)', clients.length); + + req.on('close', () => { + clearInterval(keepAlive); + clients.splice(clients.indexOf(res), 1); + console.log('🔌 SSE log client disconnected (%d)', clients.length); + }); + }); + + const broadcast = (data: string) => { + const payload = `data: ${data}\n\n`; + clients.forEach((c) => c.write(payload)); + }; + + const originalLog = console.log; + const originalError = console.error; + + console.log = (...args: any[]) => { + originalLog(...args); + broadcast(args.join(' ')); + }; + + console.error = (...args: any[]) => { + originalError(...args); + broadcast(args.join(' ')); + }; +}