@bymax-one/nest-realtime 1.0.2 → 1.0.4

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,9 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var common = require('@nestjs/common');
4
- var crypto = require('crypto');
5
- var rxjs = require('rxjs');
6
- var operators = require('rxjs/operators');
4
+ var internal = require('@bymax-one/nest-realtime/internal');
7
5
  var websockets = require('@nestjs/websockets');
8
6
  var platformSocket_io = require('@nestjs/platform-socket.io');
9
7
 
@@ -26,1347 +24,6 @@ var __decorateClass = (decorators, target, key, kind) => {
26
24
  };
27
25
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
26
  var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
29
-
30
- // src/shared/constants/error-codes.constants.ts
31
- var REALTIME_ERROR_CODES = {
32
- INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS",
33
- NO_AUTHENTICATOR: "REALTIME_NO_AUTHENTICATOR",
34
- AUTH_FAILED: "REALTIME_AUTH_FAILED",
35
- REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED",
36
- TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS"};
37
-
38
- // src/server/config/default-options.ts
39
- var DEFAULT_SSE = {
40
- endpoint: "/realtime/sse",
41
- heartbeatMs: 3e4,
42
- replayBufferSize: 100,
43
- maxConnectionsPerUser: 5,
44
- emitConnectionEvent: true
45
- };
46
- function applyDefaults(options) {
47
- return Object.freeze({
48
- ...options,
49
- sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
50
- });
51
- }
52
- var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
53
- function validateOptions(options) {
54
- if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
55
- throw new Error(
56
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
57
- );
58
- }
59
- if (!options.authenticator) {
60
- throw new Error(
61
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
62
- );
63
- }
64
- if (typeof options.authenticator.authenticate !== "function") {
65
- throw new Error(
66
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
67
- );
68
- }
69
- validateSseOptions(options);
70
- validateReauthPolicy(options);
71
- }
72
- function validateReauthPolicy(options) {
73
- const policy = options.reauthenticationPolicy;
74
- if (policy?.cacheTtlMs !== void 0 && policy.intervalSeconds !== void 0 && policy.cacheTtlMs > policy.intervalSeconds * 1e3) {
75
- common.Logger.warn(
76
- `[BymaxRealtimeModule] reauthenticationPolicy.cacheTtlMs (${policy.cacheTtlMs} ms) exceeds intervalSeconds*1000 (${policy.intervalSeconds * 1e3} ms): the positive reauth cache outlives the interval, so revalidate is skipped on ticks within the cache window \u2014 reauthentication is effectively weakened`,
77
- "BymaxRealtimeModule"
78
- );
79
- }
80
- }
81
- function validateSseOptions(options) {
82
- const sse = options.sse;
83
- if (sse?.heartbeatMs !== void 0 && sse.heartbeatMs <= 0) {
84
- throw new Error(
85
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be > 0`
86
- );
87
- }
88
- if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
89
- throw new Error(
90
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
91
- );
92
- }
93
- if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
94
- throw new Error(
95
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
96
- );
97
- }
98
- }
99
-
100
- // src/server/constants/injection-tokens.constants.ts
101
- var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
102
- var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
103
- var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
104
- var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
105
- var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
106
- var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
107
- var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
108
- var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
109
- var DEFAULT_HEARTBEAT_MS = 3e4;
110
- var RETRIEVE_LIMIT = 200;
111
- var OfflineQueueDeliveryService = class {
112
- constructor(storage) {
113
- this.storage = storage;
114
- }
115
- storage;
116
- logger = new common.Logger(OfflineQueueDeliveryService.name);
117
- /**
118
- * Return events for `userId` that arrived after `lastEventId` and are NOT
119
- * already covered by `ringBufferIds` (already replayed from in-memory buffer).
120
- *
121
- * Retrieval does NOT acknowledge: the durable queue is pruned only after the events
122
- * have been emitted to a live subscriber via {@link acknowledge}. This guarantees
123
- * at-least-once delivery — events that never reach the client are never lost.
124
- *
125
- * @param userId - The reconnecting user.
126
- * @param lastEventId - The `Last-Event-ID` header value.
127
- * @param ringBufferIds - Set of event ids already replayed from the ring buffer.
128
- * @returns Gap events, or an empty array when no offline queue is configured.
129
- */
130
- async retrieve(userId, lastEventId, ringBufferIds) {
131
- if (!this.storage) return [];
132
- let events;
133
- try {
134
- events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
135
- } catch (err) {
136
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
137
- return [];
138
- }
139
- if (events.length === RETRIEVE_LIMIT) {
140
- this.logger.warn(
141
- `Offline queue retrieve hit the ${RETRIEVE_LIMIT}-event limit for user; older gap events may be dropped.`
142
- );
143
- }
144
- return events.filter((e) => !ringBufferIds.has(e.id));
145
- }
146
- /**
147
- * Acknowledge delivered offline events so the storage backend can prune them.
148
- *
149
- * At-least-once contract: call this ONLY after the events have been emitted to a
150
- * still-open subscriber. Acknowledging before emission would permanently drop events
151
- * that never reached the client. A failure is swallowed (logged) so a transient
152
- * storage error never disrupts delivery; the events simply redeliver on reconnect.
153
- *
154
- * @param userId - The user whose queue is acknowledged.
155
- * @param events - The delivered gap events; the last id is the prune watermark.
156
- */
157
- async acknowledge(userId, events) {
158
- if (!this.storage || events.length === 0) return;
159
- const lastId = events[events.length - 1].id;
160
- try {
161
- await this.storage.acknowledge(userId, lastId);
162
- } catch (err) {
163
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
164
- }
165
- }
166
- };
167
- OfflineQueueDeliveryService = __decorateClass([
168
- common.Injectable(),
169
- __decorateParam(0, common.Optional()),
170
- __decorateParam(0, common.Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
171
- ], OfflineQueueDeliveryService);
172
-
173
- // src/shared/constants/reserved-events.constants.ts
174
- var RESERVED_EVENT_NAMES = {
175
- CONNECTION_ESTABLISHED: "connection:established",
176
- CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed",
177
- CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring",
178
- ROOM_JOINED: "room:joined",
179
- ROOM_LEFT: "room:left",
180
- ERROR: "error"
181
- };
182
-
183
- // src/server/utils/parse-cookie-header.ts
184
- function parseCookieHeader(cookieHeader) {
185
- const out = /* @__PURE__ */ Object.create(null);
186
- if (!cookieHeader) return out;
187
- for (const pair of cookieHeader.split(";")) {
188
- const idx = pair.indexOf("=");
189
- if (idx === -1) continue;
190
- const name = pair.slice(0, idx).trim();
191
- const value = pair.slice(idx + 1).trim();
192
- if (name) out[name] = value;
193
- }
194
- return out;
195
- }
196
- var ConnectionRegistry = class {
197
- byId = /* @__PURE__ */ new Map();
198
- byUserId = /* @__PURE__ */ new Map();
199
- byTenantId = /* @__PURE__ */ new Map();
200
- /** Register a connection and index it by user and tenant. */
201
- register(record) {
202
- this.byId.set(record.connectionId, record);
203
- this.addToSetMap(this.byUserId, record.userId, record.connectionId);
204
- if (record.tenantId !== void 0) {
205
- this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
206
- }
207
- }
208
- /** Remove a connection from every index. Returns the removed record, if any. */
209
- unregister(connectionId) {
210
- const record = this.byId.get(connectionId);
211
- if (!record) return void 0;
212
- this.byId.delete(connectionId);
213
- this.removeFromSetMap(this.byUserId, record.userId, connectionId);
214
- if (record.tenantId !== void 0) {
215
- this.removeFromSetMap(this.byTenantId, record.tenantId, connectionId);
216
- }
217
- return record;
218
- }
219
- /** Look up a single connection by id. */
220
- get(connectionId) {
221
- return this.byId.get(connectionId);
222
- }
223
- /** All connections of a user, optionally filtered by transport. */
224
- byUser(userId, transport) {
225
- return this.resolve(this.byUserId.get(userId), transport);
226
- }
227
- /** All connections of a tenant, optionally filtered by transport. */
228
- byTenant(tenantId, transport) {
229
- return this.resolve(this.byTenantId.get(tenantId), transport);
230
- }
231
- /** All connections of a given transport. */
232
- allByTransport(transport) {
233
- return Array.from(this.byId.values()).filter((record) => record.transport === transport);
234
- }
235
- /** Total number of active connections. */
236
- count() {
237
- return this.byId.size;
238
- }
239
- /** Number of distinct users currently connected. */
240
- countUsers() {
241
- return this.byUserId.size;
242
- }
243
- resolve(ids, transport) {
244
- if (!ids) return [];
245
- const out = [];
246
- for (const id of ids) {
247
- const record = this.byId.get(id);
248
- if (record && (transport === void 0 || record.transport === transport)) {
249
- out.push(record);
250
- }
251
- }
252
- return out;
253
- }
254
- addToSetMap(map, key, value) {
255
- const existing = map.get(key);
256
- if (existing) existing.add(value);
257
- else map.set(key, /* @__PURE__ */ new Set([value]));
258
- }
259
- removeFromSetMap(map, key, value) {
260
- const existing = map.get(key);
261
- if (!existing) return;
262
- existing.delete(value);
263
- if (existing.size === 0) map.delete(key);
264
- }
265
- };
266
- ConnectionRegistry = __decorateClass([
267
- common.Injectable()
268
- ], ConnectionRegistry);
269
- var COUNTER_WIDTH = 6;
270
- var EventIdGenerator = class {
271
- lastMs = 0;
272
- counter = 0;
273
- /** Produce the next monotonic event id. */
274
- next() {
275
- const now = Date.now();
276
- if (now === this.lastMs) {
277
- this.counter += 1;
278
- } else {
279
- this.lastMs = now;
280
- this.counter = 1;
281
- }
282
- return `${now}-${String(this.counter).padStart(COUNTER_WIDTH, "0")}`;
283
- }
284
- };
285
- EventIdGenerator = __decorateClass([
286
- common.Injectable()
287
- ], EventIdGenerator);
288
- var RoomRegistry = class {
289
- rooms = /* @__PURE__ */ new Map();
290
- connectionRooms = /* @__PURE__ */ new Map();
291
- /** Join a connection to a room (idempotent). */
292
- join(connectionId, roomId) {
293
- const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
294
- room.add(connectionId);
295
- this.rooms.set(roomId, room);
296
- const conn = this.connectionRooms.get(connectionId) ?? /* @__PURE__ */ new Set();
297
- conn.add(roomId);
298
- this.connectionRooms.set(connectionId, conn);
299
- }
300
- /** Remove a connection from a room (idempotent); prunes empty entries. */
301
- leave(connectionId, roomId) {
302
- const room = this.rooms.get(roomId);
303
- if (room) {
304
- room.delete(connectionId);
305
- if (room.size === 0) this.rooms.delete(roomId);
306
- }
307
- const conn = this.connectionRooms.get(connectionId);
308
- if (conn) {
309
- conn.delete(roomId);
310
- if (conn.size === 0) this.connectionRooms.delete(connectionId);
311
- }
312
- }
313
- /** Snapshot of a room's members — safe to iterate while membership mutates. */
314
- members(roomId) {
315
- const set = this.rooms.get(roomId);
316
- return set ? Array.from(set) : [];
317
- }
318
- /** Snapshot of the rooms a connection currently belongs to. */
319
- roomsOf(connectionId) {
320
- const set = this.connectionRooms.get(connectionId);
321
- return set ? Array.from(set) : [];
322
- }
323
- /** Remove a connection from every room (called on disconnect). */
324
- leaveAll(connectionId) {
325
- const rooms = this.connectionRooms.get(connectionId);
326
- if (!rooms) return;
327
- for (const roomId of rooms) {
328
- const set = this.rooms.get(roomId);
329
- if (set) {
330
- set.delete(connectionId);
331
- if (set.size === 0) this.rooms.delete(roomId);
332
- }
333
- }
334
- this.connectionRooms.delete(connectionId);
335
- }
336
- /** Total number of distinct rooms. */
337
- countRooms() {
338
- return this.rooms.size;
339
- }
340
- };
341
- RoomRegistry = __decorateClass([
342
- common.Injectable()
343
- ], RoomRegistry);
344
-
345
- // src/shared/constants/room-prefixes.constants.ts
346
- var ROOM_PREFIXES = {
347
- USER: "user",
348
- TENANT: "tenant",
349
- RESOURCE: "resource"
350
- };
351
-
352
- // src/server/utils/compose-room-id.ts
353
- function composeRoomId(prefix, ...parts) {
354
- return [ROOM_PREFIXES[prefix], ...parts].join(":");
355
- }
356
- var DEFAULT_REPLAY_BUFFER_SIZE = 100;
357
- var EventReplayBuffer = class {
358
- constructor(opts) {
359
- this.opts = opts;
360
- }
361
- opts;
362
- buffers = /* @__PURE__ */ new Map();
363
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
364
- append(userId, event) {
365
- const buf = this.buffers.get(userId) ?? [];
366
- buf.push(event);
367
- const cap = this.opts.sse?.replayBufferSize ?? DEFAULT_REPLAY_BUFFER_SIZE;
368
- if (buf.length > cap) buf.shift();
369
- this.buffers.set(userId, buf);
370
- }
371
- /**
372
- * Return the events emitted after `lastEventId`.
373
- *
374
- * Returns an empty array when the user has no buffer, or when `lastEventId` is
375
- * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
376
- */
377
- since(userId, lastEventId) {
378
- const buf = this.buffers.get(userId);
379
- if (!buf) return [];
380
- const idx = buf.findIndex((event) => event.id === lastEventId);
381
- if (idx === -1) return [];
382
- return buf.slice(idx + 1);
383
- }
384
- /** Number of events currently buffered for a user (diagnostics). */
385
- size(userId) {
386
- return this.buffers.get(userId)?.length ?? 0;
387
- }
388
- };
389
- EventReplayBuffer = __decorateClass([
390
- common.Injectable(),
391
- __decorateParam(0, common.Inject(REALTIME_OPTIONS_TOKEN))
392
- ], EventReplayBuffer);
393
- var KEEPALIVE_COMMENT = ": keepalive\n\n";
394
- var HEARTBEAT_MIN_MS = 5e3;
395
- var HEARTBEAT_MAX_MS = 9e4;
396
- var HeartbeatService = class {
397
- timers = /* @__PURE__ */ new Map();
398
- /**
399
- * Start writing keepalives for a connection every `intervalMs`.
400
- *
401
- * @param connectionId - Unique connection identifier used to track the timer.
402
- * @param res - The writable response stream (or any object with a `write` method).
403
- * @param intervalMs - Keepalive interval in milliseconds; must be within
404
- * `[5_000, 90_000]`.
405
- * @throws {Error} When `intervalMs` is outside the valid range.
406
- */
407
- start(connectionId, res, intervalMs) {
408
- if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
409
- throw new Error(
410
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
411
- );
412
- }
413
- this.stop(connectionId);
414
- const timer = setInterval(() => {
415
- try {
416
- res.write(KEEPALIVE_COMMENT);
417
- } catch {
418
- this.stop(connectionId);
419
- }
420
- }, intervalMs);
421
- timer.unref();
422
- this.timers.set(connectionId, timer);
423
- }
424
- /** Stop and clear the keepalive timer for a connection (idempotent). */
425
- stop(connectionId) {
426
- const timer = this.timers.get(connectionId);
427
- if (timer) {
428
- clearInterval(timer);
429
- this.timers.delete(connectionId);
430
- }
431
- }
432
- /** Stop every keepalive timer (used on shutdown). */
433
- stopAll() {
434
- for (const timer of this.timers.values()) clearInterval(timer);
435
- this.timers.clear();
436
- }
437
- };
438
- HeartbeatService = __decorateClass([
439
- common.Injectable()
440
- ], HeartbeatService);
441
-
442
- // src/server/transports/sse/sse.transport.ts
443
- var SseTransport = class {
444
- constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
445
- this.connections = connections;
446
- this.rooms = rooms;
447
- this.replayBuffer = replayBuffer;
448
- this.idGen = idGen;
449
- this.heartbeat = heartbeat;
450
- this.auth = auth;
451
- this.pubsub = pubsub;
452
- this.hooks = hooks;
453
- this.options = options;
454
- this.instanceId = instanceId;
455
- this.offlineQueue = offlineQueue;
456
- }
457
- connections;
458
- rooms;
459
- replayBuffer;
460
- idGen;
461
- heartbeat;
462
- auth;
463
- pubsub;
464
- hooks;
465
- options;
466
- instanceId;
467
- offlineQueue;
468
- kind = "sse";
469
- logger = new common.Logger(SseTransport.name);
470
- /** Tear down every SSE connection and stop heartbeat on process shutdown. */
471
- async onApplicationShutdown() {
472
- this.heartbeat.stopAll();
473
- for (const conn of this.connections.allByTransport("sse")) {
474
- await this.disconnectLocal(conn.connectionId);
475
- }
476
- }
477
- /** The resolved heartbeat interval for this transport. */
478
- get heartbeatMs() {
479
- return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
480
- }
481
- /** Whether the `connection:established` event should be emitted on connect. */
482
- get emitConnectionEvent() {
483
- return this.options.sse?.emitConnectionEvent !== false;
484
- }
485
- /** Authenticate a connection through the consumer-provided authenticator. */
486
- authenticate(context) {
487
- return this.auth.authenticate(context);
488
- }
489
- /**
490
- * Register an authenticated SSE connection and auto-join its user/tenant rooms.
491
- *
492
- * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
493
- * lifecycle hook is fired by the subscription handler after this returns, so that the
494
- * handler can carry a consistent connection record reference.
495
- */
496
- async registerConnection(params) {
497
- const record = {
498
- connectionId: params.connectionId,
499
- userId: params.auth.userId,
500
- tenantId: params.auth.tenantId,
501
- transport: "sse",
502
- ip: params.ip,
503
- userAgent: params.userAgent,
504
- connectedAt: /* @__PURE__ */ new Date(),
505
- subject: params.subject,
506
- close$: params.close$,
507
- originalAuth: {
508
- userId: params.auth.userId,
509
- tenantId: params.auth.tenantId,
510
- roles: params.auth.roles
511
- }
512
- };
513
- this.connections.register(record);
514
- this.rooms.join(params.connectionId, composeRoomId("USER", params.auth.userId));
515
- if (params.auth.tenantId !== void 0) {
516
- this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
517
- }
518
- await this.evictBeyondLimit(params.auth.userId);
519
- }
520
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
521
- async unregisterConnection(connectionId, reason) {
522
- const record = this.connections.unregister(connectionId);
523
- if (!record) return;
524
- this.rooms.leaveAll(connectionId);
525
- this.heartbeat.stop(connectionId);
526
- try {
527
- await this.hooks.onDisconnect?.({
528
- connectionId: record.connectionId,
529
- userId: record.userId,
530
- tenantId: record.tenantId,
531
- transport: "sse",
532
- ip: record.ip,
533
- userAgent: record.userAgent,
534
- connectedAt: record.connectedAt,
535
- durationMs: Date.now() - record.connectedAt.getTime(),
536
- ...reason !== void 0 ? { reason } : {}
537
- });
538
- } catch (error) {
539
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
540
- }
541
- }
542
- /** Replay the events a user missed after `lastEventId`. */
543
- getReplayEvents(userId, lastEventId) {
544
- return this.replayBuffer.since(userId, lastEventId);
545
- }
546
- /**
547
- * All SSE connections for a user — public accessor so external callers can
548
- * inspect or iterate without reaching into a private registry field.
549
- *
550
- * @param userId - The user whose active connections are returned.
551
- * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
552
- */
553
- connectionsForUser(userId) {
554
- return this.connections.byUser(userId, "sse");
555
- }
556
- /**
557
- * Look up a single connection by id.
558
- *
559
- * @param connectionId - The unique connection identifier.
560
- * @returns The `ConnectionRecord`, or `undefined` when not found.
561
- */
562
- getConnection(connectionId) {
563
- return this.connections.get(connectionId);
564
- }
565
- async emitToUser(userId, event, data) {
566
- const id = this.idGen.next();
567
- this.emitToUserLocal(userId, event, data, id);
568
- if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
569
- void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
570
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
571
- );
572
- }
573
- await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
574
- }
575
- async emitToTenant(tenantId, event, data) {
576
- const id = this.idGen.next();
577
- this.emitToTenantLocal(tenantId, event, data, id);
578
- await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
579
- }
580
- async emitToRoom(roomId, event, data) {
581
- const id = this.idGen.next();
582
- this.emitToRoomLocal(roomId, event, data, id);
583
- await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
584
- }
585
- async broadcast(event, data) {
586
- const id = this.idGen.next();
587
- this.broadcastLocal(event, data, id);
588
- await this.publish({ op: "broadcast", args: { event, data, id } });
589
- }
590
- async joinRoom(connectionId, roomId) {
591
- this.rooms.join(connectionId, roomId);
592
- }
593
- async leaveRoom(connectionId, roomId) {
594
- this.rooms.leave(connectionId, roomId);
595
- }
596
- /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
597
- async disconnect(connectionId, reason) {
598
- const record = this.connections.get(connectionId);
599
- if (record && record.transport === "sse") {
600
- await this.disconnectLocal(connectionId, reason);
601
- return;
602
- }
603
- await this.publish({ op: "disconnect", args: { connectionId, reason } });
604
- }
605
- /**
606
- * Deliver an event to a user's local SSE connections and update the replay buffer.
607
- *
608
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
609
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
610
- */
611
- emitToUserLocal(userId, event, data, id) {
612
- const message = this.buildMessage(id, event, data);
613
- this.replayBuffer.append(userId, message);
614
- for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
615
- }
616
- /**
617
- * Deliver an event to all local SSE connections for a tenant.
618
- *
619
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
620
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
621
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
622
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
623
- */
624
- emitToTenantLocal(tenantId, event, data, id) {
625
- const message = this.buildMessage(id, event, data);
626
- for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
627
- }
628
- /**
629
- * Deliver an event to all local SSE connections that joined the given room.
630
- *
631
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
632
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
633
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
634
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
635
- */
636
- emitToRoomLocal(roomId, event, data, id) {
637
- const message = this.buildMessage(id, event, data);
638
- for (const connectionId of this.rooms.members(roomId)) {
639
- const conn = this.connections.get(connectionId);
640
- if (conn && conn.transport === "sse") this.deliver(conn, message);
641
- }
642
- }
643
- /**
644
- * Deliver an event to all local SSE connections.
645
- *
646
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
647
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
648
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
649
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
650
- */
651
- broadcastLocal(event, data, id) {
652
- const message = this.buildMessage(id, event, data);
653
- for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
654
- }
655
- /**
656
- * Tear down a locally-owned SSE stream, then clean up (no re-publish).
657
- *
658
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
659
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
660
- */
661
- async disconnectLocal(connectionId, reason) {
662
- const record = this.connections.get(connectionId);
663
- if (!record || record.transport !== "sse") return;
664
- await this.unregisterConnection(connectionId, reason);
665
- record.close$?.next();
666
- record.close$?.complete();
667
- }
668
- buildMessage(id, event, data) {
669
- return { id, type: event, data };
670
- }
671
- /** Deliver to one connection, isolating failures so others still receive the event. */
672
- deliver(conn, message) {
673
- try {
674
- conn.subject?.next(message);
675
- } catch (error) {
676
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
677
- }
678
- }
679
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
680
- async publish(message) {
681
- try {
682
- await this.pubsub.publish({ ...message, origin: this.instanceId });
683
- } catch (error) {
684
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
685
- }
686
- }
687
- /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
688
- async evictBeyondLimit(userId) {
689
- const max = this.options.sse?.maxConnectionsPerUser;
690
- if (max === void 0 || max <= 0) return;
691
- let userConnections = this.connections.byUser(userId, "sse");
692
- while (userConnections.length > max) {
693
- const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
694
- await this.disconnectLocal(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
695
- userConnections = this.connections.byUser(userId, "sse");
696
- }
697
- }
698
- };
699
- SseTransport = __decorateClass([
700
- common.Injectable(),
701
- __decorateParam(0, common.Inject(ConnectionRegistry)),
702
- __decorateParam(1, common.Inject(RoomRegistry)),
703
- __decorateParam(2, common.Inject(EventReplayBuffer)),
704
- __decorateParam(3, common.Inject(EventIdGenerator)),
705
- __decorateParam(4, common.Inject(HeartbeatService)),
706
- __decorateParam(5, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
707
- __decorateParam(6, common.Inject(REALTIME_PUBSUB_TOKEN)),
708
- __decorateParam(7, common.Inject(REALTIME_HOOKS_TOKEN)),
709
- __decorateParam(8, common.Inject(REALTIME_OPTIONS_TOKEN)),
710
- __decorateParam(9, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
711
- __decorateParam(10, common.Optional()),
712
- __decorateParam(10, common.Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
713
- ], SseTransport);
714
-
715
- // src/server/transports/sse/sse-subscription.handler.ts
716
- function singleHeader(value) {
717
- return typeof value === "string" ? value : void 0;
718
- }
719
- function resolveIp(req) {
720
- const forwarded = req.headers["x-forwarded-for"];
721
- const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
722
- return candidate.trim() || req.ip || "unknown";
723
- }
724
- function normalizeHeaders(headers) {
725
- const out = /* @__PURE__ */ Object.create(null);
726
- for (const [key, value] of Object.entries(headers)) {
727
- out[key.toLowerCase()] = Array.isArray(value) ? value.join(",") : value;
728
- }
729
- return out;
730
- }
731
- function sanitizeQuery(query) {
732
- const out = /* @__PURE__ */ Object.create(null);
733
- for (const [key, value] of Object.entries(query)) {
734
- out[key] = typeof value === "string" ? value : void 0;
735
- }
736
- return out;
737
- }
738
- function buildAuthContext(req) {
739
- const headers = normalizeHeaders(req.headers);
740
- delete headers["authorization"];
741
- return {
742
- cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
743
- headers,
744
- query: sanitizeQuery(req.query),
745
- ip: resolveIp(req),
746
- userAgent: singleHeader(req.headers["user-agent"]),
747
- transport: "sse"
748
- };
749
- }
750
- function buildEstablishedEvent(connectionId, auth) {
751
- return {
752
- type: RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
753
- data: {
754
- connectionId,
755
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
756
- }
757
- };
758
- }
759
- function toMessageEvent(event) {
760
- return { id: event.id, type: event.event, data: event.data };
761
- }
762
- function buildMeta(record) {
763
- return {
764
- connectionId: record.connectionId,
765
- userId: record.userId,
766
- tenantId: record.tenantId,
767
- transport: "sse",
768
- ip: record.ip,
769
- userAgent: record.userAgent,
770
- connectedAt: record.connectedAt
771
- };
772
- }
773
- var SseSubscriptionHandler = class {
774
- constructor(transport, heartbeat, options, hooks, offlineDelivery) {
775
- this.transport = transport;
776
- this.heartbeat = heartbeat;
777
- this.options = options;
778
- this.hooks = hooks;
779
- this.offlineDelivery = offlineDelivery;
780
- }
781
- transport;
782
- heartbeat;
783
- options;
784
- hooks;
785
- offlineDelivery;
786
- logger = new common.Logger(SseSubscriptionHandler.name);
787
- /**
788
- * Handle an incoming SSE connection request end-to-end.
789
- *
790
- * Sets anti-buffering headers, authenticates the request, captures the offline-gap
791
- * before exposing the connection, then returns an Observable whose subscriber callback
792
- * wires the downstream listener BEFORE calling `registerConnection` — so a plain
793
- * `Subject` suffices and the replay buffer cannot grow unboundedly.
794
- *
795
- * @param req - The Express request (SSE GET).
796
- * @param res - The Express response (passthrough for header mutations and heartbeat writes).
797
- * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
798
- * @throws UnauthorizedException when authentication returns null.
799
- */
800
- async handle(req, res) {
801
- res.setHeader("Cache-Control", "no-cache, no-transform");
802
- res.setHeader("X-Accel-Buffering", "no");
803
- const context = buildAuthContext(req);
804
- const auth = await this.transport.authenticate(context);
805
- if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
806
- const resolvedTenantId = this.options.tenantResolver?.(auth) ?? auth.tenantId;
807
- const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
808
- const connectionId = crypto.randomUUID();
809
- const subject = new rxjs.Subject();
810
- const close$ = new rxjs.Subject();
811
- const lastEventId = singleHeader(req.headers["last-event-id"]);
812
- const replayEvents = lastEventId ? this.transport.getReplayEvents(resolvedAuth.userId, lastEventId) : [];
813
- const replay$ = replayEvents.length > 0 ? rxjs.of(...replayEvents) : rxjs.EMPTY;
814
- const ringBufferIds = new Set(replayEvents.map((e) => e.id ?? ""));
815
- const queueEvents = lastEventId && this.offlineDelivery ? await this.offlineDelivery.retrieve(resolvedAuth.userId, lastEventId, ringBufferIds) : [];
816
- const established$ = this.transport.emitConnectionEvent ? rxjs.of(buildEstablishedEvent(connectionId, resolvedAuth)) : rxjs.EMPTY;
817
- return this.buildStream({
818
- connectionId,
819
- resolvedAuth,
820
- ip: context.ip,
821
- userAgent: context.userAgent,
822
- res,
823
- subject,
824
- close$,
825
- established$,
826
- replay$,
827
- queueEvents
828
- });
829
- }
830
- /**
831
- * Build the live Observable using a subscribe-before-register pattern.
832
- *
833
- * The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
834
- * already has a listener when `registerConnection` runs. Any `subject.next()` that
835
- * occurs during or after registration goes directly to the subscriber — nothing is
836
- * buffered or retained, nothing is dropped, and ordering (established → replay →
837
- * queue → live) is preserved.
838
- */
839
- buildStream(p) {
840
- return new rxjs.Observable((subscriber) => {
841
- const inner = this.subscribePipeline(p, subscriber);
842
- if (!subscriber.closed && p.queueEvents.length > 0) {
843
- void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
844
- }
845
- this.activateConnection(p, subscriber);
846
- return () => inner.unsubscribe();
847
- });
848
- }
849
- /**
850
- * Wire the merged pipeline to the downstream subscriber with teardown.
851
- *
852
- * Subscribing first guarantees `subject` has a listener before registration can emit,
853
- * so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
854
- */
855
- subscribePipeline(p, subscriber) {
856
- const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
857
- const queueReplay$ = queueEvents.length > 0 ? rxjs.of(...queueEvents.map(toMessageEvent)) : rxjs.EMPTY;
858
- return rxjs.merge(established$, replay$, queueReplay$, subject).pipe(
859
- operators.takeUntil(close$),
860
- operators.catchError((error) => {
861
- this.fireHook(
862
- () => this.hooks?.onError?.({ connectionId, error, transport: "sse" })
863
- );
864
- return rxjs.EMPTY;
865
- }),
866
- operators.finalize(() => {
867
- this.heartbeat.stop(connectionId);
868
- void this.transport.unregisterConnection(connectionId);
869
- })
870
- ).subscribe(subscriber);
871
- }
872
- /**
873
- * Register the connection (after the subscriber is wired) and activate it on resolution.
874
- *
875
- * A registration failure routes to `onError` and errors the stream; a failure that
876
- * arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
877
- */
878
- activateConnection(p, subscriber) {
879
- const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
880
- this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
881
- this.fireHook(
882
- () => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
883
- );
884
- subscriber.error(err);
885
- });
886
- }
887
- /**
888
- * Complete the connection handshake once registration resolves.
889
- *
890
- * Registration is async and can resolve AFTER the downstream subscriber has already
891
- * torn down (client disconnected mid-handshake). When that happens `finalize` has
892
- * already stopped the heartbeat and unregistered, so re-firing onConnect or starting
893
- * a fresh heartbeat would leak the connection and write after close. Guard on
894
- * `subscriber.closed`: if closed, undo the late registration idempotently and return.
895
- */
896
- onRegistered(p, subscriber) {
897
- const { connectionId, res } = p;
898
- if (subscriber.closed) {
899
- this.heartbeat.stop(connectionId);
900
- void this.transport.unregisterConnection(connectionId);
901
- return;
902
- }
903
- const record = this.transport.getConnection(connectionId);
904
- if (record) {
905
- this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
906
- }
907
- const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
908
- this.heartbeat.start(connectionId, res, heartbeatMs);
909
- }
910
- /**
911
- * Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
912
- * so it never disrupts the connection lifecycle or live event delivery.
913
- *
914
- * @param invoke - A zero-arg function that calls the hook (handles optionality).
915
- */
916
- fireHook(invoke) {
917
- void Promise.resolve(invoke()).catch((err) => {
918
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
919
- });
920
- }
921
- };
922
- SseSubscriptionHandler = __decorateClass([
923
- common.Injectable(),
924
- __decorateParam(0, common.Inject(SseTransport)),
925
- __decorateParam(1, common.Inject(HeartbeatService)),
926
- __decorateParam(2, common.Inject(REALTIME_OPTIONS_TOKEN)),
927
- __decorateParam(3, common.Optional()),
928
- __decorateParam(3, common.Inject(REALTIME_HOOKS_TOKEN)),
929
- __decorateParam(4, common.Optional()),
930
- __decorateParam(4, common.Inject(OfflineQueueDeliveryService))
931
- ], SseSubscriptionHandler);
932
-
933
- // src/server/factories/sse-controller.factory.ts
934
- function createSseController(endpoint) {
935
- const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
936
- let DynamicSseController = class {
937
- // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
938
- // not emit `design:paramtypes` decorator metadata, so constructor params must
939
- // be resolved by token rather than by reflected type.
940
- constructor(handler) {
941
- this.handler = handler;
942
- }
943
- handler;
944
- subscribe(req, res) {
945
- return this.handler.handle(req, res);
946
- }
947
- };
948
- __decorateClass([
949
- common.Sse(ssePath),
950
- __decorateParam(0, common.Req()),
951
- __decorateParam(1, common.Res({ passthrough: true }))
952
- ], DynamicSseController.prototype, "subscribe", 1);
953
- DynamicSseController = __decorateClass([
954
- common.Controller(),
955
- __decorateParam(0, common.Inject(SseSubscriptionHandler))
956
- ], DynamicSseController);
957
- return DynamicSseController;
958
- }
959
- var InMemoryPubSub = class {
960
- handlers = /* @__PURE__ */ new Set();
961
- /**
962
- * Publish a message to all subscribed handlers.
963
- *
964
- * Delivery is deferred one microtask so a handler that enqueues further publishes
965
- * does not deepen the current call stack. One handler's failure does not block others.
966
- *
967
- * @param message - The pub/sub message to fan out.
968
- */
969
- async publish(message) {
970
- await Promise.resolve();
971
- for (const handler of this.handlers) {
972
- try {
973
- handler(message);
974
- } catch {
975
- }
976
- }
977
- }
978
- /**
979
- * Subscribe to pub/sub messages.
980
- *
981
- * @param handler - Called for every published message.
982
- * @returns An async unsubscribe function that removes this handler.
983
- */
984
- async subscribe(handler) {
985
- this.handlers.add(handler);
986
- return async () => {
987
- this.handlers.delete(handler);
988
- };
989
- }
990
- };
991
- InMemoryPubSub = __decorateClass([
992
- common.Injectable()
993
- ], InMemoryPubSub);
994
- var RealtimeService = class {
995
- constructor(transport) {
996
- this.transport = transport;
997
- }
998
- transport;
999
- /**
1000
- * Send to all of a user's connections (across devices/tabs).
1001
- *
1002
- * @example
1003
- * ```ts
1004
- * await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
1005
- * ```
1006
- */
1007
- emitToUser(userId, event, data) {
1008
- return this.transport.emitToUser(userId, event, data);
1009
- }
1010
- /** Send to every connection in a tenant. */
1011
- emitToTenant(tenantId, event, data) {
1012
- return this.transport.emitToTenant(tenantId, event, data);
1013
- }
1014
- /**
1015
- * Send to a logical room. Use the prefix convention (`user:{id}`,
1016
- * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
1017
- */
1018
- emitToRoom(roomId, event, data) {
1019
- return this.transport.emitToRoom(roomId, event, data);
1020
- }
1021
- /** Send to every connected client. Use sparingly. */
1022
- broadcast(event, data) {
1023
- return this.transport.broadcast(event, data);
1024
- }
1025
- /** Add a specific connection to a room. */
1026
- joinRoom(connectionId, roomId) {
1027
- return this.transport.joinRoom(connectionId, roomId);
1028
- }
1029
- /** Remove a specific connection from a room. */
1030
- leaveRoom(connectionId, roomId) {
1031
- return this.transport.leaveRoom(connectionId, roomId);
1032
- }
1033
- /** Force-disconnect a specific connection (e.g. on auth revocation). */
1034
- disconnect(connectionId, reason) {
1035
- return this.transport.disconnect(connectionId, reason);
1036
- }
1037
- };
1038
- RealtimeService = __decorateClass([
1039
- common.Injectable(),
1040
- __decorateParam(0, common.Inject(REALTIME_TRANSPORT_TOKEN))
1041
- ], RealtimeService);
1042
- function resolvePolicy(raw) {
1043
- return {
1044
- intervalSeconds: raw?.intervalSeconds ?? 300,
1045
- onFailure: raw?.onFailure ?? "disconnect",
1046
- cacheTtlMs: raw?.cacheTtlMs ?? 6e4
1047
- };
1048
- }
1049
- var ReauthenticationService = class {
1050
- constructor(connections, realtime, auth, options, hooks) {
1051
- this.connections = connections;
1052
- this.realtime = realtime;
1053
- this.auth = auth;
1054
- this.hooks = hooks;
1055
- this.policy = resolvePolicy(options.reauthenticationPolicy);
1056
- }
1057
- connections;
1058
- realtime;
1059
- auth;
1060
- hooks;
1061
- logger = new common.Logger(ReauthenticationService.name);
1062
- timer = null;
1063
- /** connectionId → epoch-ms timestamp of last successful revalidation. */
1064
- positiveCache = /* @__PURE__ */ new Map();
1065
- policy;
1066
- /**
1067
- * Schedule the periodic revalidation cycle.
1068
- *
1069
- * The timer is unref'd so it never keeps the process alive on its own.
1070
- * When the authenticator does not implement `revalidate`, the service stays
1071
- * idle and emits an informative log.
1072
- */
1073
- onModuleInit() {
1074
- if (!this.auth.revalidate) {
1075
- this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
1076
- return;
1077
- }
1078
- this.timer = setInterval(() => void this.runCycle(), this.policy.intervalSeconds * 1e3);
1079
- this.timer.unref();
1080
- this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1081
- }
1082
- /**
1083
- * Clear the timer and the positive cache.
1084
- *
1085
- * Called by NestJS on graceful shutdown to prevent leaks.
1086
- */
1087
- onApplicationShutdown() {
1088
- if (this.timer) {
1089
- clearInterval(this.timer);
1090
- this.timer = null;
1091
- }
1092
- this.positiveCache.clear();
1093
- }
1094
- /**
1095
- * Run one revalidation cycle over all active SSE connections.
1096
- *
1097
- * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1098
- * refreshes the cache. A negative result (or a thrown error) invokes the configured
1099
- * `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
1100
- *
1101
- * Exposed as public for test access.
1102
- */
1103
- async runCycle() {
1104
- const now = Date.now();
1105
- for (const conn of this.connections.allByTransport("sse")) {
1106
- try {
1107
- const lastValid = this.positiveCache.get(conn.connectionId);
1108
- if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
1109
- const originalAuth = {
1110
- userId: conn.originalAuth.userId,
1111
- ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1112
- ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
1113
- };
1114
- const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
1115
- if (rawResult === true) {
1116
- this.positiveCache.set(conn.connectionId, now);
1117
- continue;
1118
- }
1119
- await this.handleFailure(conn);
1120
- } catch (err) {
1121
- this.logger.warn(
1122
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1123
- );
1124
- await this.handleFailure(conn);
1125
- }
1126
- }
1127
- }
1128
- /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1129
- async handleFailure(conn) {
1130
- this.positiveCache.delete(conn.connectionId);
1131
- if (this.policy.onFailure === "event") {
1132
- await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1133
- reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1134
- });
1135
- }
1136
- void Promise.resolve(
1137
- this.hooks?.onReauthenticationFailed?.({
1138
- connectionId: conn.connectionId,
1139
- userId: conn.userId,
1140
- tenantId: conn.tenantId,
1141
- transport: "sse",
1142
- ip: conn.ip,
1143
- userAgent: conn.userAgent,
1144
- connectedAt: conn.connectedAt
1145
- })
1146
- ).catch((err) => {
1147
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1148
- });
1149
- await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1150
- }
1151
- };
1152
- ReauthenticationService = __decorateClass([
1153
- common.Injectable(),
1154
- __decorateParam(0, common.Inject(ConnectionRegistry)),
1155
- __decorateParam(1, common.Inject(RealtimeService)),
1156
- __decorateParam(2, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
1157
- __decorateParam(3, common.Inject(REALTIME_OPTIONS_TOKEN)),
1158
- __decorateParam(4, common.Optional()),
1159
- __decorateParam(4, common.Inject(REALTIME_HOOKS_TOKEN))
1160
- ], ReauthenticationService);
1161
-
1162
- // src/server/composition/realtime-module.factory.ts
1163
- var EXPORTED_TOKENS = [
1164
- RealtimeService,
1165
- ConnectionRegistry,
1166
- REALTIME_OPTIONS_TOKEN,
1167
- REALTIME_INSTANCE_ID_TOKEN,
1168
- REALTIME_AUTHENTICATOR_TOKEN,
1169
- REALTIME_PUBSUB_TOKEN,
1170
- REALTIME_HOOKS_TOKEN,
1171
- REALTIME_OFFLINE_QUEUE_TOKEN,
1172
- REALTIME_PRESENCE_TOKEN,
1173
- REALTIME_TRANSPORT_TOKEN
1174
- ];
1175
- var SHARED_SERVICES = [
1176
- ConnectionRegistry,
1177
- RoomRegistry,
1178
- EventIdGenerator,
1179
- EventReplayBuffer,
1180
- HeartbeatService,
1181
- RealtimeService,
1182
- ReauthenticationService,
1183
- OfflineQueueDeliveryService
1184
- ];
1185
- function assertModeSupported(wiring, mode, moduleName) {
1186
- if (wiring.modes.includes(mode)) return;
1187
- const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
1188
- throw new Error(
1189
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
1190
- );
1191
- }
1192
- function warnIfSingleInstance(pubsub, transport, logger) {
1193
- if (transport === "websocket") return;
1194
- if (!pubsub && process.env["NODE_ENV"] === "production") {
1195
- logger.warn(
1196
- "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1197
- );
1198
- }
1199
- }
1200
- function buildCommonProviders(resolved, instanceId) {
1201
- return [
1202
- { provide: REALTIME_OPTIONS_TOKEN, useValue: resolved },
1203
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
1204
- { provide: REALTIME_AUTHENTICATOR_TOKEN, useValue: resolved.authenticator },
1205
- { provide: REALTIME_PUBSUB_TOKEN, useValue: resolved.pubsub ?? new InMemoryPubSub() },
1206
- { provide: REALTIME_HOOKS_TOKEN, useValue: resolved.hooks ?? {} },
1207
- { provide: REALTIME_OFFLINE_QUEUE_TOKEN, useValue: resolved.offlineQueue },
1208
- { provide: REALTIME_PRESENCE_TOKEN, useValue: resolved.presence },
1209
- ...SHARED_SERVICES
1210
- ];
1211
- }
1212
- function composeForRoot(moduleClass, wiring, logger, options) {
1213
- validateOptions(options);
1214
- assertModeSupported(wiring, options.transport, moduleClass.name);
1215
- const resolved = applyDefaults(options);
1216
- const instanceId = crypto.randomUUID();
1217
- warnIfSingleInstance(resolved.pubsub, resolved.transport, logger);
1218
- const { providers, endpoints, gateways } = wiring.build(resolved);
1219
- logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
1220
- return {
1221
- module: moduleClass,
1222
- controllers: endpoints.map((endpoint) => createSseController(endpoint)),
1223
- providers: [...buildCommonProviders(resolved, instanceId), ...providers, ...gateways],
1224
- exports: EXPORTED_TOKENS
1225
- };
1226
- }
1227
- function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1228
- if (!raw) {
1229
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1230
- }
1231
- validateOptions(raw);
1232
- if (raw.transport !== declaredMode) {
1233
- throw new Error(
1234
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
1235
- );
1236
- }
1237
- const resolved = applyDefaults(raw);
1238
- logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
1239
- return resolved;
1240
- }
1241
- function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1242
- const moduleName = moduleClass.name;
1243
- const patterns = [
1244
- asyncOptions.useFactory,
1245
- asyncOptions.useClass,
1246
- asyncOptions.useExisting
1247
- ].filter((pattern) => pattern !== void 0);
1248
- if (patterns.length !== 1) {
1249
- throw new Error(
1250
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1251
- );
1252
- }
1253
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
1254
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1255
- const instanceId = crypto.randomUUID();
1256
- const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
1257
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
1258
- provide: REALTIME_OPTIONS_TOKEN,
1259
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
1260
- inject: [...asyncOptions.inject ?? []]
1261
- } : {
1262
- provide: REALTIME_OPTIONS_TOKEN,
1263
- useFactory: async (factory) => resolve(
1264
- await factory.createRealtimeOptions(),
1265
- "createRealtimeOptions"
1266
- ),
1267
- inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
1268
- };
1269
- const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1270
- const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
1271
- const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
1272
- return {
1273
- module: moduleClass,
1274
- imports: asyncOptions.imports ?? [],
1275
- controllers,
1276
- providers: [
1277
- ...factoryClassProvider,
1278
- resolvedOptionsProvider,
1279
- fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
1280
- fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
1281
- warnIfSingleInstance(opts.pubsub, opts.transport, logger);
1282
- return opts.pubsub ?? new InMemoryPubSub();
1283
- }),
1284
- fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
1285
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
1286
- fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
1287
- fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
1288
- ...SHARED_SERVICES,
1289
- ...transportProviders,
1290
- ...asyncOptions.extraProviders ?? []
1291
- ],
1292
- exports: EXPORTED_TOKENS
1293
- };
1294
- }
1295
- var RealtimePubSubSubscriber = class {
1296
- constructor(pubsub, instanceId, sse) {
1297
- this.pubsub = pubsub;
1298
- this.instanceId = instanceId;
1299
- this.sse = sse;
1300
- }
1301
- pubsub;
1302
- instanceId;
1303
- sse;
1304
- logger = new common.Logger(RealtimePubSubSubscriber.name);
1305
- unsubscribe = null;
1306
- async onModuleInit() {
1307
- try {
1308
- this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1309
- } catch (err) {
1310
- this.logger.warn(
1311
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1312
- );
1313
- }
1314
- }
1315
- async onApplicationShutdown() {
1316
- if (this.unsubscribe) {
1317
- try {
1318
- await this.unsubscribe();
1319
- } catch (err) {
1320
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1321
- }
1322
- this.unsubscribe = null;
1323
- }
1324
- }
1325
- handle(msg) {
1326
- if (msg.origin === this.instanceId) return;
1327
- try {
1328
- switch (msg.op) {
1329
- case "emitToUser": {
1330
- const a = msg.args;
1331
- this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
1332
- break;
1333
- }
1334
- case "emitToTenant": {
1335
- const a = msg.args;
1336
- this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
1337
- break;
1338
- }
1339
- case "emitToRoom": {
1340
- const a = msg.args;
1341
- this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
1342
- break;
1343
- }
1344
- case "broadcast": {
1345
- const a = msg.args;
1346
- this.sse.broadcastLocal(a.event, a.data, a.id);
1347
- break;
1348
- }
1349
- case "disconnect": {
1350
- const a = msg.args;
1351
- void this.sse.disconnectLocal(a.connectionId, a.reason);
1352
- break;
1353
- }
1354
- default: {
1355
- const exhaustive = msg.op;
1356
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
1357
- }
1358
- }
1359
- } catch (err) {
1360
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1361
- }
1362
- }
1363
- };
1364
- RealtimePubSubSubscriber = __decorateClass([
1365
- common.Injectable(),
1366
- __decorateParam(0, common.Inject(REALTIME_PUBSUB_TOKEN)),
1367
- __decorateParam(1, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
1368
- __decorateParam(2, common.Inject(SseTransport))
1369
- ], RealtimePubSubSubscriber);
1370
27
  var CONNECTION_ROOM_PREFIX = "connection";
1371
28
  exports.WebSocketTransport = class WebSocketTransport {
1372
29
  constructor(connections, rooms, auth, hooks, options) {
@@ -1451,11 +108,11 @@ exports.WebSocketTransport = class WebSocketTransport {
1451
108
  close$: null,
1452
109
  originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1453
110
  });
1454
- await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
1455
- if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
+ await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
112
+ if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1456
113
  await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
1457
- this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
1458
- if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
114
+ this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
115
+ if (auth.tenantId) this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1459
116
  await this.evictBeyondLimit(auth.userId);
1460
117
  await this.hooks.onConnect?.({
1461
118
  connectionId: socket.id,
@@ -1502,7 +159,7 @@ exports.WebSocketTransport = class WebSocketTransport {
1502
159
  * @param data - Payload forwarded to all matching connections.
1503
160
  */
1504
161
  async emitToUser(userId, event, data) {
1505
- this.server?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
162
+ this.server?.to(`${internal.ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
1506
163
  }
1507
164
  /**
1508
165
  * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
@@ -1512,7 +169,7 @@ exports.WebSocketTransport = class WebSocketTransport {
1512
169
  * @param data - Payload forwarded to all matching connections.
1513
170
  */
1514
171
  async emitToTenant(tenantId, event, data) {
1515
- this.server?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
172
+ this.server?.to(`${internal.ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
1516
173
  }
1517
174
  /**
1518
175
  * Send an event to every connection in an arbitrary room.
@@ -1590,22 +247,22 @@ exports.WebSocketTransport = class WebSocketTransport {
1590
247
  let userConnections = this.connections.byUser(userId, "websocket");
1591
248
  while (userConnections.length > max) {
1592
249
  const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
1593
- await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1594
- await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
250
+ await this.disconnect(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
251
+ await this.unregisterSocket(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1595
252
  userConnections = this.connections.byUser(userId, "websocket");
1596
253
  }
1597
254
  }
1598
255
  };
1599
256
  exports.WebSocketTransport = __decorateClass([
1600
257
  common.Injectable(),
1601
- __decorateParam(0, common.Inject(ConnectionRegistry)),
1602
- __decorateParam(1, common.Inject(RoomRegistry)),
1603
- __decorateParam(2, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
1604
- __decorateParam(3, common.Inject(REALTIME_HOOKS_TOKEN)),
1605
- __decorateParam(4, common.Inject(REALTIME_OPTIONS_TOKEN))
258
+ __decorateParam(0, common.Inject(internal.ConnectionRegistry)),
259
+ __decorateParam(1, common.Inject(internal.RoomRegistry)),
260
+ __decorateParam(2, common.Inject(internal.REALTIME_AUTHENTICATOR_TOKEN)),
261
+ __decorateParam(3, common.Inject(internal.REALTIME_HOOKS_TOKEN)),
262
+ __decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
1606
263
  ], exports.WebSocketTransport);
1607
264
 
1608
- // src/server/transports/composite/composite.transport.ts
265
+ // src/websocket/transports/composite/composite.transport.ts
1609
266
  exports.CompositeTransport = class CompositeTransport {
1610
267
  constructor(sse, ws) {
1611
268
  this.sse = sse;
@@ -1724,7 +381,7 @@ exports.CompositeTransport = class CompositeTransport {
1724
381
  };
1725
382
  exports.CompositeTransport = __decorateClass([
1726
383
  common.Injectable(),
1727
- __decorateParam(0, common.Inject(SseTransport)),
384
+ __decorateParam(0, common.Inject(internal.SseTransport)),
1728
385
  __decorateParam(1, common.Inject(exports.WebSocketTransport))
1729
386
  ], exports.CompositeTransport);
1730
387
  function firstQueryValue(value) {
@@ -1775,7 +432,7 @@ exports.RealtimeGateway = class RealtimeGateway {
1775
432
  const ticket = firstQueryValue(query["ticket"]);
1776
433
  if (ticket !== void 0) query["ticket"] = ticket;
1777
434
  const ctx = {
1778
- cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
435
+ cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
1779
436
  headers,
1780
437
  query,
1781
438
  ip: handshake.address,
@@ -1789,7 +446,7 @@ exports.RealtimeGateway = class RealtimeGateway {
1789
446
  }
1790
447
  await this.transport.registerSocket(socket, auth);
1791
448
  if (this.options.websocket?.emitConnectionEvent !== false) {
1792
- socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
449
+ socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
1793
450
  connectionId: socket.id,
1794
451
  traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1795
452
  });
@@ -1827,7 +484,7 @@ exports.RealtimeGateway = __decorateClass([
1827
484
  cors: { origin: false }
1828
485
  }),
1829
486
  __decorateParam(0, common.Inject(exports.WebSocketTransport)),
1830
- __decorateParam(1, common.Inject(REALTIME_OPTIONS_TOKEN))
487
+ __decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
1831
488
  ], exports.RealtimeGateway);
1832
489
 
1833
490
  // src/websocket/websocket-wiring.ts
@@ -1839,7 +496,7 @@ var webSocketWiring = {
1839
496
  return {
1840
497
  providers: [
1841
498
  exports.WebSocketTransport,
1842
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
499
+ { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
1843
500
  ],
1844
501
  endpoints: [],
1845
502
  gateways: [exports.RealtimeGateway]
@@ -1847,12 +504,12 @@ var webSocketWiring = {
1847
504
  }
1848
505
  return {
1849
506
  providers: [
1850
- SseTransport,
507
+ internal.SseTransport,
1851
508
  exports.WebSocketTransport,
1852
509
  exports.CompositeTransport,
1853
- SseSubscriptionHandler,
1854
- RealtimePubSubSubscriber,
1855
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
510
+ internal.SseSubscriptionHandler,
511
+ internal.RealtimePubSubSubscriber,
512
+ { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
1856
513
  ],
1857
514
  endpoints: [resolved.sse.endpoint],
1858
515
  gateways: [exports.RealtimeGateway]
@@ -1864,22 +521,22 @@ var webSocketWiring = {
1864
521
  providers: [
1865
522
  exports.WebSocketTransport,
1866
523
  exports.RealtimeGateway,
1867
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
524
+ { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
1868
525
  ],
1869
526
  controllers: []
1870
527
  };
1871
528
  }
1872
529
  return {
1873
530
  providers: [
1874
- SseTransport,
1875
- SseSubscriptionHandler,
531
+ internal.SseTransport,
532
+ internal.SseSubscriptionHandler,
1876
533
  exports.WebSocketTransport,
1877
534
  exports.CompositeTransport,
1878
535
  exports.RealtimeGateway,
1879
- RealtimePubSubSubscriber,
1880
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
536
+ internal.RealtimePubSubSubscriber,
537
+ { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
1881
538
  ],
1882
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
539
+ controllers: [internal.createSseController(DEFAULT_ASYNC_ENDPOINT)]
1883
540
  };
1884
541
  }
1885
542
  };
@@ -1899,7 +556,7 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
1899
556
  * ```
1900
557
  */
1901
558
  static forRoot(options) {
1902
- return composeForRoot(
559
+ return internal.composeForRoot(
1903
560
  exports.BymaxRealtimeWebSocketModule,
1904
561
  webSocketWiring,
1905
562
  exports.BymaxRealtimeWebSocketModule.logger,
@@ -1930,7 +587,7 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
1930
587
  * ```
1931
588
  */
1932
589
  static forRootAsync(asyncOptions) {
1933
- return composeForRootAsync(
590
+ return internal.composeForRootAsync(
1934
591
  exports.BymaxRealtimeWebSocketModule,
1935
592
  webSocketWiring,
1936
593
  exports.BymaxRealtimeWebSocketModule.logger,
@@ -1948,7 +605,7 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
1948
605
  options;
1949
606
  constructor(app) {
1950
607
  super(app);
1951
- this.options = app.get(REALTIME_OPTIONS_TOKEN);
608
+ this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
1952
609
  }
1953
610
  /**
1954
611
  * Bind the gateway to `websocket.namespace` when configured.