@bymax-one/nest-realtime 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1083 @@
1
+ import { ModuleMetadata, Type, Provider, DynamicModule, MessageEvent, INestApplicationContext } from '@nestjs/common';
2
+ import { Server, Socket, ServerOptions } from 'socket.io';
3
+ import { Subject } from 'rxjs';
4
+ import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
5
+ import { IoAdapter } from '@nestjs/platform-socket.io';
6
+
7
+ /**
8
+ * @fileoverview Config-level transport mode selection.
9
+ * @layer shared
10
+ */
11
+ /**
12
+ * Transport mode chosen by the consumer at module configuration time.
13
+ *
14
+ * - `sse` — Server-Sent Events only. HTTP-based, server → client push.
15
+ * - `websocket` — Socket.IO only. Full duplex.
16
+ * - `both` — Compose SSE and WebSocket. Useful during migrations or when
17
+ * different product surfaces need different transports.
18
+ *
19
+ * Distinct from `ITransport.kind` (`'sse' | 'websocket'`), which identifies a
20
+ * single concrete transport implementation. See
21
+ * `docs/technical_specification.md` §1.3 for selection criteria.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const mode: TransportMode = 'sse'
26
+ * ```
27
+ */
28
+ type TransportMode = 'sse' | 'websocket' | 'both';
29
+
30
+ /**
31
+ * @fileoverview The single auth contract the library owns (auth inversion).
32
+ * @layer contracts
33
+ */
34
+ /**
35
+ * Transport-agnostic context passed to `IConnectionAuthenticator.authenticate`.
36
+ *
37
+ * Built from the HTTP request (SSE) or the Socket.IO handshake (WebSocket).
38
+ * Cookies are parsed; header names are normalized to lowercase.
39
+ */
40
+ interface ConnectionAuthContext {
41
+ /** Cookies parsed from the request/handshake headers. */
42
+ readonly cookies: Record<string, string>;
43
+ /**
44
+ * Selected headers (lowercase keys). `authorization` is always stripped for SSE:
45
+ * an `EventSource` cannot send custom headers, so it is never a valid SSE auth
46
+ * channel (use a cookie or the ticket pattern). It is available for WebSocket.
47
+ */
48
+ readonly headers: Record<string, string | undefined>;
49
+ /**
50
+ * Query string parameters — useful for the ticket pattern.
51
+ *
52
+ * Values follow the Node `ParsedUrlQuery` shape: a repeated key (`?a=1&a=2`)
53
+ * arrives as a `string[]`. Authenticators that expect a single value should
54
+ * normalize accordingly; the WebSocket gateway already collapses the `ticket`
55
+ * parameter to a single string before delegating.
56
+ */
57
+ readonly query: Record<string, string | string[] | undefined>;
58
+ /**
59
+ * Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
60
+ * spoofable unless set by a trusted proxy; do not use it for security decisions
61
+ * without validating the proxy chain.
62
+ */
63
+ readonly ip: string;
64
+ /** Raw User-Agent. */
65
+ readonly userAgent: string | undefined;
66
+ /** Transport kind initiating the connection. */
67
+ readonly transport: 'sse' | 'websocket';
68
+ }
69
+ /**
70
+ * Authenticated traits returned by a successful `authenticate()` call. Consumers
71
+ * may carry extra fields through the `metadata` bag.
72
+ */
73
+ interface AuthenticationResult {
74
+ readonly userId: string;
75
+ readonly tenantId?: string;
76
+ readonly roles?: readonly string[];
77
+ /** Free-form extras for downstream code (e.g. feature flags, plan tier). */
78
+ readonly metadata?: Record<string, unknown>;
79
+ }
80
+ /**
81
+ * Connection authenticator contract — the only auth surface the library owns.
82
+ *
83
+ * Implementations bridge the library to whatever auth strategy the consumer uses
84
+ * (cookie JWT, the ticket pattern, a bearer header in WS, etc.). The library
85
+ * NEVER imports a concrete auth library; see `docs/technical_specification.md`
86
+ * §1.6 ("auth inversion").
87
+ *
88
+ * @example
89
+ * ```ts
90
+ * class CookieAuthenticator implements IConnectionAuthenticator {
91
+ * async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
92
+ * const token = ctx.cookies['access_token']
93
+ * if (!token) return null
94
+ * const claims = await verify(token)
95
+ * return { userId: claims.sub, tenantId: claims.tid, roles: claims.roles }
96
+ * }
97
+ * }
98
+ * ```
99
+ */
100
+ interface IConnectionAuthenticator {
101
+ /**
102
+ * Authenticate a new connection request.
103
+ *
104
+ * @returns the authenticated result, or `null` to reject the connection (the
105
+ * transport replies 401 / disconnects accordingly).
106
+ */
107
+ authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
108
+ /**
109
+ * Optionally re-validate during long sessions. Called periodically based on
110
+ * `reauthenticationPolicy.intervalSeconds`.
111
+ *
112
+ * @returns `true` to keep the connection alive, `false` to disconnect.
113
+ */
114
+ revalidate?(connectionId: string, originalAuth: AuthenticationResult): Promise<boolean>;
115
+ }
116
+
117
+ /**
118
+ * @fileoverview Optional connection lifecycle hooks the consumer can provide.
119
+ * @layer contracts
120
+ */
121
+ /** Metadata describing a connection at a lifecycle transition. */
122
+ interface ConnectionEventMeta {
123
+ readonly connectionId: string;
124
+ readonly userId: string;
125
+ readonly tenantId: string | undefined;
126
+ readonly transport: 'sse' | 'websocket';
127
+ readonly ip: string;
128
+ readonly userAgent: string | undefined;
129
+ readonly connectedAt: Date;
130
+ }
131
+ /**
132
+ * Optional lifecycle hooks invoked by the active transport. Every hook may be
133
+ * synchronous or asynchronous; rejected promises are isolated so one failing hook
134
+ * never blocks delivery to other connections.
135
+ */
136
+ interface IConnectionLifecycleHooks {
137
+ /** Called after authentication succeeds and the connection is registered. */
138
+ onConnect?(meta: ConnectionEventMeta): void | Promise<void>;
139
+ /** Called when the connection closes for any reason. */
140
+ onDisconnect?(meta: ConnectionEventMeta & {
141
+ reason?: string;
142
+ durationMs: number;
143
+ }): void | Promise<void>;
144
+ /** Called on a transport error. */
145
+ onError?(meta: {
146
+ connectionId?: string;
147
+ error: Error;
148
+ transport: 'sse' | 'websocket';
149
+ }): void | Promise<void>;
150
+ /** Called on re-authentication failure, before disconnect. */
151
+ onReauthenticationFailed?(meta: ConnectionEventMeta): void | Promise<void>;
152
+ }
153
+
154
+ /**
155
+ * @fileoverview Cross-instance message bus contract for SSE horizontal scaling.
156
+ * @layer contracts
157
+ */
158
+ /** A single cross-instance fan-out message. */
159
+ interface RealtimePubSubMessage {
160
+ /** Operation type. */
161
+ readonly op: 'emitToUser' | 'emitToTenant' | 'emitToRoom' | 'broadcast' | 'disconnect';
162
+ /** Operation arguments — the concrete shape is narrowed per `op` at the call site. */
163
+ readonly args: unknown;
164
+ /** Instance id that originated the message (used to avoid echo). */
165
+ readonly origin: string;
166
+ }
167
+ /**
168
+ * Cross-instance message bus.
169
+ *
170
+ * The library provides `InMemoryPubSub` (the single-instance default) and ships a
171
+ * reference Redis-backed implementation (`RedisRealtimePubSub`) for multi-instance
172
+ * deployments. For WebSocket-only deployments, `@socket.io/redis-adapter` is the
173
+ * recommended scaling primitive and `IRealtimePubSub` is not required.
174
+ */
175
+ interface IRealtimePubSub {
176
+ /** Publish a message to all subscribers (the other instances). */
177
+ publish(message: RealtimePubSubMessage): Promise<void>;
178
+ /** Subscribe to messages. Resolves to an async unsubscribe handle. */
179
+ subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
180
+ }
181
+
182
+ /**
183
+ * @fileoverview Optional durable offline-queue storage for Last-Event-ID replay.
184
+ * @layer contracts
185
+ */
186
+ /** A single event persisted in a user's offline queue. */
187
+ interface OfflineQueuedEvent {
188
+ /** Monotonic id — used as `Last-Event-ID` across reconnections. */
189
+ readonly id: string;
190
+ readonly event: string;
191
+ readonly data: unknown;
192
+ readonly emittedAt: Date;
193
+ }
194
+ /**
195
+ * Optional durable per-user offline queue.
196
+ *
197
+ * Consulted as a fallback when a reconnect's gap exceeds the in-memory replay
198
+ * buffer. Implementations should enforce per-user retention (size + TTL).
199
+ */
200
+ interface IOfflineQueueStorage {
201
+ /** Append an event to a user's offline queue. */
202
+ append(userId: string, event: OfflineQueuedEvent): Promise<void>;
203
+ /** Retrieve events with `id > sinceId`, up to `limit`. */
204
+ retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
205
+ /** Mark events delivered up to `upToId`. Implementations may purge or retain. */
206
+ acknowledge(userId: string, upToId: string): Promise<void>;
207
+ }
208
+
209
+ /**
210
+ * @fileoverview Optional presence-tracking contract ("who is online?").
211
+ * @layer contracts
212
+ */
213
+ /**
214
+ * Optional presence tracking — answers "who is online?" across instances. When it
215
+ * is not provided, presence-dependent features (e.g. the `usePresence` hook) are
216
+ * disabled.
217
+ */
218
+ interface IPresenceStorage {
219
+ setOnline(userId: string, connectionId: string, tenantId?: string): Promise<void>;
220
+ setOffline(userId: string, connectionId: string): Promise<void>;
221
+ isOnline(userId: string): Promise<boolean>;
222
+ listOnlineByTenant(tenantId: string): Promise<string[]>;
223
+ countOnline(): Promise<number>;
224
+ }
225
+
226
+ /**
227
+ * @fileoverview Module configuration contracts (sync + async dynamic module).
228
+ * @layer contracts
229
+ */
230
+
231
+ /** CORS configuration shared by the SSE and WebSocket transports. */
232
+ interface CorsConfig {
233
+ origin?: string | readonly string[] | boolean;
234
+ credentials?: boolean;
235
+ methods?: readonly string[];
236
+ }
237
+ /**
238
+ * SSE-transport-specific options.
239
+ *
240
+ * CORS for the SSE endpoint is intentionally not configured here: the endpoint is a
241
+ * standard HTTP GET, so cross-origin access is controlled at the NestJS application
242
+ * level (`app.enableCors(...)`). `CorsConfig` applies to the WebSocket transport.
243
+ */
244
+ interface SseOptions {
245
+ endpoint?: string;
246
+ heartbeatMs?: number;
247
+ replayBufferSize?: number;
248
+ maxConnectionsPerUser?: number;
249
+ emitConnectionEvent?: boolean;
250
+ }
251
+ /** WebSocket-transport-specific options. */
252
+ interface WebSocketOptions {
253
+ namespace?: string;
254
+ cors?: CorsConfig;
255
+ maxHttpBufferSize?: number;
256
+ pingIntervalMs?: number;
257
+ pingTimeoutMs?: number;
258
+ maxConnectionsPerUser?: number;
259
+ /**
260
+ * Emit a `connection:established` event to the client immediately after a
261
+ * successful WebSocket handshake. Defaults to `true`.
262
+ *
263
+ * Transport-neutral for WebSocket and independent of `sse.emitConnectionEvent`,
264
+ * so toggling the SSE flag never changes WebSocket behavior.
265
+ */
266
+ emitConnectionEvent?: boolean;
267
+ redisAdapter?: {
268
+ /**
269
+ * The ioredis client used by `@socket.io/redis-adapter`. Typed `unknown` so
270
+ * the library never imports `ioredis`; the consumer passes a concrete client
271
+ * and the WebSocket transport calls `.duplicate()` for the subscriber.
272
+ */
273
+ pubClient: unknown;
274
+ };
275
+ }
276
+ /** Periodic re-authentication policy for long-lived connections. */
277
+ interface ReauthenticationPolicy {
278
+ intervalSeconds?: number;
279
+ onFailure?: 'disconnect' | 'event';
280
+ cacheTtlMs?: number;
281
+ }
282
+ /** Synchronous module configuration. */
283
+ interface BymaxRealtimeModuleOptions {
284
+ transport: TransportMode;
285
+ service?: {
286
+ name: string;
287
+ version: string;
288
+ };
289
+ authenticator: IConnectionAuthenticator;
290
+ tenantResolver?: (auth: AuthenticationResult) => string | undefined;
291
+ hooks?: IConnectionLifecycleHooks;
292
+ pubsub?: IRealtimePubSub;
293
+ offlineQueue?: IOfflineQueueStorage;
294
+ presence?: IPresenceStorage;
295
+ sse?: SseOptions;
296
+ websocket?: WebSocketOptions;
297
+ reauthenticationPolicy?: ReauthenticationPolicy;
298
+ }
299
+ /**
300
+ * Synchronous configuration for `BymaxRealtimeWebSocketModule`, which serves
301
+ * `'websocket'` and `'both'`. An SSE-only application wants the root module.
302
+ */
303
+ type WebSocketRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
304
+ transport: 'websocket' | 'both';
305
+ };
306
+ /** A factory that builds module options (async dynamic-module pattern). */
307
+ interface BymaxRealtimeModuleOptionsFactory {
308
+ createRealtimeOptions(): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
309
+ }
310
+ /** Asynchronous module configuration — the standard NestJS dynamic-module pattern. */
311
+ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
312
+ /**
313
+ * The transport this registration wires. Required, not a hint: providers and
314
+ * controllers are fixed at decoration time, long before a factory runs, so the
315
+ * module cannot discover its own transport later. It MUST equal the
316
+ * `transport` the factory resolves; a mismatch fails fast at bootstrap.
317
+ */
318
+ transport: TransportMode;
319
+ useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
320
+ inject?: readonly (string | symbol | Type<unknown>)[];
321
+ useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
322
+ useClass?: Type<BymaxRealtimeModuleOptionsFactory>;
323
+ /**
324
+ * Additional providers to register alongside the module (e.g. the authenticator
325
+ * class when it is a NestJS-managed injectable).
326
+ */
327
+ extraProviders?: Provider[];
328
+ }
329
+ /** Asynchronous configuration for `BymaxRealtimeWebSocketModule`. */
330
+ type WebSocketRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
331
+ transport: 'websocket' | 'both';
332
+ };
333
+
334
+ /**
335
+ * Realtime module for Socket.IO, and for `'both'` where SSE and WebSocket are
336
+ * composed. Registered globally so a single configuration serves the whole
337
+ * application.
338
+ *
339
+ * It lives in its own entry point because it is the only part of the library
340
+ * that imports `@nestjs/websockets` and `@nestjs/platform-socket.io`. Importing
341
+ * it is what pulls the Socket.IO stack in — an application on SSE uses
342
+ * `BymaxRealtimeModule` from the package root and never installs it.
343
+ */
344
+ declare class BymaxRealtimeWebSocketModule {
345
+ private static readonly logger;
346
+ /**
347
+ * Configure the module synchronously.
348
+ *
349
+ * @throws when the options are invalid.
350
+ * @example
351
+ * ```ts
352
+ * BymaxRealtimeWebSocketModule.forRoot({
353
+ * transport: 'websocket',
354
+ * authenticator: new MyAuthenticator(),
355
+ * })
356
+ * ```
357
+ */
358
+ static forRoot(options: WebSocketRealtimeModuleOptions): DynamicModule;
359
+ /**
360
+ * Configure the module asynchronously so options — and the authenticator —
361
+ * can be resolved through DI.
362
+ *
363
+ * Controllers are registered at decoration time, so `'both'` binds the SSE
364
+ * controller to the default endpoint `/events`. A non-default endpoint needs
365
+ * `forRoot` with pre-resolved options.
366
+ *
367
+ * @throws when no factory pattern is given, more than one is, or the factory
368
+ * resolves a transport other than the one declared.
369
+ * @example
370
+ * ```ts
371
+ * BymaxRealtimeWebSocketModule.forRootAsync({
372
+ * transport: 'both',
373
+ * imports: [ConfigModule],
374
+ * inject: [ConfigService],
375
+ * useFactory: (cfg: ConfigService) => ({
376
+ * transport: 'both' as const,
377
+ * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
378
+ * }),
379
+ * })
380
+ * ```
381
+ */
382
+ static forRootAsync(asyncOptions: WebSocketRealtimeModuleAsyncOptions): DynamicModule;
383
+ }
384
+
385
+ /**
386
+ * @fileoverview Unified transport abstraction implemented by every transport.
387
+ * @layer contracts
388
+ */
389
+ /**
390
+ * Unified transport abstraction.
391
+ *
392
+ * The library ships concrete implementations (`SseTransport`, the WebSocket
393
+ * transport, and a composite that fans out to both). Consumers normally interact
394
+ * with `RealtimeService`, which delegates to the active transport; implementing a
395
+ * custom `ITransport` is an advanced use case (e.g. bridging an external bus).
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * class NoopTransport implements ITransport {
400
+ * readonly kind = 'sse' as const
401
+ * async emitToUser() {}
402
+ * async emitToTenant() {}
403
+ * async emitToRoom() {}
404
+ * async broadcast() {}
405
+ * async joinRoom() {}
406
+ * async leaveRoom() {}
407
+ * async disconnect() {}
408
+ * }
409
+ * ```
410
+ */
411
+ interface ITransport {
412
+ /** Transport identifier. A composite reports its dominant kind (`'sse'`). */
413
+ readonly kind: 'sse' | 'websocket';
414
+ /** Send to every connection of a single user. */
415
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
416
+ /** Send to every connection of every user in a tenant. */
417
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
418
+ /** Send to every connection in a logical room. */
419
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
420
+ /** Send to all connected clients. Use sparingly. */
421
+ broadcast(event: string, data: unknown): Promise<void>;
422
+ /** Join a connection to a room (idempotent). */
423
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
424
+ /** Leave a connection from a room (idempotent). */
425
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
426
+ /** Disconnect a specific connection (e.g. on auth revocation). */
427
+ disconnect(connectionId: string, reason?: string): Promise<void>;
428
+ /** Lifecycle hook — called on NestJS bootstrap. */
429
+ onModuleInit?(): Promise<void>;
430
+ /** Lifecycle hook — called on NestJS shutdown. */
431
+ onApplicationShutdown?(): Promise<void>;
432
+ }
433
+
434
+ /** Transport kind a connection belongs to. */
435
+ type ConnectionTransport = 'sse' | 'websocket';
436
+ /**
437
+ * Internal record kept per active connection.
438
+ *
439
+ * `subject` and `close$` are populated only for SSE connections (the per-connection
440
+ * RxJS stream and its server-initiated teardown signal). WebSocket connections set
441
+ * both to `null` and rely on the Socket.IO server's own emit/disconnect mechanism.
442
+ */
443
+ interface ConnectionRecord {
444
+ connectionId: string;
445
+ userId: string;
446
+ tenantId: string | undefined;
447
+ transport: ConnectionTransport;
448
+ ip: string;
449
+ userAgent: string | undefined;
450
+ connectedAt: Date;
451
+ /** Per-connection event stream (SSE only); `null` for WebSocket. */
452
+ subject: Subject<MessageEvent> | null;
453
+ /** Server-initiated teardown signal (SSE only); `null` for WebSocket. */
454
+ close$: Subject<void> | null;
455
+ /** Snapshot of the original authentication result — used by the re-auth policy. */
456
+ originalAuth: {
457
+ userId: string;
458
+ tenantId: string | undefined;
459
+ roles: readonly string[] | undefined;
460
+ };
461
+ }
462
+ /**
463
+ * Indexed registry of active connections.
464
+ *
465
+ * Maintains three maps — `byId` (connectionId → record), `byUserId` (userId →
466
+ * Set<connectionId>) and `byTenantId` (tenantId → Set<connectionId>) — kept
467
+ * consistent on every `register`/`unregister`. Operations are amortized O(1);
468
+ * mutation is single-threaded (the Node.js event loop), so no locking is needed.
469
+ */
470
+ declare class ConnectionRegistry {
471
+ private readonly byId;
472
+ private readonly byUserId;
473
+ private readonly byTenantId;
474
+ /** Register a connection and index it by user and tenant. */
475
+ register(record: ConnectionRecord): void;
476
+ /** Remove a connection from every index. Returns the removed record, if any. */
477
+ unregister(connectionId: string): ConnectionRecord | undefined;
478
+ /** Look up a single connection by id. */
479
+ get(connectionId: string): ConnectionRecord | undefined;
480
+ /** All connections of a user, optionally filtered by transport. */
481
+ byUser(userId: string, transport?: ConnectionTransport): ConnectionRecord[];
482
+ /** All connections of a tenant, optionally filtered by transport. */
483
+ byTenant(tenantId: string, transport?: ConnectionTransport): ConnectionRecord[];
484
+ /** All connections of a given transport. */
485
+ allByTransport(transport: ConnectionTransport): ConnectionRecord[];
486
+ /** Total number of active connections. */
487
+ count(): number;
488
+ /** Number of distinct users currently connected. */
489
+ countUsers(): number;
490
+ private resolve;
491
+ private addToSetMap;
492
+ private removeFromSetMap;
493
+ }
494
+
495
+ /**
496
+ * Indexed registry of room membership.
497
+ *
498
+ * Maintains two maps — `rooms` (roomId → Set<connectionId>) and `connectionRooms`
499
+ * (connectionId → Set<roomId>). The reverse index makes `leaveAll()` on disconnect
500
+ * O(rooms-per-connection) instead of O(total rooms).
501
+ */
502
+ declare class RoomRegistry {
503
+ private readonly rooms;
504
+ private readonly connectionRooms;
505
+ /** Join a connection to a room (idempotent). */
506
+ join(connectionId: string, roomId: string): void;
507
+ /** Remove a connection from a room (idempotent); prunes empty entries. */
508
+ leave(connectionId: string, roomId: string): void;
509
+ /** Snapshot of a room's members — safe to iterate while membership mutates. */
510
+ members(roomId: string): readonly string[];
511
+ /** Snapshot of the rooms a connection currently belongs to. */
512
+ roomsOf(connectionId: string): readonly string[];
513
+ /** Remove a connection from every room (called on disconnect). */
514
+ leaveAll(connectionId: string): void;
515
+ /** Total number of distinct rooms. */
516
+ countRooms(): number;
517
+ }
518
+
519
+ /**
520
+ * WebSocket transport implementing `ITransport` over a Socket.IO `Server`.
521
+ *
522
+ * Emit methods call `server.to(room).emit(event, data)`. Cross-instance fan-out
523
+ * is handled exclusively by `@socket.io/redis-adapter` (spec §11.4) — this class
524
+ * never calls `IRealtimePubSub.publish` for WS messages.
525
+ *
526
+ * The Socket.IO `Server` instance is injected lazily via `setServer` (called by
527
+ * `RealtimeGateway.afterInit`) because the server only exists after NestJS boots
528
+ * the gateway. All emit methods are safe no-ops while the server is unset.
529
+ */
530
+ declare class WebSocketTransport implements ITransport {
531
+ private readonly connections;
532
+ private readonly rooms;
533
+ private readonly auth;
534
+ private readonly hooks;
535
+ private readonly options;
536
+ readonly kind: "websocket";
537
+ private readonly logger;
538
+ /** Nullable until the gateway's afterInit wires the instance. */
539
+ private server;
540
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
541
+ /**
542
+ * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
543
+ *
544
+ * All emit methods silently no-op until this is called, so the transport is
545
+ * safe to construct before the HTTP server is ready.
546
+ *
547
+ * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
548
+ */
549
+ setServer(server: Server): void;
550
+ /**
551
+ * Resolve the map of locally-connected sockets, tolerating both server shapes.
552
+ *
553
+ * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
554
+ * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
555
+ * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
556
+ * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
557
+ * this indirection so they work under either shape.
558
+ */
559
+ private localSockets;
560
+ /**
561
+ * Expose the configured authenticator to the gateway.
562
+ *
563
+ * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
564
+ * `WebSocketTransport` → authenticator, rather than injecting the token
565
+ * directly in the gateway.
566
+ *
567
+ * @returns The consumer-provided `IConnectionAuthenticator` instance.
568
+ */
569
+ authenticator(): IConnectionAuthenticator;
570
+ /**
571
+ * Register a freshly-authenticated WebSocket connection.
572
+ *
573
+ * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
574
+ * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
575
+ * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
576
+ *
577
+ * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
578
+ * does not publish to `IRealtimePubSub`.
579
+ *
580
+ * @param socket - The authenticated Socket.IO socket instance.
581
+ * @param auth - The resolved authentication result containing userId, tenantId, and roles.
582
+ */
583
+ registerSocket(socket: Socket, auth: AuthenticationResult): Promise<void>;
584
+ /**
585
+ * Unregister a disconnected WebSocket connection.
586
+ *
587
+ * Removes the record from `ConnectionRegistry`, clears all room membership
588
+ * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
589
+ * computed `durationMs`.
590
+ *
591
+ * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
592
+ * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
593
+ */
594
+ unregisterSocket(connectionId: string, reason?: string): Promise<void>;
595
+ /**
596
+ * Send an event to every connection of a user (uses `user:{userId}` room).
597
+ *
598
+ * @param userId - Target user identifier.
599
+ * @param event - Event name to emit.
600
+ * @param data - Payload forwarded to all matching connections.
601
+ */
602
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
603
+ /**
604
+ * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
605
+ *
606
+ * @param tenantId - Target tenant identifier.
607
+ * @param event - Event name to emit.
608
+ * @param data - Payload forwarded to all matching connections.
609
+ */
610
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
611
+ /**
612
+ * Send an event to every connection in an arbitrary room.
613
+ *
614
+ * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
615
+ * @param event - Event name to emit.
616
+ * @param data - Payload forwarded to all connections in the room.
617
+ */
618
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
619
+ /**
620
+ * Broadcast an event to all connected clients.
621
+ *
622
+ * @param event - Event name to emit.
623
+ * @param data - Payload forwarded to every connected socket.
624
+ */
625
+ broadcast(event: string, data: unknown): Promise<void>;
626
+ /**
627
+ * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
628
+ *
629
+ * @param connectionId - The socket `id` of the connection to join.
630
+ * @param roomId - The room to join.
631
+ */
632
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
633
+ /**
634
+ * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
635
+ *
636
+ * @param connectionId - The socket `id` of the connection to remove.
637
+ * @param roomId - The room to leave.
638
+ */
639
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
640
+ /**
641
+ * Force-disconnect a specific connection — adapter-aware, so revocation works
642
+ * across nodes.
643
+ *
644
+ * A socket local to this node is closed directly as a fast path. Regardless,
645
+ * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
646
+ * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
647
+ * connection pinned to another instance is still force-closed. The local socket
648
+ * has already left the room by then, so the broadcast does not double-close it.
649
+ *
650
+ * @param connectionId - The socket `id` of the connection to disconnect.
651
+ * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
652
+ */
653
+ disconnect(connectionId: string, _reason?: string): Promise<void>;
654
+ /**
655
+ * Evict the user's oldest WebSocket connections (FIFO) when over
656
+ * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
657
+ * as the disconnect reason — never rejects the new connection with HTTP 429.
658
+ */
659
+ private evictBeyondLimit;
660
+ }
661
+
662
+ /**
663
+ * NestJS WebSocket gateway wiring the Socket.IO lifecycle to `WebSocketTransport`.
664
+ *
665
+ * Authentication flows exclusively through the consumer-provided
666
+ * `IConnectionAuthenticator` (auth inversion — spec §1.6). The gateway never
667
+ * imports a concrete auth library; it only shapes the `ConnectionAuthContext`
668
+ * from the Socket.IO handshake and delegates to the authenticator.
669
+ *
670
+ * Namespace, CORS, ping options, and the Redis adapter are applied by
671
+ * `RealtimeIoAdapter` (not here), because `@WebSocketGateway()` args are
672
+ * evaluated at class-decoration time — before the module options are resolved.
673
+ *
674
+ * CORS is intentionally disabled in the decorator (`origin: false`). The real
675
+ * policy is applied by `RealtimeIoAdapter.createIOServer` from the consumer's
676
+ * `websocket.cors` option. Leaving it open-by-default here would allow any
677
+ * origin to make credentialed connections before the adapter overrides the policy.
678
+ */
679
+ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
680
+ private readonly transport;
681
+ private readonly options;
682
+ private readonly logger;
683
+ server: Server;
684
+ constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
685
+ /** Wire the resolved Socket.IO server to the transport after gateway init. */
686
+ afterInit(server: Server): void;
687
+ /**
688
+ * Handle a new WebSocket connection.
689
+ *
690
+ * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
691
+ * three supported auth patterns (spec §8.1):
692
+ * - Cookie HttpOnly — extracted via `parseCookieHeader`.
693
+ * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
694
+ * - Bearer header — available in `headers.authorization` or via `auth.token`.
695
+ *
696
+ * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
697
+ * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
698
+ * context so the authenticator sees a single unified shape regardless of client.
699
+ *
700
+ * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
701
+ * undefined`); the single-value `ticket` parameter is collapsed to its first
702
+ * element so the authenticator receives a well-defined string.
703
+ *
704
+ * Fail-closed: any thrown error disconnects the socket immediately so it cannot
705
+ * linger in an unregistered state and receive broadcast events.
706
+ */
707
+ handleConnection(socket: Socket): Promise<void>;
708
+ /** Handle a WebSocket disconnection — unregister the connection. */
709
+ handleDisconnect(socket: Socket): Promise<void>;
710
+ /**
711
+ * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
712
+ *
713
+ * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
714
+ * single string, matching the shape expected by `ConnectionAuthContext.headers`.
715
+ */
716
+ private normalizeHeaders;
717
+ }
718
+
719
+ /**
720
+ * Custom NestJS `IoAdapter` that:
721
+ *
722
+ * 1. Applies `websocket.cors`, `pingIntervalMs`, `pingTimeoutMs`, and
723
+ * `maxHttpBufferSize` from `BymaxRealtimeModuleOptions`.
724
+ * 2. Lazily installs `@socket.io/redis-adapter` when
725
+ * `websocket.redisAdapter.pubClient` is provided, enabling transparent
726
+ * cross-instance WebSocket fan-out (spec §11.4).
727
+ *
728
+ * Register this adapter in `main.ts` **before** `app.listen()`:
729
+ *
730
+ * ```ts
731
+ * import { RealtimeIoAdapter } from '@bymax-one/nest-realtime'
732
+ *
733
+ * const app = await NestFactory.create(AppModule)
734
+ * app.useWebSocketAdapter(new RealtimeIoAdapter(app))
735
+ * await app.listen(3000)
736
+ * ```
737
+ *
738
+ * Sticky sessions are MANDATORY when the polling fallback is enabled in a
739
+ * horizontally scaled deployment. The adapter synchronizes messages across
740
+ * nodes but does NOT remove the load-balancer's session-affinity requirement
741
+ * (spec §11.5).
742
+ */
743
+ declare class RealtimeIoAdapter extends IoAdapter {
744
+ private readonly logger;
745
+ private readonly options;
746
+ constructor(app: INestApplicationContext);
747
+ /**
748
+ * Bind the gateway to `websocket.namespace` when configured.
749
+ *
750
+ * `@WebSocketGateway()` args are evaluated at class-decoration time — before
751
+ * the module options resolve — so the namespace cannot be declared there.
752
+ * Instead we build the root server via `super.create` (which routes through the
753
+ * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
754
+ * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
755
+ * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
756
+ * namespace leaves the root server untouched.
757
+ */
758
+ create(port: number, options?: ServerOptions & {
759
+ namespace?: string;
760
+ server?: unknown;
761
+ }): Server;
762
+ /**
763
+ * Create the Socket.IO server with merged WebSocket options.
764
+ *
765
+ * When `websocket.redisAdapter.pubClient` is set, installs the
766
+ * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
767
+ * dep — its absence does not crash the lib).
768
+ */
769
+ createIOServer(port: number, opts?: ServerOptions): unknown;
770
+ /**
771
+ * Lazily load and install `@socket.io/redis-adapter`.
772
+ *
773
+ * Uses a dynamic `require` so the package stays optional — absent peers do
774
+ * not crash the lib. A load or install failure is logged and tolerated;
775
+ * the lib degrades gracefully to single-instance mode.
776
+ */
777
+ private installRedisAdapter;
778
+ }
779
+
780
+ /**
781
+ * Generates monotonically increasing event ids of the form
782
+ * `{epochMillis}-{counter}`, where the counter resets every millisecond.
783
+ *
784
+ * Guarantees:
785
+ * - Lexicographically sortable (the counter is zero-padded to a fixed width), so
786
+ * `Last-Event-ID` replay can string-compare ids.
787
+ * - Monotonic within a single instance even when called repeatedly at the same
788
+ * epoch millisecond.
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * gen.next() // → '1717000000000-000001'
793
+ * gen.next() // → '1717000000000-000002'
794
+ * ```
795
+ */
796
+ declare class EventIdGenerator {
797
+ private lastMs;
798
+ private counter;
799
+ /** Produce the next monotonic event id. */
800
+ next(): string;
801
+ }
802
+
803
+ /**
804
+ * Per-user ring buffer of recent events for `Last-Event-ID` replay.
805
+ *
806
+ * In-memory by design — it survives only as long as the process. Per-user buffers
807
+ * prevent one user from poisoning another's replay state. For durable replay
808
+ * (instance restart, or a gap larger than the buffer), a consumer can plug
809
+ * `IOfflineQueueStorage` as a fallback.
810
+ *
811
+ * @example
812
+ * ```ts
813
+ * // On reconnect with `Last-Event-ID: <id>`, replay what was missed:
814
+ * const missed = replayBuffer.since(userId, lastEventId)
815
+ * ```
816
+ */
817
+ declare class EventReplayBuffer {
818
+ private readonly opts;
819
+ private readonly buffers;
820
+ constructor(opts: BymaxRealtimeModuleOptions);
821
+ /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
822
+ append(userId: string, event: MessageEvent): void;
823
+ /**
824
+ * Return the events emitted after `lastEventId`.
825
+ *
826
+ * Returns an empty array when the user has no buffer, or when `lastEventId` is
827
+ * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
828
+ */
829
+ since(userId: string, lastEventId: string): MessageEvent[];
830
+ /** Number of events currently buffered for a user (diagnostics). */
831
+ size(userId: string): number;
832
+ }
833
+
834
+ /** Minimal response surface the heartbeat needs — a writable text stream. */
835
+ interface HeartbeatWritable {
836
+ write(chunk: string): unknown;
837
+ }
838
+ /**
839
+ * Emits the SSE keepalive on an interval, per connection.
840
+ *
841
+ * The keepalive is a raw `: keepalive\n\n` comment written DIRECTLY to the response
842
+ * stream — not a `MessageEvent`, not a named event, and outside the `Last-Event-ID`
843
+ * id-space — so it never corrupts replay. Comments keep proxies and load balancers
844
+ * from idling out the connection. Timers are tracked per connection and cleared on
845
+ * `stop`.
846
+ *
847
+ * The configured interval must be within `[5_000, 90_000]` ms; values outside this
848
+ * range throw a `REALTIME_INVALID_OPTIONS` error.
849
+ *
850
+ * See `docs/proxies-cheat-sheet.md` for nginx, Cloudflare, and AWS ALB configuration.
851
+ */
852
+ declare class HeartbeatService {
853
+ private readonly timers;
854
+ /**
855
+ * Start writing keepalives for a connection every `intervalMs`.
856
+ *
857
+ * @param connectionId - Unique connection identifier used to track the timer.
858
+ * @param res - The writable response stream (or any object with a `write` method).
859
+ * @param intervalMs - Keepalive interval in milliseconds; must be within
860
+ * `[5_000, 90_000]`.
861
+ * @throws {Error} When `intervalMs` is outside the valid range.
862
+ */
863
+ start(connectionId: string, res: HeartbeatWritable, intervalMs: number): void;
864
+ /** Stop and clear the keepalive timer for a connection (idempotent). */
865
+ stop(connectionId: string): void;
866
+ /** Stop every keepalive timer (used on shutdown). */
867
+ stopAll(): void;
868
+ }
869
+
870
+ /** Parameters required to register a freshly authenticated SSE connection. */
871
+ interface RegisterSseConnectionParams {
872
+ connectionId: string;
873
+ auth: AuthenticationResult;
874
+ subject: Subject<MessageEvent>;
875
+ close$: Subject<void>;
876
+ ip: string;
877
+ userAgent: string | undefined;
878
+ }
879
+ /**
880
+ * SSE transport implementation.
881
+ *
882
+ * Each public `emitTo*`/`broadcast` performs local delivery via the matching
883
+ * `*Local` method and then publishes exactly once to `IRealtimePubSub`. Remote
884
+ * messages received from the bus are dispatched by `RealtimePubSubSubscriber`
885
+ * (not this class) to the `*Local` methods only (never re-published), and
886
+ * self-originated messages are filtered there — so a single instance never
887
+ * double-delivers and multiple instances never ping-pong.
888
+ *
889
+ * Teardown of an SSE stream is driven by the per-connection `close$` subject:
890
+ * `disconnectLocal` completes it (which ends the `@Sse` Observable via
891
+ * `takeUntil`) before unregistering. See `docs/technical_specification.md` §6.1.
892
+ */
893
+ declare class SseTransport implements ITransport {
894
+ private readonly connections;
895
+ private readonly rooms;
896
+ private readonly replayBuffer;
897
+ private readonly idGen;
898
+ private readonly heartbeat;
899
+ private readonly auth;
900
+ private readonly pubsub;
901
+ private readonly hooks;
902
+ private readonly options;
903
+ private readonly instanceId;
904
+ private readonly offlineQueue?;
905
+ readonly kind: "sse";
906
+ private readonly logger;
907
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
908
+ /** Tear down every SSE connection and stop heartbeat on process shutdown. */
909
+ onApplicationShutdown(): Promise<void>;
910
+ /** The resolved heartbeat interval for this transport. */
911
+ get heartbeatMs(): number;
912
+ /** Whether the `connection:established` event should be emitted on connect. */
913
+ get emitConnectionEvent(): boolean;
914
+ /** Authenticate a connection through the consumer-provided authenticator. */
915
+ authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
916
+ /**
917
+ * Register an authenticated SSE connection and auto-join its user/tenant rooms.
918
+ *
919
+ * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
920
+ * lifecycle hook is fired by the subscription handler after this returns, so that the
921
+ * handler can carry a consistent connection record reference.
922
+ */
923
+ registerConnection(params: RegisterSseConnectionParams): Promise<void>;
924
+ /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
925
+ unregisterConnection(connectionId: string, reason?: string): Promise<void>;
926
+ /** Replay the events a user missed after `lastEventId`. */
927
+ getReplayEvents(userId: string, lastEventId: string): MessageEvent[];
928
+ /**
929
+ * All SSE connections for a user — public accessor so external callers can
930
+ * inspect or iterate without reaching into a private registry field.
931
+ *
932
+ * @param userId - The user whose active connections are returned.
933
+ * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
934
+ */
935
+ connectionsForUser(userId: string): ConnectionRecord[];
936
+ /**
937
+ * Look up a single connection by id.
938
+ *
939
+ * @param connectionId - The unique connection identifier.
940
+ * @returns The `ConnectionRecord`, or `undefined` when not found.
941
+ */
942
+ getConnection(connectionId: string): ConnectionRecord | undefined;
943
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
944
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
945
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
946
+ broadcast(event: string, data: unknown): Promise<void>;
947
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
948
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
949
+ /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
950
+ disconnect(connectionId: string, reason?: string): Promise<void>;
951
+ /**
952
+ * Deliver an event to a user's local SSE connections and update the replay buffer.
953
+ *
954
+ * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
955
+ * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
956
+ */
957
+ emitToUserLocal(userId: string, event: string, data: unknown, id: string): void;
958
+ /**
959
+ * Deliver an event to all local SSE connections for a tenant.
960
+ *
961
+ * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
962
+ * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
963
+ * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
964
+ * buffer or offline queue — only emitToUser populates per-user replay/offline state.
965
+ */
966
+ emitToTenantLocal(tenantId: string, event: string, data: unknown, id: string): void;
967
+ /**
968
+ * Deliver an event to all local SSE connections that joined the given room.
969
+ *
970
+ * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
971
+ * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
972
+ * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
973
+ * buffer or offline queue — only emitToUser populates per-user replay/offline state.
974
+ */
975
+ emitToRoomLocal(roomId: string, event: string, data: unknown, id: string): void;
976
+ /**
977
+ * Deliver an event to all local SSE connections.
978
+ *
979
+ * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
980
+ * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
981
+ * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
982
+ * buffer or offline queue — only emitToUser populates per-user replay/offline state.
983
+ */
984
+ broadcastLocal(event: string, data: unknown, id: string): void;
985
+ /**
986
+ * Tear down a locally-owned SSE stream, then clean up (no re-publish).
987
+ *
988
+ * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
989
+ * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
990
+ */
991
+ disconnectLocal(connectionId: string, reason?: string): Promise<void>;
992
+ private buildMessage;
993
+ /** Deliver to one connection, isolating failures so others still receive the event. */
994
+ private deliver;
995
+ /** Publish once to the bus; pub/sub failures never affect the live emit path. */
996
+ private publish;
997
+ /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
998
+ private evictBeyondLimit;
999
+ }
1000
+
1001
+ /**
1002
+ * Fan-out transport activated when `transport: 'both'`.
1003
+ *
1004
+ * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
1005
+ * parallel via `Promise.allSettled` so a failure in one never aborts the other.
1006
+ * Failures are logged as warnings without rethrowing.
1007
+ *
1008
+ * `joinRoom`, `leaveRoom`, and `disconnect` attempt both transports tolerantly:
1009
+ * only the transport that owns the connection will succeed; the other's rejection
1010
+ * is swallowed. There is no double-delivery because each connection lives on
1011
+ * exactly one transport.
1012
+ *
1013
+ * `kind` reports `'sse'` (the dominant transport); `ITransport.kind` is
1014
+ * `'sse' | 'websocket'` — `'both'` is a module-level `TransportMode`, not a
1015
+ * valid per-transport kind (spec §6.3).
1016
+ */
1017
+ declare class CompositeTransport implements ITransport {
1018
+ private readonly sse;
1019
+ private readonly ws;
1020
+ readonly kind: "sse";
1021
+ private readonly logger;
1022
+ constructor(sse: SseTransport, ws: WebSocketTransport);
1023
+ /**
1024
+ * Emit to all connections of a user across both transports.
1025
+ *
1026
+ * @param userId - Target user identifier.
1027
+ * @param event - Event name to emit.
1028
+ * @param data - Payload forwarded to all matching connections.
1029
+ */
1030
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
1031
+ /**
1032
+ * Emit to all connections within a tenant across both transports.
1033
+ *
1034
+ * @param tenantId - Target tenant identifier.
1035
+ * @param event - Event name to emit.
1036
+ * @param data - Payload forwarded to all matching connections.
1037
+ */
1038
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
1039
+ /**
1040
+ * Emit to all connections in a room across both transports.
1041
+ *
1042
+ * @param roomId - The fully-qualified room identifier.
1043
+ * @param event - Event name to emit.
1044
+ * @param data - Payload forwarded to all connections in the room.
1045
+ */
1046
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
1047
+ /**
1048
+ * Broadcast to all connected clients across both transports.
1049
+ *
1050
+ * @param event - Event name to emit.
1051
+ * @param data - Payload forwarded to every connected client.
1052
+ */
1053
+ broadcast(event: string, data: unknown): Promise<void>;
1054
+ /**
1055
+ * Join a connection to a room.
1056
+ *
1057
+ * Both transports are attempted; only the one that owns the connection
1058
+ * succeeds. The other's failure is expected and swallowed.
1059
+ */
1060
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
1061
+ /**
1062
+ * Remove a connection from a room.
1063
+ *
1064
+ * Both transports are attempted tolerantly — one will succeed, the other
1065
+ * may fail silently.
1066
+ */
1067
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
1068
+ /**
1069
+ * Disconnect a specific connection.
1070
+ *
1071
+ * Both transports are attempted; the one owning the connection disconnects it.
1072
+ */
1073
+ disconnect(connectionId: string, reason?: string): Promise<void>;
1074
+ /**
1075
+ * Run two transport tasks in parallel via `Promise.allSettled`.
1076
+ *
1077
+ * A rejection in either task is logged as a warning and does not propagate,
1078
+ * ensuring one failing transport never blocks delivery on the other.
1079
+ */
1080
+ private fanOut;
1081
+ }
1082
+
1083
+ export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, WebSocketTransport };