@bymax-one/nest-realtime 1.0.1 → 1.0.3

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,402 @@
1
+ import { DynamicModule, INestApplicationContext } from '@nestjs/common';
2
+ import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, IConnectionAuthenticator, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, AuthenticationResult, SseTransport } from '@bymax-one/nest-realtime/internal';
3
+ export { WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions } from '@bymax-one/nest-realtime/internal';
4
+ import { Server, Socket, ServerOptions } from 'socket.io';
5
+ import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
6
+ import { IoAdapter } from '@nestjs/platform-socket.io';
7
+
8
+ /**
9
+ * Realtime module for Socket.IO, and for `'both'` where SSE and WebSocket are
10
+ * composed. Registered globally so a single configuration serves the whole
11
+ * application.
12
+ *
13
+ * It lives in its own entry point because it is the only part of the library
14
+ * that imports `@nestjs/websockets` and `@nestjs/platform-socket.io`. Importing
15
+ * it is what pulls the Socket.IO stack in — an application on SSE uses
16
+ * `BymaxRealtimeModule` from the package root and never installs it.
17
+ */
18
+ declare class BymaxRealtimeWebSocketModule {
19
+ private static readonly logger;
20
+ /**
21
+ * Configure the module synchronously.
22
+ *
23
+ * @throws when the options are invalid.
24
+ * @example
25
+ * ```ts
26
+ * BymaxRealtimeWebSocketModule.forRoot({
27
+ * transport: 'websocket',
28
+ * authenticator: new MyAuthenticator(),
29
+ * })
30
+ * ```
31
+ */
32
+ static forRoot(options: WebSocketRealtimeModuleOptions): DynamicModule;
33
+ /**
34
+ * Configure the module asynchronously so options — and the authenticator —
35
+ * can be resolved through DI.
36
+ *
37
+ * Controllers are registered at decoration time, so `'both'` binds the SSE
38
+ * controller to the default endpoint `/events`. A non-default endpoint needs
39
+ * `forRoot` with pre-resolved options.
40
+ *
41
+ * @throws when no factory pattern is given, more than one is, or the factory
42
+ * resolves a transport other than the one declared.
43
+ * @example
44
+ * ```ts
45
+ * BymaxRealtimeWebSocketModule.forRootAsync({
46
+ * transport: 'both',
47
+ * imports: [ConfigModule],
48
+ * inject: [ConfigService],
49
+ * useFactory: (cfg: ConfigService) => ({
50
+ * transport: 'both' as const,
51
+ * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
52
+ * }),
53
+ * })
54
+ * ```
55
+ */
56
+ static forRootAsync(asyncOptions: WebSocketRealtimeModuleAsyncOptions): DynamicModule;
57
+ }
58
+
59
+ /**
60
+ * WebSocket transport implementing `ITransport` over a Socket.IO `Server`.
61
+ *
62
+ * Emit methods call `server.to(room).emit(event, data)`. Cross-instance fan-out
63
+ * is handled exclusively by `@socket.io/redis-adapter` (spec §11.4) — this class
64
+ * never calls `IRealtimePubSub.publish` for WS messages.
65
+ *
66
+ * The Socket.IO `Server` instance is injected lazily via `setServer` (called by
67
+ * `RealtimeGateway.afterInit`) because the server only exists after NestJS boots
68
+ * the gateway. All emit methods are safe no-ops while the server is unset.
69
+ */
70
+ declare class WebSocketTransport implements ITransport {
71
+ private readonly connections;
72
+ private readonly rooms;
73
+ private readonly auth;
74
+ private readonly hooks;
75
+ private readonly options;
76
+ readonly kind: "websocket";
77
+ private readonly logger;
78
+ /** Nullable until the gateway's afterInit wires the instance. */
79
+ private server;
80
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
81
+ /**
82
+ * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
83
+ *
84
+ * All emit methods silently no-op until this is called, so the transport is
85
+ * safe to construct before the HTTP server is ready.
86
+ *
87
+ * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
88
+ */
89
+ setServer(server: Server): void;
90
+ /**
91
+ * Resolve the map of locally-connected sockets, tolerating both server shapes.
92
+ *
93
+ * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
94
+ * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
95
+ * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
96
+ * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
97
+ * this indirection so they work under either shape.
98
+ */
99
+ private localSockets;
100
+ /**
101
+ * Expose the configured authenticator to the gateway.
102
+ *
103
+ * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
104
+ * `WebSocketTransport` → authenticator, rather than injecting the token
105
+ * directly in the gateway.
106
+ *
107
+ * @returns The consumer-provided `IConnectionAuthenticator` instance.
108
+ */
109
+ authenticator(): IConnectionAuthenticator;
110
+ /**
111
+ * Register a freshly-authenticated WebSocket connection.
112
+ *
113
+ * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
114
+ * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
115
+ * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
116
+ *
117
+ * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
118
+ * does not publish to `IRealtimePubSub`.
119
+ *
120
+ * @param socket - The authenticated Socket.IO socket instance.
121
+ * @param auth - The resolved authentication result containing userId, tenantId, and roles.
122
+ */
123
+ registerSocket(socket: Socket, auth: AuthenticationResult): Promise<void>;
124
+ /**
125
+ * Unregister a disconnected WebSocket connection.
126
+ *
127
+ * Removes the record from `ConnectionRegistry`, clears all room membership
128
+ * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
129
+ * computed `durationMs`.
130
+ *
131
+ * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
132
+ * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
133
+ */
134
+ unregisterSocket(connectionId: string, reason?: string): Promise<void>;
135
+ /**
136
+ * Send an event to every connection of a user (uses `user:{userId}` room).
137
+ *
138
+ * @param userId - Target user identifier.
139
+ * @param event - Event name to emit.
140
+ * @param data - Payload forwarded to all matching connections.
141
+ */
142
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
143
+ /**
144
+ * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
145
+ *
146
+ * @param tenantId - Target tenant identifier.
147
+ * @param event - Event name to emit.
148
+ * @param data - Payload forwarded to all matching connections.
149
+ */
150
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
151
+ /**
152
+ * Send an event to every connection in an arbitrary room.
153
+ *
154
+ * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
155
+ * @param event - Event name to emit.
156
+ * @param data - Payload forwarded to all connections in the room.
157
+ */
158
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
159
+ /**
160
+ * Broadcast an event to all connected clients.
161
+ *
162
+ * @param event - Event name to emit.
163
+ * @param data - Payload forwarded to every connected socket.
164
+ */
165
+ broadcast(event: string, data: unknown): Promise<void>;
166
+ /**
167
+ * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
168
+ *
169
+ * @param connectionId - The socket `id` of the connection to join.
170
+ * @param roomId - The room to join.
171
+ */
172
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
173
+ /**
174
+ * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
175
+ *
176
+ * @param connectionId - The socket `id` of the connection to remove.
177
+ * @param roomId - The room to leave.
178
+ */
179
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
180
+ /**
181
+ * Force-disconnect a specific connection — adapter-aware, so revocation works
182
+ * across nodes.
183
+ *
184
+ * A socket local to this node is closed directly as a fast path. Regardless,
185
+ * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
186
+ * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
187
+ * connection pinned to another instance is still force-closed. The local socket
188
+ * has already left the room by then, so the broadcast does not double-close it.
189
+ *
190
+ * @param connectionId - The socket `id` of the connection to disconnect.
191
+ * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
192
+ */
193
+ disconnect(connectionId: string, _reason?: string): Promise<void>;
194
+ /**
195
+ * Evict the user's oldest WebSocket connections (FIFO) when over
196
+ * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
197
+ * as the disconnect reason — never rejects the new connection with HTTP 429.
198
+ */
199
+ private evictBeyondLimit;
200
+ }
201
+
202
+ /**
203
+ * NestJS WebSocket gateway wiring the Socket.IO lifecycle to `WebSocketTransport`.
204
+ *
205
+ * Authentication flows exclusively through the consumer-provided
206
+ * `IConnectionAuthenticator` (auth inversion — spec §1.6). The gateway never
207
+ * imports a concrete auth library; it only shapes the `ConnectionAuthContext`
208
+ * from the Socket.IO handshake and delegates to the authenticator.
209
+ *
210
+ * Namespace, CORS, ping options, and the Redis adapter are applied by
211
+ * `RealtimeIoAdapter` (not here), because `@WebSocketGateway()` args are
212
+ * evaluated at class-decoration time — before the module options are resolved.
213
+ *
214
+ * CORS is intentionally disabled in the decorator (`origin: false`). The real
215
+ * policy is applied by `RealtimeIoAdapter.createIOServer` from the consumer's
216
+ * `websocket.cors` option. Leaving it open-by-default here would allow any
217
+ * origin to make credentialed connections before the adapter overrides the policy.
218
+ */
219
+ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
220
+ private readonly transport;
221
+ private readonly options;
222
+ private readonly logger;
223
+ server: Server;
224
+ constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
225
+ /** Wire the resolved Socket.IO server to the transport after gateway init. */
226
+ afterInit(server: Server): void;
227
+ /**
228
+ * Handle a new WebSocket connection.
229
+ *
230
+ * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
231
+ * three supported auth patterns (spec §8.1):
232
+ * - Cookie HttpOnly — extracted via `parseCookieHeader`.
233
+ * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
234
+ * - Bearer header — available in `headers.authorization` or via `auth.token`.
235
+ *
236
+ * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
237
+ * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
238
+ * context so the authenticator sees a single unified shape regardless of client.
239
+ *
240
+ * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
241
+ * undefined`); the single-value `ticket` parameter is collapsed to its first
242
+ * element so the authenticator receives a well-defined string.
243
+ *
244
+ * Fail-closed: any thrown error disconnects the socket immediately so it cannot
245
+ * linger in an unregistered state and receive broadcast events.
246
+ */
247
+ handleConnection(socket: Socket): Promise<void>;
248
+ /** Handle a WebSocket disconnection — unregister the connection. */
249
+ handleDisconnect(socket: Socket): Promise<void>;
250
+ /**
251
+ * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
252
+ *
253
+ * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
254
+ * single string, matching the shape expected by `ConnectionAuthContext.headers`.
255
+ */
256
+ private normalizeHeaders;
257
+ }
258
+
259
+ /**
260
+ * Custom NestJS `IoAdapter` that:
261
+ *
262
+ * 1. Applies `websocket.cors`, `pingIntervalMs`, `pingTimeoutMs`, and
263
+ * `maxHttpBufferSize` from `BymaxRealtimeModuleOptions`.
264
+ * 2. Lazily installs `@socket.io/redis-adapter` when
265
+ * `websocket.redisAdapter.pubClient` is provided, enabling transparent
266
+ * cross-instance WebSocket fan-out (spec §11.4).
267
+ *
268
+ * Register this adapter in `main.ts` **before** `app.listen()`:
269
+ *
270
+ * ```ts
271
+ * import { RealtimeIoAdapter } from '@bymax-one/nest-realtime'
272
+ *
273
+ * const app = await NestFactory.create(AppModule)
274
+ * app.useWebSocketAdapter(new RealtimeIoAdapter(app))
275
+ * await app.listen(3000)
276
+ * ```
277
+ *
278
+ * Sticky sessions are MANDATORY when the polling fallback is enabled in a
279
+ * horizontally scaled deployment. The adapter synchronizes messages across
280
+ * nodes but does NOT remove the load-balancer's session-affinity requirement
281
+ * (spec §11.5).
282
+ */
283
+ declare class RealtimeIoAdapter extends IoAdapter {
284
+ private readonly logger;
285
+ private readonly options;
286
+ constructor(app: INestApplicationContext);
287
+ /**
288
+ * Bind the gateway to `websocket.namespace` when configured.
289
+ *
290
+ * `@WebSocketGateway()` args are evaluated at class-decoration time — before
291
+ * the module options resolve — so the namespace cannot be declared there.
292
+ * Instead we build the root server via `super.create` (which routes through the
293
+ * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
294
+ * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
295
+ * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
296
+ * namespace leaves the root server untouched.
297
+ */
298
+ create(port: number, options?: ServerOptions & {
299
+ namespace?: string;
300
+ server?: unknown;
301
+ }): Server;
302
+ /**
303
+ * Create the Socket.IO server with merged WebSocket options.
304
+ *
305
+ * When `websocket.redisAdapter.pubClient` is set, installs the
306
+ * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
307
+ * dep — its absence does not crash the lib).
308
+ */
309
+ createIOServer(port: number, opts?: ServerOptions): unknown;
310
+ /**
311
+ * Lazily load and install `@socket.io/redis-adapter`.
312
+ *
313
+ * Uses a dynamic `require` so the package stays optional — absent peers do
314
+ * not crash the lib. A load or install failure is logged and tolerated;
315
+ * the lib degrades gracefully to single-instance mode.
316
+ */
317
+ private installRedisAdapter;
318
+ }
319
+
320
+ /**
321
+ * Fan-out transport activated when `transport: 'both'`.
322
+ *
323
+ * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
324
+ * parallel via `Promise.allSettled` so a failure in one never aborts the other.
325
+ * Failures are logged as warnings without rethrowing.
326
+ *
327
+ * `joinRoom`, `leaveRoom`, and `disconnect` attempt both transports tolerantly:
328
+ * only the transport that owns the connection will succeed; the other's rejection
329
+ * is swallowed. There is no double-delivery because each connection lives on
330
+ * exactly one transport.
331
+ *
332
+ * `kind` reports `'sse'` (the dominant transport); `ITransport.kind` is
333
+ * `'sse' | 'websocket'` — `'both'` is a module-level `TransportMode`, not a
334
+ * valid per-transport kind (spec §6.3).
335
+ */
336
+ declare class CompositeTransport implements ITransport {
337
+ private readonly sse;
338
+ private readonly ws;
339
+ readonly kind: "sse";
340
+ private readonly logger;
341
+ constructor(sse: SseTransport, ws: WebSocketTransport);
342
+ /**
343
+ * Emit to all connections of a user across both transports.
344
+ *
345
+ * @param userId - Target user identifier.
346
+ * @param event - Event name to emit.
347
+ * @param data - Payload forwarded to all matching connections.
348
+ */
349
+ emitToUser(userId: string, event: string, data: unknown): Promise<void>;
350
+ /**
351
+ * Emit to all connections within a tenant across both transports.
352
+ *
353
+ * @param tenantId - Target tenant identifier.
354
+ * @param event - Event name to emit.
355
+ * @param data - Payload forwarded to all matching connections.
356
+ */
357
+ emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
358
+ /**
359
+ * Emit to all connections in a room across both transports.
360
+ *
361
+ * @param roomId - The fully-qualified room identifier.
362
+ * @param event - Event name to emit.
363
+ * @param data - Payload forwarded to all connections in the room.
364
+ */
365
+ emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
366
+ /**
367
+ * Broadcast to all connected clients across both transports.
368
+ *
369
+ * @param event - Event name to emit.
370
+ * @param data - Payload forwarded to every connected client.
371
+ */
372
+ broadcast(event: string, data: unknown): Promise<void>;
373
+ /**
374
+ * Join a connection to a room.
375
+ *
376
+ * Both transports are attempted; only the one that owns the connection
377
+ * succeeds. The other's failure is expected and swallowed.
378
+ */
379
+ joinRoom(connectionId: string, roomId: string): Promise<void>;
380
+ /**
381
+ * Remove a connection from a room.
382
+ *
383
+ * Both transports are attempted tolerantly — one will succeed, the other
384
+ * may fail silently.
385
+ */
386
+ leaveRoom(connectionId: string, roomId: string): Promise<void>;
387
+ /**
388
+ * Disconnect a specific connection.
389
+ *
390
+ * Both transports are attempted; the one owning the connection disconnects it.
391
+ */
392
+ disconnect(connectionId: string, reason?: string): Promise<void>;
393
+ /**
394
+ * Run two transport tasks in parallel via `Promise.allSettled`.
395
+ *
396
+ * A rejection in either task is logged as a warning and does not propagate,
397
+ * ensuring one failing transport never blocks delivery on the other.
398
+ */
399
+ private fanOut;
400
+ }
401
+
402
+ export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };