export interface SSEEventClient { send: (data: string) => void; events?: Set; userId?: number; presenceChannel?: string; } /** * The connected-client set is anchored on `globalThis`, not module scope. Next.js * dev bundles server packages per route (`devBundleServerPackages`), so a plain * module-level Set forks into one copy per bundle: a broadcast issued from a * server-action or registry bundle would never reach a client subscribed through * the `/api/realtime` route bundle. Sharing it via `globalThis` (the same trick * the blackjack/poker stores use, and how Payload caches its instance) unifies * every bundle within the single dev process. In production there is one module * instance anyway, so this is a no-op there. */ interface BusRegistry { __ptfSseClients?: Set; } const globalBus = globalThis as typeof globalThis & BusRegistry; const clients: Set = (globalBus.__ptfSseClients ??= new Set()); export function subscribe(client: SSEEventClient): () => void { clients.add(client); return () => clients.delete(client); } export function unsubscribe(client: SSEEventClient): void { clients.delete(client); } export function clientCount(): number { return clients.size; } export function broadcast(event: string, data: unknown): number { const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; const presenceChannel = event === "presence" && typeof data === "object" && data !== null && "channel" in data && typeof data.channel === "string" ? data.channel : undefined; for (const client of clients) { if (client.events && !client.events.has(event)) continue; if ( event === "presence" && client.presenceChannel !== undefined && client.presenceChannel !== presenceChannel ) { continue; } try { client.send(payload); } catch { clients.delete(client); } } return clients.size; } export function broadcastToUser(event: string, userId: number, data: unknown): number { const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; const targetUserId = Number(userId); for (const client of clients) { if (client.userId !== targetUserId) continue; if (client.events && !client.events.has(event)) continue; try { client.send(payload); } catch { clients.delete(client); } } return clients.size; }