@bymax-one/nest-realtime 1.0.2 → 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.
@@ -1,846 +1 @@
1
- import { ModuleMetadata, Type, Provider, DynamicModule, MessageEvent } from '@nestjs/common';
2
- import { Subject } from 'rxjs';
3
- import { Redis } from 'ioredis';
4
-
5
- /**
6
- * @fileoverview Config-level transport mode selection.
7
- * @layer shared
8
- */
9
- /**
10
- * Transport mode chosen by the consumer at module configuration time.
11
- *
12
- * - `sse` — Server-Sent Events only. HTTP-based, server → client push.
13
- * - `websocket` — Socket.IO only. Full duplex.
14
- * - `both` — Compose SSE and WebSocket. Useful during migrations or when
15
- * different product surfaces need different transports.
16
- *
17
- * Distinct from `ITransport.kind` (`'sse' | 'websocket'`), which identifies a
18
- * single concrete transport implementation. See
19
- * `docs/technical_specification.md` §1.3 for selection criteria.
20
- *
21
- * @example
22
- * ```ts
23
- * const mode: TransportMode = 'sse'
24
- * ```
25
- */
26
- type TransportMode = 'sse' | 'websocket' | 'both';
27
-
28
- /**
29
- * @fileoverview The single auth contract the library owns (auth inversion).
30
- * @layer contracts
31
- */
32
- /**
33
- * Transport-agnostic context passed to `IConnectionAuthenticator.authenticate`.
34
- *
35
- * Built from the HTTP request (SSE) or the Socket.IO handshake (WebSocket).
36
- * Cookies are parsed; header names are normalized to lowercase.
37
- */
38
- interface ConnectionAuthContext {
39
- /** Cookies parsed from the request/handshake headers. */
40
- readonly cookies: Record<string, string>;
41
- /**
42
- * Selected headers (lowercase keys). `authorization` is always stripped for SSE:
43
- * an `EventSource` cannot send custom headers, so it is never a valid SSE auth
44
- * channel (use a cookie or the ticket pattern). It is available for WebSocket.
45
- */
46
- readonly headers: Record<string, string | undefined>;
47
- /**
48
- * Query string parameters — useful for the ticket pattern.
49
- *
50
- * Values follow the Node `ParsedUrlQuery` shape: a repeated key (`?a=1&a=2`)
51
- * arrives as a `string[]`. Authenticators that expect a single value should
52
- * normalize accordingly; the WebSocket gateway already collapses the `ticket`
53
- * parameter to a single string before delegating.
54
- */
55
- readonly query: Record<string, string | string[] | undefined>;
56
- /**
57
- * Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
58
- * spoofable unless set by a trusted proxy; do not use it for security decisions
59
- * without validating the proxy chain.
60
- */
61
- readonly ip: string;
62
- /** Raw User-Agent. */
63
- readonly userAgent: string | undefined;
64
- /** Transport kind initiating the connection. */
65
- readonly transport: 'sse' | 'websocket';
66
- }
67
- /**
68
- * Authenticated traits returned by a successful `authenticate()` call. Consumers
69
- * may carry extra fields through the `metadata` bag.
70
- */
71
- interface AuthenticationResult {
72
- readonly userId: string;
73
- readonly tenantId?: string;
74
- readonly roles?: readonly string[];
75
- /** Free-form extras for downstream code (e.g. feature flags, plan tier). */
76
- readonly metadata?: Record<string, unknown>;
77
- }
78
- /**
79
- * Connection authenticator contract — the only auth surface the library owns.
80
- *
81
- * Implementations bridge the library to whatever auth strategy the consumer uses
82
- * (cookie JWT, the ticket pattern, a bearer header in WS, etc.). The library
83
- * NEVER imports a concrete auth library; see `docs/technical_specification.md`
84
- * §1.6 ("auth inversion").
85
- *
86
- * @example
87
- * ```ts
88
- * class CookieAuthenticator implements IConnectionAuthenticator {
89
- * async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
90
- * const token = ctx.cookies['access_token']
91
- * if (!token) return null
92
- * const claims = await verify(token)
93
- * return { userId: claims.sub, tenantId: claims.tid, roles: claims.roles }
94
- * }
95
- * }
96
- * ```
97
- */
98
- interface IConnectionAuthenticator {
99
- /**
100
- * Authenticate a new connection request.
101
- *
102
- * @returns the authenticated result, or `null` to reject the connection (the
103
- * transport replies 401 / disconnects accordingly).
104
- */
105
- authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
106
- /**
107
- * Optionally re-validate during long sessions. Called periodically based on
108
- * `reauthenticationPolicy.intervalSeconds`.
109
- *
110
- * @returns `true` to keep the connection alive, `false` to disconnect.
111
- */
112
- revalidate?(connectionId: string, originalAuth: AuthenticationResult): Promise<boolean>;
113
- }
114
-
115
- /**
116
- * @fileoverview Optional connection lifecycle hooks the consumer can provide.
117
- * @layer contracts
118
- */
119
- /** Metadata describing a connection at a lifecycle transition. */
120
- interface ConnectionEventMeta {
121
- readonly connectionId: string;
122
- readonly userId: string;
123
- readonly tenantId: string | undefined;
124
- readonly transport: 'sse' | 'websocket';
125
- readonly ip: string;
126
- readonly userAgent: string | undefined;
127
- readonly connectedAt: Date;
128
- }
129
- /**
130
- * Optional lifecycle hooks invoked by the active transport. Every hook may be
131
- * synchronous or asynchronous; rejected promises are isolated so one failing hook
132
- * never blocks delivery to other connections.
133
- */
134
- interface IConnectionLifecycleHooks {
135
- /** Called after authentication succeeds and the connection is registered. */
136
- onConnect?(meta: ConnectionEventMeta): void | Promise<void>;
137
- /** Called when the connection closes for any reason. */
138
- onDisconnect?(meta: ConnectionEventMeta & {
139
- reason?: string;
140
- durationMs: number;
141
- }): void | Promise<void>;
142
- /** Called on a transport error. */
143
- onError?(meta: {
144
- connectionId?: string;
145
- error: Error;
146
- transport: 'sse' | 'websocket';
147
- }): void | Promise<void>;
148
- /** Called on re-authentication failure, before disconnect. */
149
- onReauthenticationFailed?(meta: ConnectionEventMeta): void | Promise<void>;
150
- }
151
-
152
- /**
153
- * @fileoverview Cross-instance message bus contract for SSE horizontal scaling.
154
- * @layer contracts
155
- */
156
- /** A single cross-instance fan-out message. */
157
- interface RealtimePubSubMessage {
158
- /** Operation type. */
159
- readonly op: 'emitToUser' | 'emitToTenant' | 'emitToRoom' | 'broadcast' | 'disconnect';
160
- /** Operation arguments — the concrete shape is narrowed per `op` at the call site. */
161
- readonly args: unknown;
162
- /** Instance id that originated the message (used to avoid echo). */
163
- readonly origin: string;
164
- }
165
- /**
166
- * Cross-instance message bus.
167
- *
168
- * The library provides `InMemoryPubSub` (the single-instance default) and ships a
169
- * reference Redis-backed implementation (`RedisRealtimePubSub`) for multi-instance
170
- * deployments. For WebSocket-only deployments, `@socket.io/redis-adapter` is the
171
- * recommended scaling primitive and `IRealtimePubSub` is not required.
172
- */
173
- interface IRealtimePubSub {
174
- /** Publish a message to all subscribers (the other instances). */
175
- publish(message: RealtimePubSubMessage): Promise<void>;
176
- /** Subscribe to messages. Resolves to an async unsubscribe handle. */
177
- subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
178
- }
179
-
180
- /**
181
- * @fileoverview Optional durable offline-queue storage for Last-Event-ID replay.
182
- * @layer contracts
183
- */
184
- /** A single event persisted in a user's offline queue. */
185
- interface OfflineQueuedEvent {
186
- /** Monotonic id — used as `Last-Event-ID` across reconnections. */
187
- readonly id: string;
188
- readonly event: string;
189
- readonly data: unknown;
190
- readonly emittedAt: Date;
191
- }
192
- /**
193
- * Optional durable per-user offline queue.
194
- *
195
- * Consulted as a fallback when a reconnect's gap exceeds the in-memory replay
196
- * buffer. Implementations should enforce per-user retention (size + TTL).
197
- */
198
- interface IOfflineQueueStorage {
199
- /** Append an event to a user's offline queue. */
200
- append(userId: string, event: OfflineQueuedEvent): Promise<void>;
201
- /** Retrieve events with `id > sinceId`, up to `limit`. */
202
- retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
203
- /** Mark events delivered up to `upToId`. Implementations may purge or retain. */
204
- acknowledge(userId: string, upToId: string): Promise<void>;
205
- }
206
-
207
- /**
208
- * @fileoverview Optional presence-tracking contract ("who is online?").
209
- * @layer contracts
210
- */
211
- /**
212
- * Optional presence tracking — answers "who is online?" across instances. When it
213
- * is not provided, presence-dependent features (e.g. the `usePresence` hook) are
214
- * disabled.
215
- */
216
- interface IPresenceStorage {
217
- setOnline(userId: string, connectionId: string, tenantId?: string): Promise<void>;
218
- setOffline(userId: string, connectionId: string): Promise<void>;
219
- isOnline(userId: string): Promise<boolean>;
220
- listOnlineByTenant(tenantId: string): Promise<string[]>;
221
- countOnline(): Promise<number>;
222
- }
223
-
224
- /**
225
- * @fileoverview Module configuration contracts (sync + async dynamic module).
226
- * @layer contracts
227
- */
228
-
229
- /** CORS configuration shared by the SSE and WebSocket transports. */
230
- interface CorsConfig {
231
- origin?: string | readonly string[] | boolean;
232
- credentials?: boolean;
233
- methods?: readonly string[];
234
- }
235
- /**
236
- * SSE-transport-specific options.
237
- *
238
- * CORS for the SSE endpoint is intentionally not configured here: the endpoint is a
239
- * standard HTTP GET, so cross-origin access is controlled at the NestJS application
240
- * level (`app.enableCors(...)`). `CorsConfig` applies to the WebSocket transport.
241
- */
242
- interface SseOptions {
243
- endpoint?: string;
244
- heartbeatMs?: number;
245
- replayBufferSize?: number;
246
- maxConnectionsPerUser?: number;
247
- emitConnectionEvent?: boolean;
248
- }
249
- /** WebSocket-transport-specific options. */
250
- interface WebSocketOptions {
251
- namespace?: string;
252
- cors?: CorsConfig;
253
- maxHttpBufferSize?: number;
254
- pingIntervalMs?: number;
255
- pingTimeoutMs?: number;
256
- maxConnectionsPerUser?: number;
257
- /**
258
- * Emit a `connection:established` event to the client immediately after a
259
- * successful WebSocket handshake. Defaults to `true`.
260
- *
261
- * Transport-neutral for WebSocket and independent of `sse.emitConnectionEvent`,
262
- * so toggling the SSE flag never changes WebSocket behavior.
263
- */
264
- emitConnectionEvent?: boolean;
265
- redisAdapter?: {
266
- /**
267
- * The ioredis client used by `@socket.io/redis-adapter`. Typed `unknown` so
268
- * the library never imports `ioredis`; the consumer passes a concrete client
269
- * and the WebSocket transport calls `.duplicate()` for the subscriber.
270
- */
271
- pubClient: unknown;
272
- };
273
- }
274
- /** Periodic re-authentication policy for long-lived connections. */
275
- interface ReauthenticationPolicy {
276
- intervalSeconds?: number;
277
- onFailure?: 'disconnect' | 'event';
278
- cacheTtlMs?: number;
279
- }
280
- /** Synchronous module configuration. */
281
- interface BymaxRealtimeModuleOptions {
282
- transport: TransportMode;
283
- service?: {
284
- name: string;
285
- version: string;
286
- };
287
- authenticator: IConnectionAuthenticator;
288
- tenantResolver?: (auth: AuthenticationResult) => string | undefined;
289
- hooks?: IConnectionLifecycleHooks;
290
- pubsub?: IRealtimePubSub;
291
- offlineQueue?: IOfflineQueueStorage;
292
- presence?: IPresenceStorage;
293
- sse?: SseOptions;
294
- websocket?: WebSocketOptions;
295
- reauthenticationPolicy?: ReauthenticationPolicy;
296
- }
297
- /**
298
- * Synchronous configuration for `BymaxRealtimeModule`, which serves SSE only.
299
- *
300
- * `transport` is narrowed rather than validated at runtime: WebSocket lives
301
- * behind `@bymax-one/nest-realtime/websocket`, so asking this module for it is
302
- * a mistake the compiler can catch.
303
- */
304
- type SseRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
305
- transport: 'sse';
306
- };
307
- /** A factory that builds module options (async dynamic-module pattern). */
308
- interface BymaxRealtimeModuleOptionsFactory {
309
- createRealtimeOptions(): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
310
- }
311
- /** Asynchronous module configuration — the standard NestJS dynamic-module pattern. */
312
- interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
313
- /**
314
- * The transport this registration wires. Required, not a hint: providers and
315
- * controllers are fixed at decoration time, long before a factory runs, so the
316
- * module cannot discover its own transport later. It MUST equal the
317
- * `transport` the factory resolves; a mismatch fails fast at bootstrap.
318
- */
319
- transport: TransportMode;
320
- useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
321
- inject?: readonly (string | symbol | Type<unknown>)[];
322
- useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
323
- useClass?: Type<BymaxRealtimeModuleOptionsFactory>;
324
- /**
325
- * Additional providers to register alongside the module (e.g. the authenticator
326
- * class when it is a NestJS-managed injectable).
327
- */
328
- extraProviders?: Provider[];
329
- }
330
- /** Asynchronous configuration for `BymaxRealtimeModule` (SSE only). */
331
- type SseRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
332
- transport: 'sse';
333
- };
334
-
335
- /**
336
- * Realtime module for Server-Sent Events. Registered globally so a single
337
- * configuration serves the whole application.
338
- *
339
- * WebSocket lives behind `@bymax-one/nest-realtime/websocket`, and that split is
340
- * what this module buys: nothing reachable from here imports
341
- * `@nestjs/websockets` or `socket.io`, so an SSE application never installs the
342
- * Socket.IO stack. Reach for `BymaxRealtimeWebSocketModule` when the transport
343
- * is `'websocket'` or `'both'`.
344
- */
345
- declare class BymaxRealtimeModule {
346
- private static readonly logger;
347
- /**
348
- * Configure the module synchronously.
349
- *
350
- * @throws when the options are invalid.
351
- * @example
352
- * ```ts
353
- * BymaxRealtimeModule.forRoot({
354
- * transport: 'sse',
355
- * authenticator: new MyAuthenticator(),
356
- * })
357
- * ```
358
- */
359
- static forRoot(options: SseRealtimeModuleOptions): DynamicModule;
360
- /**
361
- * Configure the module asynchronously so options — and the authenticator —
362
- * can be resolved through DI: `ConfigService`, a Redis client, and so on.
363
- *
364
- * Options are validated inside the resolving factory, so a malformed
365
- * configuration rejects at bootstrap and the application fails to start with
366
- * a clear error.
367
- *
368
- * Controllers are registered at decoration time, so this path binds the SSE
369
- * controller to the default endpoint `/events`. A non-default endpoint needs
370
- * `forRoot` with pre-resolved options.
371
- *
372
- * @throws when no factory pattern is given, more than one is, or the factory
373
- * resolves a transport other than `'sse'`.
374
- * @example
375
- * ```ts
376
- * BymaxRealtimeModule.forRootAsync({
377
- * transport: 'sse',
378
- * imports: [ConfigModule],
379
- * inject: [ConfigService],
380
- * useFactory: (cfg: ConfigService) => ({
381
- * transport: 'sse' as const,
382
- * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
383
- * }),
384
- * })
385
- * ```
386
- */
387
- static forRootAsync(asyncOptions: SseRealtimeModuleAsyncOptions): DynamicModule;
388
- }
389
-
390
- /**
391
- * @fileoverview Unified transport abstraction implemented by every transport.
392
- * @layer contracts
393
- */
394
- /**
395
- * Unified transport abstraction.
396
- *
397
- * The library ships concrete implementations (`SseTransport`, the WebSocket
398
- * transport, and a composite that fans out to both). Consumers normally interact
399
- * with `RealtimeService`, which delegates to the active transport; implementing a
400
- * custom `ITransport` is an advanced use case (e.g. bridging an external bus).
401
- *
402
- * @example
403
- * ```ts
404
- * class NoopTransport implements ITransport {
405
- * readonly kind = 'sse' as const
406
- * async emitToUser() {}
407
- * async emitToTenant() {}
408
- * async emitToRoom() {}
409
- * async broadcast() {}
410
- * async joinRoom() {}
411
- * async leaveRoom() {}
412
- * async disconnect() {}
413
- * }
414
- * ```
415
- */
416
- interface ITransport {
417
- /** Transport identifier. A composite reports its dominant kind (`'sse'`). */
418
- readonly kind: 'sse' | 'websocket';
419
- /** Send to every connection of a single user. */
420
- emitToUser(userId: string, event: string, data: unknown): Promise<void>;
421
- /** Send to every connection of every user in a tenant. */
422
- emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
423
- /** Send to every connection in a logical room. */
424
- emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
425
- /** Send to all connected clients. Use sparingly. */
426
- broadcast(event: string, data: unknown): Promise<void>;
427
- /** Join a connection to a room (idempotent). */
428
- joinRoom(connectionId: string, roomId: string): Promise<void>;
429
- /** Leave a connection from a room (idempotent). */
430
- leaveRoom(connectionId: string, roomId: string): Promise<void>;
431
- /** Disconnect a specific connection (e.g. on auth revocation). */
432
- disconnect(connectionId: string, reason?: string): Promise<void>;
433
- /** Lifecycle hook — called on NestJS bootstrap. */
434
- onModuleInit?(): Promise<void>;
435
- /** Lifecycle hook — called on NestJS shutdown. */
436
- onApplicationShutdown?(): Promise<void>;
437
- }
438
-
439
- /**
440
- * Transport-agnostic realtime API.
441
- *
442
- * Every method delegates to the active transport, so switching transport (for
443
- * example `'sse'` → `'websocket'`) requires no change in the application services
444
- * that call this API.
445
- */
446
- declare class RealtimeService {
447
- private readonly transport;
448
- constructor(transport: ITransport);
449
- /**
450
- * Send to all of a user's connections (across devices/tabs).
451
- *
452
- * @example
453
- * ```ts
454
- * await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
455
- * ```
456
- */
457
- emitToUser(userId: string, event: string, data: unknown): Promise<void>;
458
- /** Send to every connection in a tenant. */
459
- emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
460
- /**
461
- * Send to a logical room. Use the prefix convention (`user:{id}`,
462
- * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
463
- */
464
- emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
465
- /** Send to every connected client. Use sparingly. */
466
- broadcast(event: string, data: unknown): Promise<void>;
467
- /** Add a specific connection to a room. */
468
- joinRoom(connectionId: string, roomId: string): Promise<void>;
469
- /** Remove a specific connection from a room. */
470
- leaveRoom(connectionId: string, roomId: string): Promise<void>;
471
- /** Force-disconnect a specific connection (e.g. on auth revocation). */
472
- disconnect(connectionId: string, reason?: string): Promise<void>;
473
- }
474
-
475
- /** Transport kind a connection belongs to. */
476
- type ConnectionTransport = 'sse' | 'websocket';
477
- /**
478
- * Internal record kept per active connection.
479
- *
480
- * `subject` and `close$` are populated only for SSE connections (the per-connection
481
- * RxJS stream and its server-initiated teardown signal). WebSocket connections set
482
- * both to `null` and rely on the Socket.IO server's own emit/disconnect mechanism.
483
- */
484
- interface ConnectionRecord {
485
- connectionId: string;
486
- userId: string;
487
- tenantId: string | undefined;
488
- transport: ConnectionTransport;
489
- ip: string;
490
- userAgent: string | undefined;
491
- connectedAt: Date;
492
- /** Per-connection event stream (SSE only); `null` for WebSocket. */
493
- subject: Subject<MessageEvent> | null;
494
- /** Server-initiated teardown signal (SSE only); `null` for WebSocket. */
495
- close$: Subject<void> | null;
496
- /** Snapshot of the original authentication result — used by the re-auth policy. */
497
- originalAuth: {
498
- userId: string;
499
- tenantId: string | undefined;
500
- roles: readonly string[] | undefined;
501
- };
502
- }
503
- /**
504
- * Indexed registry of active connections.
505
- *
506
- * Maintains three maps — `byId` (connectionId → record), `byUserId` (userId →
507
- * Set<connectionId>) and `byTenantId` (tenantId → Set<connectionId>) — kept
508
- * consistent on every `register`/`unregister`. Operations are amortized O(1);
509
- * mutation is single-threaded (the Node.js event loop), so no locking is needed.
510
- */
511
- declare class ConnectionRegistry {
512
- private readonly byId;
513
- private readonly byUserId;
514
- private readonly byTenantId;
515
- /** Register a connection and index it by user and tenant. */
516
- register(record: ConnectionRecord): void;
517
- /** Remove a connection from every index. Returns the removed record, if any. */
518
- unregister(connectionId: string): ConnectionRecord | undefined;
519
- /** Look up a single connection by id. */
520
- get(connectionId: string): ConnectionRecord | undefined;
521
- /** All connections of a user, optionally filtered by transport. */
522
- byUser(userId: string, transport?: ConnectionTransport): ConnectionRecord[];
523
- /** All connections of a tenant, optionally filtered by transport. */
524
- byTenant(tenantId: string, transport?: ConnectionTransport): ConnectionRecord[];
525
- /** All connections of a given transport. */
526
- allByTransport(transport: ConnectionTransport): ConnectionRecord[];
527
- /** Total number of active connections. */
528
- count(): number;
529
- /** Number of distinct users currently connected. */
530
- countUsers(): number;
531
- private resolve;
532
- private addToSetMap;
533
- private removeFromSetMap;
534
- }
535
-
536
- /**
537
- * Default single-instance pub/sub.
538
- *
539
- * `publish` defers delivery one microtask (`await Promise.resolve()`) before
540
- * iterating handlers, matching Redis async-callback semantics. A handler that
541
- * throws is caught internally so the remaining handlers still receive the message.
542
- * Multi-instance deployments replace this with a Redis-backed `IRealtimePubSub`.
543
- */
544
- declare class InMemoryPubSub implements IRealtimePubSub {
545
- private readonly handlers;
546
- /**
547
- * Publish a message to all subscribed handlers.
548
- *
549
- * Delivery is deferred one microtask so a handler that enqueues further publishes
550
- * does not deepen the current call stack. One handler's failure does not block others.
551
- *
552
- * @param message - The pub/sub message to fan out.
553
- */
554
- publish(message: RealtimePubSubMessage): Promise<void>;
555
- /**
556
- * Subscribe to pub/sub messages.
557
- *
558
- * @param handler - Called for every published message.
559
- * @returns An async unsubscribe function that removes this handler.
560
- */
561
- subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
562
- }
563
-
564
- /**
565
- * @fileoverview Redis-backed pub/sub for cross-instance SSE fan-out.
566
- * @layer infrastructure
567
- */
568
-
569
- /** Options for RedisRealtimePubSub. */
570
- interface RedisRealtimePubSubOptions {
571
- /** The Redis client used for publishing. A separate subscriber clone is created internally. */
572
- readonly client: Redis;
573
- /** The Redis pub/sub channel name. Defaults to `bymax:realtime`. */
574
- readonly channel?: string;
575
- }
576
- /**
577
- * Redis-backed `IRealtimePubSub` for horizontal scaling.
578
- *
579
- * Uses two Redis clients: one for `PUBLISH` (the provided client) and one for
580
- * `SUBSCRIBE` (a lazily-duplicated clone). The subscriber clone is created on
581
- * the first `subscribe()` call and quit on the last `unsubscribe()`.
582
- *
583
- * Messages are JSON-encoded. Malformed payloads are silently dropped.
584
- *
585
- * @example
586
- * ```ts
587
- * const redis = new Redis(process.env.REDIS_URL)
588
- * BymaxRealtimeModule.forRoot({
589
- * transport: 'sse',
590
- * authenticator,
591
- * pubsub: new RedisRealtimePubSub({ client: redis }),
592
- * })
593
- * ```
594
- */
595
- declare class RedisRealtimePubSub implements IRealtimePubSub {
596
- private readonly pub;
597
- private readonly channel;
598
- private subInit;
599
- private readonly handlers;
600
- constructor(options: RedisRealtimePubSubOptions);
601
- /** JSON-encodes the message and PUBLISHes it to the configured channel. */
602
- publish(message: RealtimePubSubMessage): Promise<void>;
603
- /**
604
- * Lazily creates the single shared subscribe client on first call; returns an async
605
- * unsubscribe that quits the client when the last handler is removed. Concurrent
606
- * subscribe calls are idempotent — only one client is ever created. Malformed
607
- * payloads are dropped silently.
608
- *
609
- * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
610
- * the handler registration is rolled back and the cached init promise is cleared so
611
- * the next call retries from scratch.
612
- */
613
- subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
614
- /** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
615
- private ensureSubscriber;
616
- private createSubscriber;
617
- private dispatch;
618
- }
619
-
620
- /**
621
- * @fileoverview Redis sorted-set offline queue for durable per-user event retention.
622
- * @layer infrastructure
623
- */
624
-
625
- /** Options for RedisOfflineQueue. */
626
- interface RedisOfflineQueueOptions {
627
- /** The Redis client to use for all queue operations. */
628
- readonly client: Redis;
629
- /** Maximum events retained per user (oldest are trimmed). Defaults to 500. */
630
- readonly maxPerUser?: number;
631
- /** TTL for each user's key in seconds. Defaults to 3600 (1 hour). */
632
- readonly ttlSeconds?: number;
633
- }
634
- /**
635
- * Redis sorted-set–backed implementation of `IOfflineQueueStorage`.
636
- *
637
- * Each user's events are stored in a sorted set keyed `bymax:oq:{userId}`.
638
- * All entries share score 0; ordering is purely lexicographic on the member
639
- * prefix `${ms_padded}-${counter_padded}|${json}`, which is immune to the
640
- * IEEE-754 double precision loss that affects fractional ZSET scores at
641
- * epoch-millisecond magnitude. Events are trimmed to `maxPerUser` oldest-first,
642
- * and the key expires after `ttlSeconds` of inactivity.
643
- *
644
- * @example
645
- * ```ts
646
- * const redis = new Redis(process.env.REDIS_URL)
647
- * BymaxRealtimeModule.forRoot({
648
- * transport: 'sse',
649
- * authenticator,
650
- * offlineQueue: new RedisOfflineQueue({ client: redis }),
651
- * })
652
- * ```
653
- */
654
- declare class RedisOfflineQueue implements IOfflineQueueStorage {
655
- private readonly client;
656
- private readonly maxPerUser;
657
- private readonly ttlSeconds;
658
- /** Zero-pad width for the epoch-millisecond component of the sort key. */
659
- private static readonly MS_PAD;
660
- /** Zero-pad width for the intra-millisecond counter component of the sort key. */
661
- private static readonly COUNTER_PAD;
662
- constructor(options: RedisOfflineQueueOptions);
663
- private key;
664
- /**
665
- * Build the fixed-width lexicographic sort key for an event id.
666
- *
667
- * Handles two id formats:
668
- * - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
669
- * - Legacy plain numeric strings: `1700000000000`
670
- */
671
- private lexKey;
672
- /**
673
- * Return the lexicographically next sort key after `id`, used as an
674
- * inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
675
- */
676
- private lexKeyNext;
677
- /** Encode an event into a lexicographically sortable ZSET member string. */
678
- private encodeMember;
679
- append(userId: string, event: OfflineQueuedEvent): Promise<void>;
680
- retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
681
- acknowledge(userId: string, upToId: string): Promise<void>;
682
- }
683
-
684
- /**
685
- * @fileoverview Dependency-injection tokens (unique Symbols) and shared module-level constants.
686
- * @layer composition
687
- */
688
- /**
689
- * Dependency-injection tokens.
690
- *
691
- * Symbols are used instead of strings so tokens are guaranteed unique at runtime
692
- * and cannot collide with tokens from other libraries.
693
- */
694
- declare const REALTIME_OPTIONS_TOKEN: unique symbol;
695
- declare const REALTIME_TRANSPORT_TOKEN: unique symbol;
696
- declare const REALTIME_AUTHENTICATOR_TOKEN: unique symbol;
697
- declare const REALTIME_PUBSUB_TOKEN: unique symbol;
698
- declare const REALTIME_OFFLINE_QUEUE_TOKEN: unique symbol;
699
- declare const REALTIME_PRESENCE_TOKEN: unique symbol;
700
- declare const REALTIME_HOOKS_TOKEN: unique symbol;
701
- declare const REALTIME_INSTANCE_ID_TOKEN: unique symbol;
702
-
703
- /**
704
- * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
705
- * @layer shared
706
- */
707
- /**
708
- * Canonical room id prefixes — used to scope emits and auto-join connections.
709
- *
710
- * Convention:
711
- * - `user:{userId}` — a single user's connections
712
- * - `tenant:{tenantId}` — every connection within a tenant
713
- * - `resource:{resourceType}:{id}` — a per-resource room (e.g. invoice, session)
714
- *
715
- * Anything else is application-defined and free-form. Changing a prefix value is
716
- * a breaking change for every connected client and stored room id.
717
- */
718
- declare const ROOM_PREFIXES: {
719
- readonly USER: "user";
720
- readonly TENANT: "tenant";
721
- readonly RESOURCE: "resource";
722
- };
723
- /** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
724
- type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
725
-
726
- /**
727
- * @fileoverview Helper that builds canonical room ids from the prefix convention.
728
- * @layer utils
729
- */
730
-
731
- /**
732
- * Build a canonical room id following the library's prefix convention.
733
- *
734
- * Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
735
- * this helper only joins the prefix and parts with `:`.
736
- *
737
- * @example
738
- * ```ts
739
- * composeRoomId('USER', 'u_abc') // → 'user:u_abc'
740
- * composeRoomId('TENANT', 't_acme') // → 'tenant:t_acme'
741
- * composeRoomId('RESOURCE', 'invoice', 'inv_123') // → 'resource:invoice:inv_123'
742
- * ```
743
- */
744
- declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
745
-
746
- /**
747
- * @fileoverview Generic realtime event shape shared across transports and the client.
748
- * @layer shared
749
- */
750
- /**
751
- * Generic shape of an event traveling over a realtime transport.
752
- *
753
- * Consumers typically declare a mapped type describing their own events and layer
754
- * it on top of this generic for end-to-end type safety:
755
- *
756
- * @example
757
- * ```ts
758
- * interface MyAppEvents {
759
- * 'invoice.paid': { id: string; amount: number }
760
- * 'webhook.dlq': { webhookId: string; reason: string }
761
- * }
762
- *
763
- * type InvoicePaid = RealtimeEvent<MyAppEvents['invoice.paid']>
764
- * ```
765
- */
766
- interface RealtimeEvent<TData = unknown> {
767
- /** Monotonically increasing event id — used for `Last-Event-ID` replay. */
768
- readonly id: string;
769
- /** Event name (matches the consumer's mapped-type key). */
770
- readonly type: string;
771
- /** Free-form payload. */
772
- readonly data: TData;
773
- }
774
-
775
- /**
776
- * @fileoverview Public-facing metadata about a single realtime connection.
777
- * @layer shared
778
- */
779
- /**
780
- * Public-facing metadata about a single realtime connection.
781
- *
782
- * The full internal record (which, for SSE, also holds the per-connection RxJS
783
- * `Subject` and `close$` teardown signal) is kept private to the server runtime —
784
- * see `src/server/services/connection-registry.service.ts`. This type exposes only
785
- * the fields that are safe to share with diagnostics and the client.
786
- */
787
- interface PublicConnectionMeta {
788
- readonly connectionId: string;
789
- readonly userId: string;
790
- readonly tenantId?: string;
791
- readonly transport: 'sse' | 'websocket';
792
- readonly connectedAt: Date;
793
- }
794
-
795
- /**
796
- * @fileoverview Event names reserved by the library (the §13 catalog).
797
- * @layer shared
798
- */
799
- /**
800
- * Event names reserved by the library.
801
- *
802
- * Consumer apps should not reuse these names for application-level events; doing
803
- * so will not throw, but causes confusion in logs and client-side listeners.
804
- *
805
- * Note: the SSE heartbeat is intentionally absent. It is a raw `: keepalive`
806
- * comment written directly to the response stream (not a named event and outside
807
- * the `Last-Event-ID` id-space), so it is not part of this catalog.
808
- */
809
- declare const RESERVED_EVENT_NAMES: {
810
- readonly CONNECTION_ESTABLISHED: "connection:established";
811
- readonly CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed";
812
- readonly CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring";
813
- readonly ROOM_JOINED: "room:joined";
814
- readonly ROOM_LEFT: "room:left";
815
- readonly ERROR: "error";
816
- };
817
- /** Union of reserved event name values. */
818
- type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
819
-
820
- /**
821
- * @fileoverview Canonical error codes emitted by the library (the §14 catalog).
822
- * @layer shared
823
- */
824
- /**
825
- * Canonical error codes emitted by the library. Map 1-to-1 with
826
- * `docs/technical_specification.md` §14.
827
- *
828
- * `TOO_MANY_CONNECTIONS` signals FIFO eviction: when a user exceeds
829
- * `maxConnectionsPerUser`, the OLDEST connection is evicted (closed with this
830
- * code) and the new one is admitted — it is never an HTTP 429 rejection.
831
- */
832
- declare const REALTIME_ERROR_CODES: {
833
- readonly INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS";
834
- readonly NO_AUTHENTICATOR: "REALTIME_NO_AUTHENTICATOR";
835
- readonly AUTH_FAILED: "REALTIME_AUTH_FAILED";
836
- readonly REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED";
837
- readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
838
- readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
839
- readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
840
- readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
841
- readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
842
- };
843
- /** Union of canonical error code values. */
844
- type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
845
-
846
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimeService, type ReauthenticationPolicy, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, type SseOptions, type TransportMode, type WebSocketOptions, composeRoomId };
1
+ export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';