@bymax-one/nest-realtime 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2276 +1,78 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
- var common = require('@nestjs/common');
5
- var rxjs = require('rxjs');
6
- var operators = require('rxjs/operators');
7
- var websockets = require('@nestjs/websockets');
8
- var platformSocket_io = require('@nestjs/platform-socket.io');
3
+ var internal = require('@bymax-one/nest-realtime/internal');
9
4
 
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
14
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
15
- }) : x)(function(x) {
16
- if (typeof require !== "undefined") return require.apply(this, arguments);
17
- throw Error('Dynamic require of "' + x + '" is not supported');
18
- });
19
- var __decorateClass = (decorators, target, key, kind) => {
20
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
- if (decorator = decorators[i])
23
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
- if (kind && result) __defProp(target, key, result);
25
- return result;
26
- };
27
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
- 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
- INVALID_TICKET: "REALTIME_INVALID_TICKET",
38
- PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
39
- PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
40
- REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
41
- };
42
-
43
- // src/server/config/default-options.ts
44
- var DEFAULT_SSE = {
45
- endpoint: "/realtime/sse",
46
- heartbeatMs: 3e4,
47
- replayBufferSize: 100,
48
- maxConnectionsPerUser: 5,
49
- emitConnectionEvent: true
50
- };
51
- function applyDefaults(options) {
52
- return Object.freeze({
53
- ...options,
54
- sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
55
- });
56
- }
57
- var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
58
- function validateOptions(options) {
59
- if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
60
- throw new Error(
61
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
62
- );
63
- }
64
- if (!options.authenticator) {
65
- throw new Error(
66
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
67
- );
68
- }
69
- if (typeof options.authenticator.authenticate !== "function") {
70
- throw new Error(
71
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
72
- );
73
- }
74
- validateSseOptions(options);
75
- validateReauthPolicy(options);
76
- }
77
- function validateReauthPolicy(options) {
78
- const policy = options.reauthenticationPolicy;
79
- if (policy?.cacheTtlMs !== void 0 && policy.intervalSeconds !== void 0 && policy.cacheTtlMs > policy.intervalSeconds * 1e3) {
80
- common.Logger.warn(
81
- `[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`,
82
- "BymaxRealtimeModule"
83
- );
84
- }
85
- }
86
- function validateSseOptions(options) {
87
- const sse = options.sse;
88
- if (sse?.heartbeatMs !== void 0 && sse.heartbeatMs <= 0) {
89
- throw new Error(
90
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be > 0`
91
- );
92
- }
93
- if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
94
- throw new Error(
95
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
96
- );
97
- }
98
- if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
99
- throw new Error(
100
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
101
- );
102
- }
103
- }
104
-
105
- // src/server/constants/injection-tokens.constants.ts
106
- var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
107
- var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
108
- var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
109
- var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
110
- var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
111
- var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
112
- var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
113
- var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
114
- var DEFAULT_HEARTBEAT_MS = 3e4;
115
- var RETRIEVE_LIMIT = 200;
116
- var OfflineQueueDeliveryService = class {
117
- constructor(storage) {
118
- this.storage = storage;
119
- }
120
- storage;
121
- logger = new common.Logger(OfflineQueueDeliveryService.name);
122
- /**
123
- * Return events for `userId` that arrived after `lastEventId` and are NOT
124
- * already covered by `ringBufferIds` (already replayed from in-memory buffer).
125
- *
126
- * Retrieval does NOT acknowledge: the durable queue is pruned only after the events
127
- * have been emitted to a live subscriber via {@link acknowledge}. This guarantees
128
- * at-least-once delivery — events that never reach the client are never lost.
129
- *
130
- * @param userId - The reconnecting user.
131
- * @param lastEventId - The `Last-Event-ID` header value.
132
- * @param ringBufferIds - Set of event ids already replayed from the ring buffer.
133
- * @returns Gap events, or an empty array when no offline queue is configured.
134
- */
135
- async retrieve(userId, lastEventId, ringBufferIds) {
136
- if (!this.storage) return [];
137
- let events;
138
- try {
139
- events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
140
- } catch (err) {
141
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
142
- return [];
143
- }
144
- if (events.length === RETRIEVE_LIMIT) {
145
- this.logger.warn(
146
- `Offline queue retrieve hit the ${RETRIEVE_LIMIT}-event limit for user; older gap events may be dropped.`
147
- );
148
- }
149
- return events.filter((e) => !ringBufferIds.has(e.id));
150
- }
151
- /**
152
- * Acknowledge delivered offline events so the storage backend can prune them.
153
- *
154
- * At-least-once contract: call this ONLY after the events have been emitted to a
155
- * still-open subscriber. Acknowledging before emission would permanently drop events
156
- * that never reached the client. A failure is swallowed (logged) so a transient
157
- * storage error never disrupts delivery; the events simply redeliver on reconnect.
158
- *
159
- * @param userId - The user whose queue is acknowledged.
160
- * @param events - The delivered gap events; the last id is the prune watermark.
161
- */
162
- async acknowledge(userId, events) {
163
- if (!this.storage || events.length === 0) return;
164
- const lastId = events[events.length - 1].id;
165
- try {
166
- await this.storage.acknowledge(userId, lastId);
167
- } catch (err) {
168
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
169
- }
170
- }
171
- };
172
- OfflineQueueDeliveryService = __decorateClass([
173
- common.Injectable(),
174
- __decorateParam(0, common.Optional()),
175
- __decorateParam(0, common.Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
176
- ], OfflineQueueDeliveryService);
177
-
178
- // src/shared/constants/reserved-events.constants.ts
179
- var RESERVED_EVENT_NAMES = {
180
- CONNECTION_ESTABLISHED: "connection:established",
181
- CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed",
182
- CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring",
183
- ROOM_JOINED: "room:joined",
184
- ROOM_LEFT: "room:left",
185
- ERROR: "error"
186
- };
187
-
188
- // src/server/utils/parse-cookie-header.ts
189
- function parseCookieHeader(cookieHeader) {
190
- const out = /* @__PURE__ */ Object.create(null);
191
- if (!cookieHeader) return out;
192
- for (const pair of cookieHeader.split(";")) {
193
- const idx = pair.indexOf("=");
194
- if (idx === -1) continue;
195
- const name = pair.slice(0, idx).trim();
196
- const value = pair.slice(idx + 1).trim();
197
- if (name) out[name] = value;
198
- }
199
- return out;
200
- }
201
- exports.ConnectionRegistry = class ConnectionRegistry {
202
- byId = /* @__PURE__ */ new Map();
203
- byUserId = /* @__PURE__ */ new Map();
204
- byTenantId = /* @__PURE__ */ new Map();
205
- /** Register a connection and index it by user and tenant. */
206
- register(record) {
207
- this.byId.set(record.connectionId, record);
208
- this.addToSetMap(this.byUserId, record.userId, record.connectionId);
209
- if (record.tenantId !== void 0) {
210
- this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
211
- }
212
- }
213
- /** Remove a connection from every index. Returns the removed record, if any. */
214
- unregister(connectionId) {
215
- const record = this.byId.get(connectionId);
216
- if (!record) return void 0;
217
- this.byId.delete(connectionId);
218
- this.removeFromSetMap(this.byUserId, record.userId, connectionId);
219
- if (record.tenantId !== void 0) {
220
- this.removeFromSetMap(this.byTenantId, record.tenantId, connectionId);
221
- }
222
- return record;
223
- }
224
- /** Look up a single connection by id. */
225
- get(connectionId) {
226
- return this.byId.get(connectionId);
227
- }
228
- /** All connections of a user, optionally filtered by transport. */
229
- byUser(userId, transport) {
230
- return this.resolve(this.byUserId.get(userId), transport);
231
- }
232
- /** All connections of a tenant, optionally filtered by transport. */
233
- byTenant(tenantId, transport) {
234
- return this.resolve(this.byTenantId.get(tenantId), transport);
235
- }
236
- /** All connections of a given transport. */
237
- allByTransport(transport) {
238
- return Array.from(this.byId.values()).filter((record) => record.transport === transport);
239
- }
240
- /** Total number of active connections. */
241
- count() {
242
- return this.byId.size;
243
- }
244
- /** Number of distinct users currently connected. */
245
- countUsers() {
246
- return this.byUserId.size;
247
- }
248
- resolve(ids, transport) {
249
- if (!ids) return [];
250
- const out = [];
251
- for (const id of ids) {
252
- const record = this.byId.get(id);
253
- if (record && (transport === void 0 || record.transport === transport)) {
254
- out.push(record);
255
- }
256
- }
257
- return out;
258
- }
259
- addToSetMap(map, key, value) {
260
- const existing = map.get(key);
261
- if (existing) existing.add(value);
262
- else map.set(key, /* @__PURE__ */ new Set([value]));
263
- }
264
- removeFromSetMap(map, key, value) {
265
- const existing = map.get(key);
266
- if (!existing) return;
267
- existing.delete(value);
268
- if (existing.size === 0) map.delete(key);
269
- }
270
- };
271
- exports.ConnectionRegistry = __decorateClass([
272
- common.Injectable()
273
- ], exports.ConnectionRegistry);
274
- var COUNTER_WIDTH = 6;
275
- var EventIdGenerator = class {
276
- lastMs = 0;
277
- counter = 0;
278
- /** Produce the next monotonic event id. */
279
- next() {
280
- const now = Date.now();
281
- if (now === this.lastMs) {
282
- this.counter += 1;
283
- } else {
284
- this.lastMs = now;
285
- this.counter = 1;
286
- }
287
- return `${now}-${String(this.counter).padStart(COUNTER_WIDTH, "0")}`;
288
- }
289
- };
290
- EventIdGenerator = __decorateClass([
291
- common.Injectable()
292
- ], EventIdGenerator);
293
- var RoomRegistry = class {
294
- rooms = /* @__PURE__ */ new Map();
295
- connectionRooms = /* @__PURE__ */ new Map();
296
- /** Join a connection to a room (idempotent). */
297
- join(connectionId, roomId) {
298
- const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
299
- room.add(connectionId);
300
- this.rooms.set(roomId, room);
301
- const conn = this.connectionRooms.get(connectionId) ?? /* @__PURE__ */ new Set();
302
- conn.add(roomId);
303
- this.connectionRooms.set(connectionId, conn);
304
- }
305
- /** Remove a connection from a room (idempotent); prunes empty entries. */
306
- leave(connectionId, roomId) {
307
- const room = this.rooms.get(roomId);
308
- if (room) {
309
- room.delete(connectionId);
310
- if (room.size === 0) this.rooms.delete(roomId);
311
- }
312
- const conn = this.connectionRooms.get(connectionId);
313
- if (conn) {
314
- conn.delete(roomId);
315
- if (conn.size === 0) this.connectionRooms.delete(connectionId);
316
- }
317
- }
318
- /** Snapshot of a room's members — safe to iterate while membership mutates. */
319
- members(roomId) {
320
- const set = this.rooms.get(roomId);
321
- return set ? Array.from(set) : [];
322
- }
323
- /** Snapshot of the rooms a connection currently belongs to. */
324
- roomsOf(connectionId) {
325
- const set = this.connectionRooms.get(connectionId);
326
- return set ? Array.from(set) : [];
327
- }
328
- /** Remove a connection from every room (called on disconnect). */
329
- leaveAll(connectionId) {
330
- const rooms = this.connectionRooms.get(connectionId);
331
- if (!rooms) return;
332
- for (const roomId of rooms) {
333
- const set = this.rooms.get(roomId);
334
- if (set) {
335
- set.delete(connectionId);
336
- if (set.size === 0) this.rooms.delete(roomId);
337
- }
338
- }
339
- this.connectionRooms.delete(connectionId);
340
- }
341
- /** Total number of distinct rooms. */
342
- countRooms() {
343
- return this.rooms.size;
344
- }
345
- };
346
- RoomRegistry = __decorateClass([
347
- common.Injectable()
348
- ], RoomRegistry);
349
-
350
- // src/shared/constants/room-prefixes.constants.ts
351
- var ROOM_PREFIXES = {
352
- USER: "user",
353
- TENANT: "tenant",
354
- RESOURCE: "resource"
355
- };
356
-
357
- // src/server/utils/compose-room-id.ts
358
- function composeRoomId(prefix, ...parts) {
359
- return [ROOM_PREFIXES[prefix], ...parts].join(":");
360
- }
361
- var DEFAULT_REPLAY_BUFFER_SIZE = 100;
362
- var EventReplayBuffer = class {
363
- constructor(opts) {
364
- this.opts = opts;
365
- }
366
- opts;
367
- buffers = /* @__PURE__ */ new Map();
368
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
369
- append(userId, event) {
370
- const buf = this.buffers.get(userId) ?? [];
371
- buf.push(event);
372
- const cap = this.opts.sse?.replayBufferSize ?? DEFAULT_REPLAY_BUFFER_SIZE;
373
- if (buf.length > cap) buf.shift();
374
- this.buffers.set(userId, buf);
375
- }
376
- /**
377
- * Return the events emitted after `lastEventId`.
378
- *
379
- * Returns an empty array when the user has no buffer, or when `lastEventId` is
380
- * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
381
- */
382
- since(userId, lastEventId) {
383
- const buf = this.buffers.get(userId);
384
- if (!buf) return [];
385
- const idx = buf.findIndex((event) => event.id === lastEventId);
386
- if (idx === -1) return [];
387
- return buf.slice(idx + 1);
388
- }
389
- /** Number of events currently buffered for a user (diagnostics). */
390
- size(userId) {
391
- return this.buffers.get(userId)?.length ?? 0;
392
- }
393
- };
394
- EventReplayBuffer = __decorateClass([
395
- common.Injectable(),
396
- __decorateParam(0, common.Inject(REALTIME_OPTIONS_TOKEN))
397
- ], EventReplayBuffer);
398
- var KEEPALIVE_COMMENT = ": keepalive\n\n";
399
- var HEARTBEAT_MIN_MS = 5e3;
400
- var HEARTBEAT_MAX_MS = 9e4;
401
- var HeartbeatService = class {
402
- timers = /* @__PURE__ */ new Map();
403
- /**
404
- * Start writing keepalives for a connection every `intervalMs`.
405
- *
406
- * @param connectionId - Unique connection identifier used to track the timer.
407
- * @param res - The writable response stream (or any object with a `write` method).
408
- * @param intervalMs - Keepalive interval in milliseconds; must be within
409
- * `[5_000, 90_000]`.
410
- * @throws {Error} When `intervalMs` is outside the valid range.
411
- */
412
- start(connectionId, res, intervalMs) {
413
- if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
414
- throw new Error(
415
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
416
- );
417
- }
418
- this.stop(connectionId);
419
- const timer = setInterval(() => {
420
- try {
421
- res.write(KEEPALIVE_COMMENT);
422
- } catch {
423
- this.stop(connectionId);
424
- }
425
- }, intervalMs);
426
- timer.unref();
427
- this.timers.set(connectionId, timer);
428
- }
429
- /** Stop and clear the keepalive timer for a connection (idempotent). */
430
- stop(connectionId) {
431
- const timer = this.timers.get(connectionId);
432
- if (timer) {
433
- clearInterval(timer);
434
- this.timers.delete(connectionId);
435
- }
436
- }
437
- /** Stop every keepalive timer (used on shutdown). */
438
- stopAll() {
439
- for (const timer of this.timers.values()) clearInterval(timer);
440
- this.timers.clear();
441
- }
442
- };
443
- HeartbeatService = __decorateClass([
444
- common.Injectable()
445
- ], HeartbeatService);
446
5
 
447
- // src/server/transports/sse/sse.transport.ts
448
- var SseTransport = class {
449
- constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
450
- this.connections = connections;
451
- this.rooms = rooms;
452
- this.replayBuffer = replayBuffer;
453
- this.idGen = idGen;
454
- this.heartbeat = heartbeat;
455
- this.auth = auth;
456
- this.pubsub = pubsub;
457
- this.hooks = hooks;
458
- this.options = options;
459
- this.instanceId = instanceId;
460
- this.offlineQueue = offlineQueue;
461
- }
462
- connections;
463
- rooms;
464
- replayBuffer;
465
- idGen;
466
- heartbeat;
467
- auth;
468
- pubsub;
469
- hooks;
470
- options;
471
- instanceId;
472
- offlineQueue;
473
- kind = "sse";
474
- logger = new common.Logger(SseTransport.name);
475
- /** Tear down every SSE connection and stop heartbeat on process shutdown. */
476
- async onApplicationShutdown() {
477
- this.heartbeat.stopAll();
478
- for (const conn of this.connections.allByTransport("sse")) {
479
- await this.disconnectLocal(conn.connectionId);
480
- }
481
- }
482
- /** The resolved heartbeat interval for this transport. */
483
- get heartbeatMs() {
484
- return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
485
- }
486
- /** Whether the `connection:established` event should be emitted on connect. */
487
- get emitConnectionEvent() {
488
- return this.options.sse?.emitConnectionEvent !== false;
489
- }
490
- /** Authenticate a connection through the consumer-provided authenticator. */
491
- authenticate(context) {
492
- return this.auth.authenticate(context);
493
- }
494
- /**
495
- * Register an authenticated SSE connection and auto-join its user/tenant rooms.
496
- *
497
- * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
498
- * lifecycle hook is fired by the subscription handler after this returns, so that the
499
- * handler can carry a consistent connection record reference.
500
- */
501
- async registerConnection(params) {
502
- const record = {
503
- connectionId: params.connectionId,
504
- userId: params.auth.userId,
505
- tenantId: params.auth.tenantId,
506
- transport: "sse",
507
- ip: params.ip,
508
- userAgent: params.userAgent,
509
- connectedAt: /* @__PURE__ */ new Date(),
510
- subject: params.subject,
511
- close$: params.close$,
512
- originalAuth: {
513
- userId: params.auth.userId,
514
- tenantId: params.auth.tenantId,
515
- roles: params.auth.roles
516
- }
517
- };
518
- this.connections.register(record);
519
- this.rooms.join(params.connectionId, composeRoomId("USER", params.auth.userId));
520
- if (params.auth.tenantId !== void 0) {
521
- this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
522
- }
523
- await this.evictBeyondLimit(params.auth.userId);
524
- }
525
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
526
- async unregisterConnection(connectionId, reason) {
527
- const record = this.connections.unregister(connectionId);
528
- if (!record) return;
529
- this.rooms.leaveAll(connectionId);
530
- this.heartbeat.stop(connectionId);
531
- try {
532
- await this.hooks.onDisconnect?.({
533
- connectionId: record.connectionId,
534
- userId: record.userId,
535
- tenantId: record.tenantId,
536
- transport: "sse",
537
- ip: record.ip,
538
- userAgent: record.userAgent,
539
- connectedAt: record.connectedAt,
540
- durationMs: Date.now() - record.connectedAt.getTime(),
541
- ...reason !== void 0 ? { reason } : {}
542
- });
543
- } catch (error) {
544
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
545
- }
546
- }
547
- /** Replay the events a user missed after `lastEventId`. */
548
- getReplayEvents(userId, lastEventId) {
549
- return this.replayBuffer.since(userId, lastEventId);
550
- }
551
- /**
552
- * All SSE connections for a user — public accessor so external callers can
553
- * inspect or iterate without reaching into a private registry field.
554
- *
555
- * @param userId - The user whose active connections are returned.
556
- * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
557
- */
558
- connectionsForUser(userId) {
559
- return this.connections.byUser(userId, "sse");
560
- }
561
- /**
562
- * Look up a single connection by id.
563
- *
564
- * @param connectionId - The unique connection identifier.
565
- * @returns The `ConnectionRecord`, or `undefined` when not found.
566
- */
567
- getConnection(connectionId) {
568
- return this.connections.get(connectionId);
569
- }
570
- async emitToUser(userId, event, data) {
571
- const id = this.idGen.next();
572
- this.emitToUserLocal(userId, event, data, id);
573
- if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
574
- void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
575
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
576
- );
577
- }
578
- await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
579
- }
580
- async emitToTenant(tenantId, event, data) {
581
- const id = this.idGen.next();
582
- this.emitToTenantLocal(tenantId, event, data, id);
583
- await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
584
- }
585
- async emitToRoom(roomId, event, data) {
586
- const id = this.idGen.next();
587
- this.emitToRoomLocal(roomId, event, data, id);
588
- await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
589
- }
590
- async broadcast(event, data) {
591
- const id = this.idGen.next();
592
- this.broadcastLocal(event, data, id);
593
- await this.publish({ op: "broadcast", args: { event, data, id } });
594
- }
595
- async joinRoom(connectionId, roomId) {
596
- this.rooms.join(connectionId, roomId);
597
- }
598
- async leaveRoom(connectionId, roomId) {
599
- this.rooms.leave(connectionId, roomId);
600
- }
601
- /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
602
- async disconnect(connectionId, reason) {
603
- const record = this.connections.get(connectionId);
604
- if (record && record.transport === "sse") {
605
- await this.disconnectLocal(connectionId, reason);
606
- return;
607
- }
608
- await this.publish({ op: "disconnect", args: { connectionId, reason } });
609
- }
610
- /**
611
- * Deliver an event to a user's local SSE connections and update the replay buffer.
612
- *
613
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
614
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
615
- */
616
- emitToUserLocal(userId, event, data, id) {
617
- const message = this.buildMessage(id, event, data);
618
- this.replayBuffer.append(userId, message);
619
- for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
620
- }
621
- /**
622
- * Deliver an event to all local SSE connections for a tenant.
623
- *
624
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
625
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
626
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
627
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
628
- */
629
- emitToTenantLocal(tenantId, event, data, id) {
630
- const message = this.buildMessage(id, event, data);
631
- for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
632
- }
633
- /**
634
- * Deliver an event to all local SSE connections that joined the given room.
635
- *
636
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
637
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
638
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
639
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
640
- */
641
- emitToRoomLocal(roomId, event, data, id) {
642
- const message = this.buildMessage(id, event, data);
643
- for (const connectionId of this.rooms.members(roomId)) {
644
- const conn = this.connections.get(connectionId);
645
- if (conn && conn.transport === "sse") this.deliver(conn, message);
646
- }
647
- }
648
- /**
649
- * Deliver an event to all local SSE connections.
650
- *
651
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
652
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
653
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
654
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
655
- */
656
- broadcastLocal(event, data, id) {
657
- const message = this.buildMessage(id, event, data);
658
- for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
659
- }
660
- /**
661
- * Tear down a locally-owned SSE stream, then clean up (no re-publish).
662
- *
663
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
664
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
665
- */
666
- async disconnectLocal(connectionId, reason) {
667
- const record = this.connections.get(connectionId);
668
- if (!record || record.transport !== "sse") return;
669
- await this.unregisterConnection(connectionId, reason);
670
- record.close$?.next();
671
- record.close$?.complete();
672
- }
673
- buildMessage(id, event, data) {
674
- return { id, type: event, data };
675
- }
676
- /** Deliver to one connection, isolating failures so others still receive the event. */
677
- deliver(conn, message) {
678
- try {
679
- conn.subject?.next(message);
680
- } catch (error) {
681
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
682
- }
683
- }
684
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
685
- async publish(message) {
686
- try {
687
- await this.pubsub.publish({ ...message, origin: this.instanceId });
688
- } catch (error) {
689
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
690
- }
691
- }
692
- /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
693
- async evictBeyondLimit(userId) {
694
- const max = this.options.sse?.maxConnectionsPerUser;
695
- if (max === void 0 || max <= 0) return;
696
- let userConnections = this.connections.byUser(userId, "sse");
697
- while (userConnections.length > max) {
698
- const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
699
- await this.disconnectLocal(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
700
- userConnections = this.connections.byUser(userId, "sse");
701
- }
702
- }
703
- };
704
- SseTransport = __decorateClass([
705
- common.Injectable(),
706
- __decorateParam(0, common.Inject(exports.ConnectionRegistry)),
707
- __decorateParam(1, common.Inject(RoomRegistry)),
708
- __decorateParam(2, common.Inject(EventReplayBuffer)),
709
- __decorateParam(3, common.Inject(EventIdGenerator)),
710
- __decorateParam(4, common.Inject(HeartbeatService)),
711
- __decorateParam(5, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
712
- __decorateParam(6, common.Inject(REALTIME_PUBSUB_TOKEN)),
713
- __decorateParam(7, common.Inject(REALTIME_HOOKS_TOKEN)),
714
- __decorateParam(8, common.Inject(REALTIME_OPTIONS_TOKEN)),
715
- __decorateParam(9, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
716
- __decorateParam(10, common.Optional()),
717
- __decorateParam(10, common.Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
718
- ], SseTransport);
719
6
 
720
- // src/server/transports/sse/sse-subscription.handler.ts
721
- function singleHeader(value) {
722
- return typeof value === "string" ? value : void 0;
723
- }
724
- function resolveIp(req) {
725
- const forwarded = req.headers["x-forwarded-for"];
726
- const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
727
- return candidate.trim() || req.ip || "unknown";
728
- }
729
- function normalizeHeaders(headers) {
730
- const out = /* @__PURE__ */ Object.create(null);
731
- for (const [key, value] of Object.entries(headers)) {
732
- out[key.toLowerCase()] = Array.isArray(value) ? value.join(",") : value;
733
- }
734
- return out;
735
- }
736
- function sanitizeQuery(query) {
737
- const out = /* @__PURE__ */ Object.create(null);
738
- for (const [key, value] of Object.entries(query)) {
739
- out[key] = typeof value === "string" ? value : void 0;
740
- }
741
- return out;
742
- }
743
- function buildAuthContext(req) {
744
- const headers = normalizeHeaders(req.headers);
745
- delete headers["authorization"];
746
- return {
747
- cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
748
- headers,
749
- query: sanitizeQuery(req.query),
750
- ip: resolveIp(req),
751
- userAgent: singleHeader(req.headers["user-agent"]),
752
- transport: "sse"
753
- };
754
- }
755
- function buildEstablishedEvent(connectionId, auth) {
756
- return {
757
- type: RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
758
- data: {
759
- connectionId,
760
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
761
- }
762
- };
763
- }
764
- function toMessageEvent(event) {
765
- return { id: event.id, type: event.event, data: event.data };
766
- }
767
- function buildMeta(record) {
768
- return {
769
- connectionId: record.connectionId,
770
- userId: record.userId,
771
- tenantId: record.tenantId,
772
- transport: "sse",
773
- ip: record.ip,
774
- userAgent: record.userAgent,
775
- connectedAt: record.connectedAt
776
- };
777
- }
778
- var SseSubscriptionHandler = class {
779
- constructor(transport, heartbeat, options, hooks, offlineDelivery) {
780
- this.transport = transport;
781
- this.heartbeat = heartbeat;
782
- this.options = options;
783
- this.hooks = hooks;
784
- this.offlineDelivery = offlineDelivery;
785
- }
786
- transport;
787
- heartbeat;
788
- options;
789
- hooks;
790
- offlineDelivery;
791
- logger = new common.Logger(SseSubscriptionHandler.name);
792
- /**
793
- * Handle an incoming SSE connection request end-to-end.
794
- *
795
- * Sets anti-buffering headers, authenticates the request, captures the offline-gap
796
- * before exposing the connection, then returns an Observable whose subscriber callback
797
- * wires the downstream listener BEFORE calling `registerConnection` — so a plain
798
- * `Subject` suffices and the replay buffer cannot grow unboundedly.
799
- *
800
- * @param req - The Express request (SSE GET).
801
- * @param res - The Express response (passthrough for header mutations and heartbeat writes).
802
- * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
803
- * @throws UnauthorizedException when authentication returns null.
804
- */
805
- async handle(req, res) {
806
- res.setHeader("Cache-Control", "no-cache, no-transform");
807
- res.setHeader("X-Accel-Buffering", "no");
808
- const context = buildAuthContext(req);
809
- const auth = await this.transport.authenticate(context);
810
- if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
811
- const resolvedTenantId = this.options.tenantResolver?.(auth) ?? auth.tenantId;
812
- const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
813
- const connectionId = crypto.randomUUID();
814
- const subject = new rxjs.Subject();
815
- const close$ = new rxjs.Subject();
816
- const lastEventId = singleHeader(req.headers["last-event-id"]);
817
- const replayEvents = lastEventId ? this.transport.getReplayEvents(resolvedAuth.userId, lastEventId) : [];
818
- const replay$ = replayEvents.length > 0 ? rxjs.of(...replayEvents) : rxjs.EMPTY;
819
- const ringBufferIds = new Set(replayEvents.map((e) => e.id ?? ""));
820
- const queueEvents = lastEventId && this.offlineDelivery ? await this.offlineDelivery.retrieve(resolvedAuth.userId, lastEventId, ringBufferIds) : [];
821
- const established$ = this.transport.emitConnectionEvent ? rxjs.of(buildEstablishedEvent(connectionId, resolvedAuth)) : rxjs.EMPTY;
822
- return this.buildStream({
823
- connectionId,
824
- resolvedAuth,
825
- ip: context.ip,
826
- userAgent: context.userAgent,
827
- res,
828
- subject,
829
- close$,
830
- established$,
831
- replay$,
832
- queueEvents
833
- });
834
- }
835
- /**
836
- * Build the live Observable using a subscribe-before-register pattern.
837
- *
838
- * The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
839
- * already has a listener when `registerConnection` runs. Any `subject.next()` that
840
- * occurs during or after registration goes directly to the subscriber — nothing is
841
- * buffered or retained, nothing is dropped, and ordering (established → replay →
842
- * queue → live) is preserved.
843
- */
844
- buildStream(p) {
845
- return new rxjs.Observable((subscriber) => {
846
- const inner = this.subscribePipeline(p, subscriber);
847
- if (!subscriber.closed && p.queueEvents.length > 0) {
848
- void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
849
- }
850
- this.activateConnection(p, subscriber);
851
- return () => inner.unsubscribe();
852
- });
853
- }
854
- /**
855
- * Wire the merged pipeline to the downstream subscriber with teardown.
856
- *
857
- * Subscribing first guarantees `subject` has a listener before registration can emit,
858
- * so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
859
- */
860
- subscribePipeline(p, subscriber) {
861
- const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
862
- const queueReplay$ = queueEvents.length > 0 ? rxjs.of(...queueEvents.map(toMessageEvent)) : rxjs.EMPTY;
863
- return rxjs.merge(established$, replay$, queueReplay$, subject).pipe(
864
- operators.takeUntil(close$),
865
- operators.catchError((error) => {
866
- this.fireHook(
867
- () => this.hooks?.onError?.({ connectionId, error, transport: "sse" })
868
- );
869
- return rxjs.EMPTY;
870
- }),
871
- operators.finalize(() => {
872
- this.heartbeat.stop(connectionId);
873
- void this.transport.unregisterConnection(connectionId);
874
- })
875
- ).subscribe(subscriber);
876
- }
877
- /**
878
- * Register the connection (after the subscriber is wired) and activate it on resolution.
879
- *
880
- * A registration failure routes to `onError` and errors the stream; a failure that
881
- * arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
882
- */
883
- activateConnection(p, subscriber) {
884
- const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
885
- this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
886
- this.fireHook(
887
- () => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
888
- );
889
- subscriber.error(err);
890
- });
891
- }
892
- /**
893
- * Complete the connection handshake once registration resolves.
894
- *
895
- * Registration is async and can resolve AFTER the downstream subscriber has already
896
- * torn down (client disconnected mid-handshake). When that happens `finalize` has
897
- * already stopped the heartbeat and unregistered, so re-firing onConnect or starting
898
- * a fresh heartbeat would leak the connection and write after close. Guard on
899
- * `subscriber.closed`: if closed, undo the late registration idempotently and return.
900
- */
901
- onRegistered(p, subscriber) {
902
- const { connectionId, res } = p;
903
- if (subscriber.closed) {
904
- this.heartbeat.stop(connectionId);
905
- void this.transport.unregisterConnection(connectionId);
906
- return;
907
- }
908
- const record = this.transport.getConnection(connectionId);
909
- if (record) {
910
- this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
911
- }
912
- const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
913
- this.heartbeat.start(connectionId, res, heartbeatMs);
914
- }
915
- /**
916
- * Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
917
- * so it never disrupts the connection lifecycle or live event delivery.
918
- *
919
- * @param invoke - A zero-arg function that calls the hook (handles optionality).
920
- */
921
- fireHook(invoke) {
922
- void Promise.resolve(invoke()).catch((err) => {
923
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
924
- });
925
- }
926
- };
927
- SseSubscriptionHandler = __decorateClass([
928
- common.Injectable(),
929
- __decorateParam(0, common.Inject(SseTransport)),
930
- __decorateParam(1, common.Inject(HeartbeatService)),
931
- __decorateParam(2, common.Inject(REALTIME_OPTIONS_TOKEN)),
932
- __decorateParam(3, common.Optional()),
933
- __decorateParam(3, common.Inject(REALTIME_HOOKS_TOKEN)),
934
- __decorateParam(4, common.Optional()),
935
- __decorateParam(4, common.Inject(OfflineQueueDeliveryService))
936
- ], SseSubscriptionHandler);
937
-
938
- // src/server/factories/sse-controller.factory.ts
939
- function createSseController(endpoint) {
940
- const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
941
- let DynamicSseController = class {
942
- // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
943
- // not emit `design:paramtypes` decorator metadata, so constructor params must
944
- // be resolved by token rather than by reflected type.
945
- constructor(handler) {
946
- this.handler = handler;
947
- }
948
- handler;
949
- subscribe(req, res) {
950
- return this.handler.handle(req, res);
951
- }
952
- };
953
- __decorateClass([
954
- common.Sse(ssePath),
955
- __decorateParam(0, common.Req()),
956
- __decorateParam(1, common.Res({ passthrough: true }))
957
- ], DynamicSseController.prototype, "subscribe", 1);
958
- DynamicSseController = __decorateClass([
959
- common.Controller(),
960
- __decorateParam(0, common.Inject(SseSubscriptionHandler))
961
- ], DynamicSseController);
962
- return DynamicSseController;
963
- }
964
- exports.InMemoryPubSub = class InMemoryPubSub {
965
- handlers = /* @__PURE__ */ new Set();
966
- /**
967
- * Publish a message to all subscribed handlers.
968
- *
969
- * Delivery is deferred one microtask so a handler that enqueues further publishes
970
- * does not deepen the current call stack. One handler's failure does not block others.
971
- *
972
- * @param message - The pub/sub message to fan out.
973
- */
974
- async publish(message) {
975
- await Promise.resolve();
976
- for (const handler of this.handlers) {
977
- try {
978
- handler(message);
979
- } catch {
980
- }
981
- }
982
- }
983
- /**
984
- * Subscribe to pub/sub messages.
985
- *
986
- * @param handler - Called for every published message.
987
- * @returns An async unsubscribe function that removes this handler.
988
- */
989
- async subscribe(handler) {
990
- this.handlers.add(handler);
991
- return async () => {
992
- this.handlers.delete(handler);
993
- };
994
- }
995
- };
996
- exports.InMemoryPubSub = __decorateClass([
997
- common.Injectable()
998
- ], exports.InMemoryPubSub);
999
- var RealtimePubSubSubscriber = class {
1000
- constructor(pubsub, instanceId, sse) {
1001
- this.pubsub = pubsub;
1002
- this.instanceId = instanceId;
1003
- this.sse = sse;
1004
- }
1005
- pubsub;
1006
- instanceId;
1007
- sse;
1008
- logger = new common.Logger(RealtimePubSubSubscriber.name);
1009
- unsubscribe = null;
1010
- async onModuleInit() {
1011
- try {
1012
- this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1013
- } catch (err) {
1014
- this.logger.warn(
1015
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1016
- );
1017
- }
1018
- }
1019
- async onApplicationShutdown() {
1020
- if (this.unsubscribe) {
1021
- try {
1022
- await this.unsubscribe();
1023
- } catch (err) {
1024
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1025
- }
1026
- this.unsubscribe = null;
1027
- }
1028
- }
1029
- handle(msg) {
1030
- if (msg.origin === this.instanceId) return;
1031
- try {
1032
- switch (msg.op) {
1033
- case "emitToUser": {
1034
- const a = msg.args;
1035
- this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
1036
- break;
1037
- }
1038
- case "emitToTenant": {
1039
- const a = msg.args;
1040
- this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
1041
- break;
1042
- }
1043
- case "emitToRoom": {
1044
- const a = msg.args;
1045
- this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
1046
- break;
1047
- }
1048
- case "broadcast": {
1049
- const a = msg.args;
1050
- this.sse.broadcastLocal(a.event, a.data, a.id);
1051
- break;
1052
- }
1053
- case "disconnect": {
1054
- const a = msg.args;
1055
- void this.sse.disconnectLocal(a.connectionId, a.reason);
1056
- break;
1057
- }
1058
- default: {
1059
- const exhaustive = msg.op;
1060
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
1061
- }
1062
- }
1063
- } catch (err) {
1064
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1065
- }
1066
- }
1067
- };
1068
- RealtimePubSubSubscriber = __decorateClass([
1069
- common.Injectable(),
1070
- __decorateParam(0, common.Inject(REALTIME_PUBSUB_TOKEN)),
1071
- __decorateParam(1, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
1072
- __decorateParam(2, common.Inject(SseTransport))
1073
- ], RealtimePubSubSubscriber);
1074
- exports.RealtimeService = class RealtimeService {
1075
- constructor(transport) {
1076
- this.transport = transport;
1077
- }
1078
- transport;
1079
- /**
1080
- * Send to all of a user's connections (across devices/tabs).
1081
- *
1082
- * @example
1083
- * ```ts
1084
- * await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
1085
- * ```
1086
- */
1087
- emitToUser(userId, event, data) {
1088
- return this.transport.emitToUser(userId, event, data);
1089
- }
1090
- /** Send to every connection in a tenant. */
1091
- emitToTenant(tenantId, event, data) {
1092
- return this.transport.emitToTenant(tenantId, event, data);
1093
- }
1094
- /**
1095
- * Send to a logical room. Use the prefix convention (`user:{id}`,
1096
- * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
1097
- */
1098
- emitToRoom(roomId, event, data) {
1099
- return this.transport.emitToRoom(roomId, event, data);
1100
- }
1101
- /** Send to every connected client. Use sparingly. */
1102
- broadcast(event, data) {
1103
- return this.transport.broadcast(event, data);
1104
- }
1105
- /** Add a specific connection to a room. */
1106
- joinRoom(connectionId, roomId) {
1107
- return this.transport.joinRoom(connectionId, roomId);
1108
- }
1109
- /** Remove a specific connection from a room. */
1110
- leaveRoom(connectionId, roomId) {
1111
- return this.transport.leaveRoom(connectionId, roomId);
1112
- }
1113
- /** Force-disconnect a specific connection (e.g. on auth revocation). */
1114
- disconnect(connectionId, reason) {
1115
- return this.transport.disconnect(connectionId, reason);
1116
- }
1117
- };
1118
- exports.RealtimeService = __decorateClass([
1119
- common.Injectable(),
1120
- __decorateParam(0, common.Inject(REALTIME_TRANSPORT_TOKEN))
1121
- ], exports.RealtimeService);
1122
- function resolvePolicy(raw) {
1123
- return {
1124
- intervalSeconds: raw?.intervalSeconds ?? 300,
1125
- onFailure: raw?.onFailure ?? "disconnect",
1126
- cacheTtlMs: raw?.cacheTtlMs ?? 6e4
1127
- };
1128
- }
1129
- var ReauthenticationService = class {
1130
- constructor(connections, realtime, auth, options, hooks) {
1131
- this.connections = connections;
1132
- this.realtime = realtime;
1133
- this.auth = auth;
1134
- this.hooks = hooks;
1135
- this.policy = resolvePolicy(options.reauthenticationPolicy);
1136
- }
1137
- connections;
1138
- realtime;
1139
- auth;
1140
- hooks;
1141
- logger = new common.Logger(ReauthenticationService.name);
1142
- timer = null;
1143
- /** connectionId → epoch-ms timestamp of last successful revalidation. */
1144
- positiveCache = /* @__PURE__ */ new Map();
1145
- policy;
1146
- /**
1147
- * Schedule the periodic revalidation cycle.
1148
- *
1149
- * The timer is unref'd so it never keeps the process alive on its own.
1150
- * When the authenticator does not implement `revalidate`, the service stays
1151
- * idle and emits an informative log.
1152
- */
1153
- onModuleInit() {
1154
- if (!this.auth.revalidate) {
1155
- this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
1156
- return;
1157
- }
1158
- this.timer = setInterval(() => void this.runCycle(), this.policy.intervalSeconds * 1e3);
1159
- this.timer.unref();
1160
- this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1161
- }
1162
- /**
1163
- * Clear the timer and the positive cache.
1164
- *
1165
- * Called by NestJS on graceful shutdown to prevent leaks.
1166
- */
1167
- onApplicationShutdown() {
1168
- if (this.timer) {
1169
- clearInterval(this.timer);
1170
- this.timer = null;
1171
- }
1172
- this.positiveCache.clear();
1173
- }
1174
- /**
1175
- * Run one revalidation cycle over all active SSE connections.
1176
- *
1177
- * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1178
- * refreshes the cache. A negative result (or a thrown error) invokes the configured
1179
- * `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
1180
- *
1181
- * Exposed as public for test access.
1182
- */
1183
- async runCycle() {
1184
- const now = Date.now();
1185
- for (const conn of this.connections.allByTransport("sse")) {
1186
- try {
1187
- const lastValid = this.positiveCache.get(conn.connectionId);
1188
- if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
1189
- const originalAuth = {
1190
- userId: conn.originalAuth.userId,
1191
- ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1192
- ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
1193
- };
1194
- const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
1195
- if (rawResult === true) {
1196
- this.positiveCache.set(conn.connectionId, now);
1197
- continue;
1198
- }
1199
- await this.handleFailure(conn);
1200
- } catch (err) {
1201
- this.logger.warn(
1202
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1203
- );
1204
- await this.handleFailure(conn);
1205
- }
1206
- }
1207
- }
1208
- /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1209
- async handleFailure(conn) {
1210
- this.positiveCache.delete(conn.connectionId);
1211
- if (this.policy.onFailure === "event") {
1212
- await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1213
- reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1214
- });
1215
- }
1216
- void Promise.resolve(
1217
- this.hooks?.onReauthenticationFailed?.({
1218
- connectionId: conn.connectionId,
1219
- userId: conn.userId,
1220
- tenantId: conn.tenantId,
1221
- transport: "sse",
1222
- ip: conn.ip,
1223
- userAgent: conn.userAgent,
1224
- connectedAt: conn.connectedAt
1225
- })
1226
- ).catch((err) => {
1227
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1228
- });
1229
- await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1230
- }
1231
- };
1232
- ReauthenticationService = __decorateClass([
1233
- common.Injectable(),
1234
- __decorateParam(0, common.Inject(exports.ConnectionRegistry)),
1235
- __decorateParam(1, common.Inject(exports.RealtimeService)),
1236
- __decorateParam(2, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
1237
- __decorateParam(3, common.Inject(REALTIME_OPTIONS_TOKEN)),
1238
- __decorateParam(4, common.Optional()),
1239
- __decorateParam(4, common.Inject(REALTIME_HOOKS_TOKEN))
1240
- ], ReauthenticationService);
1241
- var CONNECTION_ROOM_PREFIX = "connection";
1242
- exports.WebSocketTransport = class WebSocketTransport {
1243
- constructor(connections, rooms, auth, hooks, options) {
1244
- this.connections = connections;
1245
- this.rooms = rooms;
1246
- this.auth = auth;
1247
- this.hooks = hooks;
1248
- this.options = options;
1249
- }
1250
- connections;
1251
- rooms;
1252
- auth;
1253
- hooks;
1254
- options;
1255
- kind = "websocket";
1256
- logger = new common.Logger(exports.WebSocketTransport.name);
1257
- /** Nullable until the gateway's afterInit wires the instance. */
1258
- server = null;
1259
- /**
1260
- * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
1261
- *
1262
- * All emit methods silently no-op until this is called, so the transport is
1263
- * safe to construct before the HTTP server is ready.
1264
- *
1265
- * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
1266
- */
1267
- setServer(server) {
1268
- this.server = server;
1269
- this.logger.log("Socket.IO server wired to WebSocketTransport");
1270
- }
1271
- /**
1272
- * Resolve the map of locally-connected sockets, tolerating both server shapes.
1273
- *
1274
- * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
1275
- * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
1276
- * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
1277
- * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
1278
- * this indirection so they work under either shape.
1279
- */
1280
- localSockets() {
1281
- const server = this.server;
1282
- if (!server) return void 0;
1283
- const sockets = server.sockets;
1284
- return sockets instanceof Map ? sockets : sockets.sockets;
1285
- }
1286
- /**
1287
- * Expose the configured authenticator to the gateway.
1288
- *
1289
- * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
1290
- * `WebSocketTransport` → authenticator, rather than injecting the token
1291
- * directly in the gateway.
1292
- *
1293
- * @returns The consumer-provided `IConnectionAuthenticator` instance.
1294
- */
1295
- authenticator() {
1296
- return this.auth;
1297
- }
1298
- /**
1299
- * Register a freshly-authenticated WebSocket connection.
1300
- *
1301
- * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
1302
- * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
1303
- * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
1304
- *
1305
- * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
1306
- * does not publish to `IRealtimePubSub`.
1307
- *
1308
- * @param socket - The authenticated Socket.IO socket instance.
1309
- * @param auth - The resolved authentication result containing userId, tenantId, and roles.
1310
- */
1311
- async registerSocket(socket, auth) {
1312
- const connectedAt = /* @__PURE__ */ new Date();
1313
- this.connections.register({
1314
- connectionId: socket.id,
1315
- userId: auth.userId,
1316
- tenantId: auth.tenantId,
1317
- transport: "websocket",
1318
- ip: socket.handshake.address,
1319
- userAgent: socket.handshake.headers["user-agent"],
1320
- connectedAt,
1321
- subject: null,
1322
- close$: null,
1323
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1324
- });
1325
- await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
1326
- if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1327
- await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
1328
- this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
1329
- if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1330
- await this.evictBeyondLimit(auth.userId);
1331
- await this.hooks.onConnect?.({
1332
- connectionId: socket.id,
1333
- userId: auth.userId,
1334
- tenantId: auth.tenantId,
1335
- transport: "websocket",
1336
- ip: socket.handshake.address,
1337
- userAgent: socket.handshake.headers["user-agent"],
1338
- connectedAt
1339
- });
1340
- }
1341
- /**
1342
- * Unregister a disconnected WebSocket connection.
1343
- *
1344
- * Removes the record from `ConnectionRegistry`, clears all room membership
1345
- * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
1346
- * computed `durationMs`.
1347
- *
1348
- * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
1349
- * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
1350
- */
1351
- async unregisterSocket(connectionId, reason) {
1352
- const record = this.connections.unregister(connectionId);
1353
- if (!record) return;
1354
- this.rooms.leaveAll(connectionId);
1355
- const disconnectMeta = {
1356
- connectionId,
1357
- userId: record.userId,
1358
- tenantId: record.tenantId,
1359
- transport: "websocket",
1360
- ip: record.ip,
1361
- userAgent: record.userAgent,
1362
- connectedAt: record.connectedAt,
1363
- durationMs: Date.now() - record.connectedAt.getTime(),
1364
- ...reason !== void 0 ? { reason } : {}
1365
- };
1366
- await this.hooks.onDisconnect?.(disconnectMeta);
1367
- }
1368
- /**
1369
- * Send an event to every connection of a user (uses `user:{userId}` room).
1370
- *
1371
- * @param userId - Target user identifier.
1372
- * @param event - Event name to emit.
1373
- * @param data - Payload forwarded to all matching connections.
1374
- */
1375
- async emitToUser(userId, event, data) {
1376
- this.server?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
1377
- }
1378
- /**
1379
- * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
1380
- *
1381
- * @param tenantId - Target tenant identifier.
1382
- * @param event - Event name to emit.
1383
- * @param data - Payload forwarded to all matching connections.
1384
- */
1385
- async emitToTenant(tenantId, event, data) {
1386
- this.server?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
1387
- }
1388
- /**
1389
- * Send an event to every connection in an arbitrary room.
1390
- *
1391
- * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
1392
- * @param event - Event name to emit.
1393
- * @param data - Payload forwarded to all connections in the room.
1394
- */
1395
- async emitToRoom(roomId, event, data) {
1396
- this.server?.to(roomId).emit(event, data);
1397
- }
1398
- /**
1399
- * Broadcast an event to all connected clients.
1400
- *
1401
- * @param event - Event name to emit.
1402
- * @param data - Payload forwarded to every connected socket.
1403
- */
1404
- async broadcast(event, data) {
1405
- this.server?.emit(event, data);
1406
- }
1407
- /**
1408
- * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
1409
- *
1410
- * @param connectionId - The socket `id` of the connection to join.
1411
- * @param roomId - The room to join.
1412
- */
1413
- async joinRoom(connectionId, roomId) {
1414
- const socket = this.localSockets()?.get(connectionId);
1415
- if (socket) {
1416
- await socket.join(roomId);
1417
- this.rooms.join(connectionId, roomId);
1418
- }
1419
- }
1420
- /**
1421
- * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
1422
- *
1423
- * @param connectionId - The socket `id` of the connection to remove.
1424
- * @param roomId - The room to leave.
1425
- */
1426
- async leaveRoom(connectionId, roomId) {
1427
- const socket = this.localSockets()?.get(connectionId);
1428
- if (socket) {
1429
- await socket.leave(roomId);
1430
- this.rooms.leave(connectionId, roomId);
1431
- }
1432
- }
1433
- /**
1434
- * Force-disconnect a specific connection — adapter-aware, so revocation works
1435
- * across nodes.
1436
- *
1437
- * A socket local to this node is closed directly as a fast path. Regardless,
1438
- * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
1439
- * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
1440
- * connection pinned to another instance is still force-closed. The local socket
1441
- * has already left the room by then, so the broadcast does not double-close it.
1442
- *
1443
- * @param connectionId - The socket `id` of the connection to disconnect.
1444
- * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
1445
- */
1446
- async disconnect(connectionId, _reason) {
1447
- const server = this.server;
1448
- if (!server) return;
1449
- const local = this.localSockets()?.get(connectionId);
1450
- if (local) local.disconnect(true);
1451
- server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
1452
- }
1453
- /**
1454
- * Evict the user's oldest WebSocket connections (FIFO) when over
1455
- * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
1456
- * as the disconnect reason — never rejects the new connection with HTTP 429.
1457
- */
1458
- async evictBeyondLimit(userId) {
1459
- const max = this.options.websocket?.maxConnectionsPerUser;
1460
- if (max === void 0 || max <= 0) return;
1461
- let userConnections = this.connections.byUser(userId, "websocket");
1462
- while (userConnections.length > max) {
1463
- const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
1464
- await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1465
- await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1466
- userConnections = this.connections.byUser(userId, "websocket");
1467
- }
1468
- }
1469
- };
1470
- exports.WebSocketTransport = __decorateClass([
1471
- common.Injectable(),
1472
- __decorateParam(0, common.Inject(exports.ConnectionRegistry)),
1473
- __decorateParam(1, common.Inject(RoomRegistry)),
1474
- __decorateParam(2, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
1475
- __decorateParam(3, common.Inject(REALTIME_HOOKS_TOKEN)),
1476
- __decorateParam(4, common.Inject(REALTIME_OPTIONS_TOKEN))
1477
- ], exports.WebSocketTransport);
1478
- function firstQueryValue(value) {
1479
- return Array.isArray(value) ? value[0] : value;
1480
- }
1481
- exports.RealtimeGateway = class RealtimeGateway {
1482
- constructor(transport, options) {
1483
- this.transport = transport;
1484
- this.options = options;
1485
- }
1486
- transport;
1487
- options;
1488
- logger = new common.Logger(exports.RealtimeGateway.name);
1489
- server;
1490
- /** Wire the resolved Socket.IO server to the transport after gateway init. */
1491
- afterInit(server) {
1492
- this.transport.setServer(server);
1493
- this.logger.log("RealtimeGateway initialized");
1494
- }
1495
- /**
1496
- * Handle a new WebSocket connection.
1497
- *
1498
- * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
1499
- * three supported auth patterns (spec §8.1):
1500
- * - Cookie HttpOnly — extracted via `parseCookieHeader`.
1501
- * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
1502
- * - Bearer header — available in `headers.authorization` or via `auth.token`.
1503
- *
1504
- * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
1505
- * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
1506
- * context so the authenticator sees a single unified shape regardless of client.
1507
- *
1508
- * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
1509
- * undefined`); the single-value `ticket` parameter is collapsed to its first
1510
- * element so the authenticator receives a well-defined string.
1511
- *
1512
- * Fail-closed: any thrown error disconnects the socket immediately so it cannot
1513
- * linger in an unregistered state and receive broadcast events.
1514
- */
1515
- async handleConnection(socket) {
1516
- try {
1517
- const { handshake } = socket;
1518
- const headers = this.normalizeHeaders(handshake.headers);
1519
- const query = { ...handshake.query };
1520
- const handshakeAuth = handshake.auth;
1521
- if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
1522
- if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
1523
- const ticket = firstQueryValue(query["ticket"]);
1524
- if (ticket !== void 0) query["ticket"] = ticket;
1525
- const ctx = {
1526
- cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
1527
- headers,
1528
- query,
1529
- ip: handshake.address,
1530
- userAgent: handshake.headers["user-agent"],
1531
- transport: "websocket"
1532
- };
1533
- const auth = await this.transport.authenticator().authenticate(ctx);
1534
- if (!auth) {
1535
- socket.disconnect(true);
1536
- return;
1537
- }
1538
- await this.transport.registerSocket(socket, auth);
1539
- if (this.options.websocket?.emitConnectionEvent !== false) {
1540
- socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
1541
- connectionId: socket.id,
1542
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1543
- });
1544
- }
1545
- } catch (err) {
1546
- this.logger.error(
1547
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
1548
- );
1549
- socket.disconnect(true);
1550
- }
1551
- }
1552
- /** Handle a WebSocket disconnection — unregister the connection. */
1553
- async handleDisconnect(socket) {
1554
- await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
1555
- }
1556
- /**
1557
- * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
1558
- *
1559
- * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
1560
- * single string, matching the shape expected by `ConnectionAuthContext.headers`.
1561
- */
1562
- normalizeHeaders(input) {
1563
- const out = {};
1564
- for (const [k, v] of Object.entries(input)) {
1565
- out[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v;
1566
- }
1567
- return out;
1568
- }
1569
- };
1570
- __decorateClass([
1571
- websockets.WebSocketServer()
1572
- ], exports.RealtimeGateway.prototype, "server", 2);
1573
- exports.RealtimeGateway = __decorateClass([
1574
- websockets.WebSocketGateway({
1575
- cors: { origin: false }
1576
- }),
1577
- __decorateParam(0, common.Inject(exports.WebSocketTransport)),
1578
- __decorateParam(1, common.Inject(REALTIME_OPTIONS_TOKEN))
1579
- ], exports.RealtimeGateway);
1580
- exports.CompositeTransport = class CompositeTransport {
1581
- constructor(sse, ws) {
1582
- this.sse = sse;
1583
- this.ws = ws;
1584
- }
1585
- sse;
1586
- ws;
1587
- kind = "sse";
1588
- logger = new common.Logger(exports.CompositeTransport.name);
1589
- /**
1590
- * Emit to all connections of a user across both transports.
1591
- *
1592
- * @param userId - Target user identifier.
1593
- * @param event - Event name to emit.
1594
- * @param data - Payload forwarded to all matching connections.
1595
- */
1596
- async emitToUser(userId, event, data) {
1597
- await this.fanOut(
1598
- "emitToUser",
1599
- () => this.sse.emitToUser(userId, event, data),
1600
- () => this.ws.emitToUser(userId, event, data)
1601
- );
1602
- }
1603
- /**
1604
- * Emit to all connections within a tenant across both transports.
1605
- *
1606
- * @param tenantId - Target tenant identifier.
1607
- * @param event - Event name to emit.
1608
- * @param data - Payload forwarded to all matching connections.
1609
- */
1610
- async emitToTenant(tenantId, event, data) {
1611
- await this.fanOut(
1612
- "emitToTenant",
1613
- () => this.sse.emitToTenant(tenantId, event, data),
1614
- () => this.ws.emitToTenant(tenantId, event, data)
1615
- );
1616
- }
1617
- /**
1618
- * Emit to all connections in a room across both transports.
1619
- *
1620
- * @param roomId - The fully-qualified room identifier.
1621
- * @param event - Event name to emit.
1622
- * @param data - Payload forwarded to all connections in the room.
1623
- */
1624
- async emitToRoom(roomId, event, data) {
1625
- await this.fanOut(
1626
- "emitToRoom",
1627
- () => this.sse.emitToRoom(roomId, event, data),
1628
- () => this.ws.emitToRoom(roomId, event, data)
1629
- );
1630
- }
1631
- /**
1632
- * Broadcast to all connected clients across both transports.
1633
- *
1634
- * @param event - Event name to emit.
1635
- * @param data - Payload forwarded to every connected client.
1636
- */
1637
- async broadcast(event, data) {
1638
- await this.fanOut(
1639
- "broadcast",
1640
- () => this.sse.broadcast(event, data),
1641
- () => this.ws.broadcast(event, data)
1642
- );
1643
- }
1644
- /**
1645
- * Join a connection to a room.
1646
- *
1647
- * Both transports are attempted; only the one that owns the connection
1648
- * succeeds. The other's failure is expected and swallowed.
1649
- */
1650
- async joinRoom(connectionId, roomId) {
1651
- await Promise.all([
1652
- this.sse.joinRoom(connectionId, roomId).catch(() => void 0),
1653
- this.ws.joinRoom(connectionId, roomId).catch(() => void 0)
1654
- ]);
1655
- }
1656
- /**
1657
- * Remove a connection from a room.
1658
- *
1659
- * Both transports are attempted tolerantly — one will succeed, the other
1660
- * may fail silently.
1661
- */
1662
- async leaveRoom(connectionId, roomId) {
1663
- await Promise.all([
1664
- this.sse.leaveRoom(connectionId, roomId).catch(() => void 0),
1665
- this.ws.leaveRoom(connectionId, roomId).catch(() => void 0)
1666
- ]);
1667
- }
1668
- /**
1669
- * Disconnect a specific connection.
1670
- *
1671
- * Both transports are attempted; the one owning the connection disconnects it.
1672
- */
1673
- async disconnect(connectionId, reason) {
1674
- await Promise.all([
1675
- this.sse.disconnect(connectionId, reason).catch(() => void 0),
1676
- this.ws.disconnect(connectionId, reason).catch(() => void 0)
1677
- ]);
1678
- }
1679
- /**
1680
- * Run two transport tasks in parallel via `Promise.allSettled`.
1681
- *
1682
- * A rejection in either task is logged as a warning and does not propagate,
1683
- * ensuring one failing transport never blocks delivery on the other.
1684
- */
1685
- async fanOut(op, ...tasks) {
1686
- const results = await Promise.allSettled(tasks.map((t) => t()));
1687
- for (const result of results) {
1688
- if (result.status === "rejected") {
1689
- this.logger.warn(
1690
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
1691
- );
1692
- }
1693
- }
1694
- }
1695
- };
1696
- exports.CompositeTransport = __decorateClass([
1697
- common.Injectable(),
1698
- __decorateParam(0, common.Inject(SseTransport)),
1699
- __decorateParam(1, common.Inject(exports.WebSocketTransport))
1700
- ], exports.CompositeTransport);
1701
-
1702
- // src/server/realtime.module.ts
1703
- function assertWsPeerDeps(resolver = __require.resolve) {
1704
- try {
1705
- resolver("@nestjs/websockets");
1706
- resolver("socket.io");
1707
- } catch {
1708
- throw new Error(
1709
- "[BymaxRealtimeModule] transport 'websocket'|'both' requires '@nestjs/websockets' and 'socket.io' \u2014 install them, or switch to transport: 'sse'."
1710
- );
1711
- }
1712
- }
1713
- function buildCommonProviders(resolved, instanceId) {
1714
- return [
1715
- { provide: REALTIME_OPTIONS_TOKEN, useValue: resolved },
1716
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
1717
- { provide: REALTIME_AUTHENTICATOR_TOKEN, useValue: resolved.authenticator },
1718
- { provide: REALTIME_PUBSUB_TOKEN, useValue: resolved.pubsub ?? new exports.InMemoryPubSub() },
1719
- { provide: REALTIME_HOOKS_TOKEN, useValue: resolved.hooks ?? {} },
1720
- { provide: REALTIME_OFFLINE_QUEUE_TOKEN, useValue: resolved.offlineQueue },
1721
- { provide: REALTIME_PRESENCE_TOKEN, useValue: resolved.presence },
1722
- exports.ConnectionRegistry,
1723
- RoomRegistry,
1724
- EventIdGenerator,
1725
- EventReplayBuffer,
1726
- HeartbeatService,
1727
- exports.RealtimeService,
1728
- ReauthenticationService,
1729
- OfflineQueueDeliveryService
1730
- ];
1731
- }
1732
- function buildTransportProviders(resolved) {
1733
- const transport = resolved.transport;
1734
- const providers = [];
1735
- const controllers = [];
1736
- const gateways = [];
1737
- if (transport === "sse") {
1738
- providers.push(SseTransport, SseSubscriptionHandler, RealtimePubSubSubscriber);
1739
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport });
1740
- controllers.push(resolved.sse.endpoint);
1741
- } else if (transport === "websocket") {
1742
- assertWsPeerDeps();
1743
- providers.push(exports.WebSocketTransport);
1744
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport });
1745
- gateways.push(exports.RealtimeGateway);
1746
- } else {
1747
- assertWsPeerDeps();
1748
- providers.push(
1749
- SseTransport,
1750
- exports.WebSocketTransport,
1751
- exports.CompositeTransport,
1752
- SseSubscriptionHandler,
1753
- RealtimePubSubSubscriber
1754
- );
1755
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport });
1756
- controllers.push(resolved.sse.endpoint);
1757
- gateways.push(exports.RealtimeGateway);
1758
- }
1759
- return { providers, controllers, gateways };
1760
- }
1761
- function buildLegacyAsyncTransportProviders() {
1762
- return [
1763
- SseTransport,
1764
- SseSubscriptionHandler,
1765
- exports.WebSocketTransport,
1766
- exports.CompositeTransport,
1767
- exports.RealtimeGateway,
1768
- RealtimePubSubSubscriber,
1769
- {
1770
- provide: REALTIME_TRANSPORT_TOKEN,
1771
- useFactory: (opts, sse, ws, composite) => {
1772
- if (opts.transport === "sse") return sse;
1773
- if (opts.transport === "websocket") return ws;
1774
- return composite;
1775
- },
1776
- inject: [REALTIME_OPTIONS_TOKEN, SseTransport, exports.WebSocketTransport, exports.CompositeTransport]
1777
- }
1778
- ];
1779
- }
1780
- function buildAsyncTransportProviders(mode) {
1781
- if (mode === "sse") {
1782
- return {
1783
- providers: [
1784
- SseTransport,
1785
- SseSubscriptionHandler,
1786
- RealtimePubSubSubscriber,
1787
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
1788
- ],
1789
- controllers: [createSseController("/events")]
1790
- };
1791
- }
1792
- if (mode === "websocket") {
1793
- assertWsPeerDeps();
1794
- return {
1795
- providers: [
1796
- exports.WebSocketTransport,
1797
- exports.RealtimeGateway,
1798
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
1799
- ],
1800
- controllers: []
1801
- };
1802
- }
1803
- if (mode === "both") {
1804
- assertWsPeerDeps();
1805
- return {
1806
- providers: [
1807
- SseTransport,
1808
- SseSubscriptionHandler,
1809
- exports.WebSocketTransport,
1810
- exports.CompositeTransport,
1811
- exports.RealtimeGateway,
1812
- RealtimePubSubSubscriber,
1813
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
1814
- ],
1815
- controllers: [createSseController("/events")]
1816
- };
1817
- }
1818
- return {
1819
- providers: buildLegacyAsyncTransportProviders(),
1820
- controllers: [createSseController("/events")]
1821
- };
1822
- }
1823
- exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1824
- /**
1825
- * Validate a raw async factory result, enforce the optional synchronous
1826
- * `transport` hint, apply defaults, and log the bootstrap line.
1827
- *
1828
- * @throws when the factory returned nothing, the options are invalid, or the
1829
- * resolved transport disagrees with the synchronous hint used to gate
1830
- * provider registration.
1831
- */
1832
- static resolveAsyncOptions(raw, transportHint, instanceId, source) {
1833
- if (!raw) {
1834
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1835
- }
1836
- validateOptions(raw);
1837
- if (transportHint !== void 0 && raw.transport !== transportHint) {
1838
- throw new Error(
1839
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync transport hint '${transportHint}' does not match the resolved transport '${raw.transport}'`
1840
- );
1841
- }
1842
- const resolved = applyDefaults(raw);
1843
- exports.BymaxRealtimeModule.logger.log(
1844
- `Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
1845
- );
1846
- return resolved;
1847
- }
1848
- /**
1849
- * Configure the module synchronously.
1850
- *
1851
- * @example
1852
- * ```ts
1853
- * BymaxRealtimeModule.forRoot({
1854
- * transport: 'sse',
1855
- * authenticator: new MyAuthenticator(),
1856
- * })
1857
- * ```
1858
- */
1859
- static forRoot(options) {
1860
- validateOptions(options);
1861
- const resolved = applyDefaults(options);
1862
- const instanceId = crypto.randomUUID();
1863
- if (!resolved.pubsub && process.env["NODE_ENV"] === "production") {
1864
- exports.BymaxRealtimeModule.logger.warn(
1865
- "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1866
- );
1867
- }
1868
- const common = buildCommonProviders(resolved, instanceId);
1869
- const {
1870
- providers: transportProviders,
1871
- controllers,
1872
- gateways
1873
- } = buildTransportProviders(resolved);
1874
- exports.BymaxRealtimeModule.logger.log(
1875
- `Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
1876
- );
1877
- return {
1878
- module: exports.BymaxRealtimeModule,
1879
- controllers: controllers.map((ep) => createSseController(ep)),
1880
- providers: [...common, ...transportProviders, ...gateways],
1881
- exports: [
1882
- exports.RealtimeService,
1883
- exports.ConnectionRegistry,
1884
- REALTIME_OPTIONS_TOKEN,
1885
- REALTIME_INSTANCE_ID_TOKEN,
1886
- REALTIME_AUTHENTICATOR_TOKEN,
1887
- REALTIME_PUBSUB_TOKEN,
1888
- REALTIME_HOOKS_TOKEN,
1889
- REALTIME_OFFLINE_QUEUE_TOKEN,
1890
- REALTIME_PRESENCE_TOKEN,
1891
- REALTIME_TRANSPORT_TOKEN
1892
- ]
1893
- };
1894
- }
1895
- /**
1896
- * Configure the module asynchronously so consumers can resolve options (and
1897
- * the authenticator) through DI — `ConfigService`, `JwtService`, a Redis
1898
- * client, etc.
1899
- *
1900
- * Options are validated and defaulted **inside** the resolving factory, so a
1901
- * malformed configuration rejects via the Promise at bootstrap time and the
1902
- * application fails to start with a clear error.
1903
- *
1904
- * Controllers are registered at decoration time, so the async path binds the
1905
- * SSE controller to the fixed default endpoint `/events`. Consumers that need
1906
- * a non-default endpoint with async configuration should use `forRoot` and
1907
- * pre-resolve the options before passing them.
1908
- *
1909
- * Pass a synchronous `transport` hint to gate WebSocket wiring exactly as
1910
- * `forRoot` does — an SSE-only application then never registers the gateway,
1911
- * never boots Socket.IO, and never requires the optional WS peer deps. Without
1912
- * the hint, every transport provider is registered and the active one is
1913
- * resolved at runtime from the factory result.
1914
- *
1915
- * @example
1916
- * ```ts
1917
- * BymaxRealtimeModule.forRootAsync({
1918
- * transport: 'sse',
1919
- * imports: [ConfigModule],
1920
- * inject: [ConfigService],
1921
- * useFactory: async (cfg: ConfigService) => ({
1922
- * transport: 'sse',
1923
- * authenticator: new CookieJwtAuthenticator(cfg.get('JWT_SECRET')!),
1924
- * }),
1925
- * })
1926
- * ```
1927
- */
1928
- static forRootAsync(asyncOptions) {
1929
- const patterns = [
1930
- asyncOptions.useFactory,
1931
- asyncOptions.useClass,
1932
- asyncOptions.useExisting
1933
- ].filter((pattern) => pattern !== void 0);
1934
- if (patterns.length !== 1) {
1935
- throw new Error(
1936
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1937
- );
1938
- }
1939
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1940
- const instanceId = crypto.randomUUID();
1941
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
1942
- provide: REALTIME_OPTIONS_TOKEN,
1943
- useFactory: async (...args) => exports.BymaxRealtimeModule.resolveAsyncOptions(
1944
- await asyncOptions.useFactory(...args),
1945
- asyncOptions.transport,
1946
- instanceId,
1947
- "useFactory"
1948
- ),
1949
- inject: [...asyncOptions.inject ?? []]
1950
- } : {
1951
- provide: REALTIME_OPTIONS_TOKEN,
1952
- useFactory: async (factory) => exports.BymaxRealtimeModule.resolveAsyncOptions(
1953
- await factory.createRealtimeOptions(),
1954
- asyncOptions.transport,
1955
- instanceId,
1956
- "options factory"
1957
- ),
1958
- inject: [asyncOptions.useClass ? FACTORY_TOKEN : asyncOptions.useExisting]
1959
- };
1960
- const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1961
- const authenticatorProvider = {
1962
- provide: REALTIME_AUTHENTICATOR_TOKEN,
1963
- useFactory: (opts) => opts.authenticator,
1964
- inject: [REALTIME_OPTIONS_TOKEN]
1965
- };
1966
- const pubsubProvider = {
1967
- provide: REALTIME_PUBSUB_TOKEN,
1968
- useFactory: (opts) => {
1969
- if (!opts.pubsub && process.env["NODE_ENV"] === "production") {
1970
- exports.BymaxRealtimeModule.logger.warn(
1971
- "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1972
- );
1973
- }
1974
- return opts.pubsub ?? new exports.InMemoryPubSub();
1975
- },
1976
- inject: [REALTIME_OPTIONS_TOKEN]
1977
- };
1978
- const hooksProvider = {
1979
- provide: REALTIME_HOOKS_TOKEN,
1980
- useFactory: (opts) => opts.hooks ?? {},
1981
- inject: [REALTIME_OPTIONS_TOKEN]
1982
- };
1983
- const offlineQueueProvider = {
1984
- provide: REALTIME_OFFLINE_QUEUE_TOKEN,
1985
- useFactory: (opts) => opts.offlineQueue,
1986
- inject: [REALTIME_OPTIONS_TOKEN]
1987
- };
1988
- const presenceProvider = {
1989
- provide: REALTIME_PRESENCE_TOKEN,
1990
- useFactory: (opts) => opts.presence,
1991
- inject: [REALTIME_OPTIONS_TOKEN]
1992
- };
1993
- const { providers: transportProviders, controllers } = buildAsyncTransportProviders(
1994
- asyncOptions.transport
1995
- );
1996
- const providers = [
1997
- ...factoryClassProvider,
1998
- resolvedOptionsProvider,
1999
- authenticatorProvider,
2000
- pubsubProvider,
2001
- hooksProvider,
2002
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2003
- offlineQueueProvider,
2004
- presenceProvider,
2005
- exports.ConnectionRegistry,
2006
- RoomRegistry,
2007
- EventIdGenerator,
2008
- EventReplayBuffer,
2009
- HeartbeatService,
2010
- exports.RealtimeService,
2011
- ReauthenticationService,
2012
- OfflineQueueDeliveryService,
2013
- ...transportProviders,
2014
- ...asyncOptions.extraProviders ?? []
2015
- ];
2016
- return {
2017
- module: exports.BymaxRealtimeModule,
2018
- imports: asyncOptions.imports ?? [],
2019
- providers,
2020
- controllers,
2021
- exports: [
2022
- exports.RealtimeService,
2023
- exports.ConnectionRegistry,
2024
- REALTIME_OPTIONS_TOKEN,
2025
- REALTIME_INSTANCE_ID_TOKEN,
2026
- REALTIME_AUTHENTICATOR_TOKEN,
2027
- REALTIME_PUBSUB_TOKEN,
2028
- REALTIME_HOOKS_TOKEN,
2029
- REALTIME_OFFLINE_QUEUE_TOKEN,
2030
- REALTIME_PRESENCE_TOKEN,
2031
- REALTIME_TRANSPORT_TOKEN
2032
- ]
2033
- };
2034
- }
2035
- };
2036
- __publicField(exports.BymaxRealtimeModule, "logger", new common.Logger(exports.BymaxRealtimeModule.name));
2037
- exports.BymaxRealtimeModule = __decorateClass([
2038
- common.Global(),
2039
- common.Module({})
2040
- ], exports.BymaxRealtimeModule);
2041
-
2042
- // src/server/pubsub/redis-realtime-pubsub.ts
2043
- var RedisRealtimePubSub = class {
2044
- pub;
2045
- channel;
2046
- subInit = null;
2047
- handlers = /* @__PURE__ */ new Set();
2048
- constructor(options) {
2049
- this.pub = options.client;
2050
- this.channel = options.channel ?? "bymax:realtime";
2051
- }
2052
- /** JSON-encodes the message and PUBLISHes it to the configured channel. */
2053
- async publish(message) {
2054
- await this.pub.publish(this.channel, JSON.stringify(message));
2055
- }
2056
- /**
2057
- * Lazily creates the single shared subscribe client on first call; returns an async
2058
- * unsubscribe that quits the client when the last handler is removed. Concurrent
2059
- * subscribe calls are idempotent — only one client is ever created. Malformed
2060
- * payloads are dropped silently.
2061
- *
2062
- * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
2063
- * the handler registration is rolled back and the cached init promise is cleared so
2064
- * the next call retries from scratch.
2065
- */
2066
- async subscribe(handler) {
2067
- this.handlers.add(handler);
2068
- let sub;
2069
- try {
2070
- sub = await this.ensureSubscriber();
2071
- } catch (err) {
2072
- this.handlers.delete(handler);
2073
- this.subInit = null;
2074
- throw err;
2075
- }
2076
- return async () => {
2077
- this.handlers.delete(handler);
2078
- if (this.handlers.size === 0) {
2079
- this.subInit = null;
2080
- try {
2081
- await sub.quit();
2082
- } catch {
2083
- }
2084
- }
2085
- };
2086
- }
2087
- /** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
2088
- ensureSubscriber() {
2089
- if (!this.subInit) this.subInit = this.createSubscriber();
2090
- return this.subInit;
2091
- }
2092
- async createSubscriber() {
2093
- const sub = this.pub.duplicate();
2094
- await sub.subscribe(this.channel);
2095
- sub.on("message", (_ch, payload) => this.dispatch(payload));
2096
- return sub;
2097
- }
2098
- dispatch(payload) {
2099
- let msg;
2100
- try {
2101
- msg = JSON.parse(payload);
2102
- } catch {
2103
- return;
2104
- }
2105
- for (const h of this.handlers) {
2106
- try {
2107
- h(msg);
2108
- } catch {
2109
- }
2110
- }
2111
- }
2112
- };
2113
-
2114
- // src/server/offline-queue/redis-offline-queue.ts
2115
- var RedisOfflineQueue = class _RedisOfflineQueue {
2116
- client;
2117
- maxPerUser;
2118
- ttlSeconds;
2119
- /** Zero-pad width for the epoch-millisecond component of the sort key. */
2120
- static MS_PAD = 16;
2121
- /** Zero-pad width for the intra-millisecond counter component of the sort key. */
2122
- static COUNTER_PAD = 6;
2123
- constructor(options) {
2124
- this.client = options.client;
2125
- this.maxPerUser = options.maxPerUser ?? 500;
2126
- this.ttlSeconds = options.ttlSeconds ?? 3600;
2127
- }
2128
- key(userId) {
2129
- return `bymax:oq:${userId}`;
2130
- }
2131
- /**
2132
- * Build the fixed-width lexicographic sort key for an event id.
2133
- *
2134
- * Handles two id formats:
2135
- * - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
2136
- * - Legacy plain numeric strings: `1700000000000`
2137
- */
2138
- lexKey(id) {
2139
- const dashIdx = id.indexOf("-");
2140
- const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
2141
- const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
2142
- return String(ms).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(counter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
2143
- }
2144
- /**
2145
- * Return the lexicographically next sort key after `id`, used as an
2146
- * inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
2147
- */
2148
- lexKeyNext(id) {
2149
- const dashIdx = id.indexOf("-");
2150
- const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
2151
- const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
2152
- const counterMax = 10 ** _RedisOfflineQueue.COUNTER_PAD - 1;
2153
- const nextMs = counter < counterMax ? ms : ms + 1;
2154
- const nextCounter = counter < counterMax ? counter + 1 : 0;
2155
- return String(nextMs).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(nextCounter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
2156
- }
2157
- /** Encode an event into a lexicographically sortable ZSET member string. */
2158
- encodeMember(event) {
2159
- return `${this.lexKey(event.id)}|${JSON.stringify(event)}`;
2160
- }
2161
- async append(userId, event) {
2162
- const key = this.key(userId);
2163
- const pipeline = this.client.pipeline();
2164
- pipeline.zadd(key, 0, this.encodeMember(event));
2165
- pipeline.zremrangebyrank(key, 0, -(this.maxPerUser + 1));
2166
- pipeline.expire(key, this.ttlSeconds);
2167
- const results = await pipeline.exec() ?? [];
2168
- for (const [error] of results) {
2169
- if (error) throw error;
2170
- }
2171
- }
2172
- async retrieveSince(userId, sinceId, limit) {
2173
- const lowerBound = `[${this.lexKeyNext(sinceId)}`;
2174
- const raw = await this.client.zrangebylex(this.key(userId), lowerBound, "+", "LIMIT", 0, limit);
2175
- return raw.map(
2176
- (entry) => JSON.parse(
2177
- entry.slice(entry.indexOf("|") + 1),
2178
- (k, value) => k === "emittedAt" ? new Date(value) : value
2179
- )
2180
- );
2181
- }
2182
- async acknowledge(userId, upToId) {
2183
- const upperBound = `(${this.lexKeyNext(upToId)}`;
2184
- const toRemove = await this.client.zrangebylex(this.key(userId), "-", upperBound);
2185
- if (toRemove.length > 0) {
2186
- await this.client.zrem(this.key(userId), ...toRemove);
2187
- }
2188
- }
2189
- };
2190
- var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
2191
- logger = new common.Logger(_RealtimeIoAdapter.name);
2192
- options;
2193
- constructor(app) {
2194
- super(app);
2195
- this.options = app.get(REALTIME_OPTIONS_TOKEN);
2196
- }
2197
- /**
2198
- * Bind the gateway to `websocket.namespace` when configured.
2199
- *
2200
- * `@WebSocketGateway()` args are evaluated at class-decoration time — before
2201
- * the module options resolve — so the namespace cannot be declared there.
2202
- * Instead we build the root server via `super.create` (which routes through the
2203
- * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
2204
- * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
2205
- * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
2206
- * namespace leaves the root server untouched.
2207
- */
2208
- create(port, options) {
2209
- const server = super.create(port, options);
2210
- const ns = this.options.websocket?.namespace;
2211
- if (ns && ns !== "/" && typeof server.of === "function") {
2212
- return server.of(ns);
2213
- }
2214
- return server;
2215
- }
2216
- /**
2217
- * Create the Socket.IO server with merged WebSocket options.
2218
- *
2219
- * When `websocket.redisAdapter.pubClient` is set, installs the
2220
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
2221
- * dep — its absence does not crash the lib).
2222
- */
2223
- createIOServer(port, opts) {
2224
- const wsOpts = this.options.websocket ?? {};
2225
- const mergedOpts = {
2226
- ...opts,
2227
- cors: wsOpts.cors ?? opts?.cors,
2228
- pingInterval: wsOpts.pingIntervalMs ?? 25e3,
2229
- pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
2230
- maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
2231
- };
2232
- const server = super.createIOServer(port, mergedOpts);
2233
- if (wsOpts.redisAdapter?.pubClient) {
2234
- this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
2235
- }
2236
- return server;
2237
- }
2238
- /**
2239
- * Lazily load and install `@socket.io/redis-adapter`.
2240
- *
2241
- * Uses a dynamic `require` so the package stays optional — absent peers do
2242
- * not crash the lib. A load or install failure is logged and tolerated;
2243
- * the lib degrades gracefully to single-instance mode.
2244
- */
2245
- installRedisAdapter(server, pubClient) {
2246
- try {
2247
- const { createAdapter } = __require("@socket.io/redis-adapter");
2248
- const pub = pubClient;
2249
- const sub = pub.duplicate();
2250
- server.adapter(createAdapter(pub, sub));
2251
- this.logger.log(
2252
- "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
2253
- );
2254
- } catch (err) {
2255
- this.logger.error(
2256
- `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
2257
- );
2258
- }
2259
- }
2260
- };
2261
-
2262
- exports.REALTIME_AUTHENTICATOR_TOKEN = REALTIME_AUTHENTICATOR_TOKEN;
2263
- exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
2264
- exports.REALTIME_HOOKS_TOKEN = REALTIME_HOOKS_TOKEN;
2265
- exports.REALTIME_INSTANCE_ID_TOKEN = REALTIME_INSTANCE_ID_TOKEN;
2266
- exports.REALTIME_OFFLINE_QUEUE_TOKEN = REALTIME_OFFLINE_QUEUE_TOKEN;
2267
- exports.REALTIME_OPTIONS_TOKEN = REALTIME_OPTIONS_TOKEN;
2268
- exports.REALTIME_PRESENCE_TOKEN = REALTIME_PRESENCE_TOKEN;
2269
- exports.REALTIME_PUBSUB_TOKEN = REALTIME_PUBSUB_TOKEN;
2270
- exports.REALTIME_TRANSPORT_TOKEN = REALTIME_TRANSPORT_TOKEN;
2271
- exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
2272
- exports.ROOM_PREFIXES = ROOM_PREFIXES;
2273
- exports.RealtimeIoAdapter = RealtimeIoAdapter;
2274
- exports.RedisOfflineQueue = RedisOfflineQueue;
2275
- exports.RedisRealtimePubSub = RedisRealtimePubSub;
2276
- exports.composeRoomId = composeRoomId;
7
+ Object.defineProperty(exports, "BymaxRealtimeModule", {
8
+ enumerable: true,
9
+ get: function () { return internal.BymaxRealtimeModule; }
10
+ });
11
+ Object.defineProperty(exports, "ConnectionRegistry", {
12
+ enumerable: true,
13
+ get: function () { return internal.ConnectionRegistry; }
14
+ });
15
+ Object.defineProperty(exports, "InMemoryPubSub", {
16
+ enumerable: true,
17
+ get: function () { return internal.InMemoryPubSub; }
18
+ });
19
+ Object.defineProperty(exports, "REALTIME_AUTHENTICATOR_TOKEN", {
20
+ enumerable: true,
21
+ get: function () { return internal.REALTIME_AUTHENTICATOR_TOKEN; }
22
+ });
23
+ Object.defineProperty(exports, "REALTIME_ERROR_CODES", {
24
+ enumerable: true,
25
+ get: function () { return internal.REALTIME_ERROR_CODES; }
26
+ });
27
+ Object.defineProperty(exports, "REALTIME_HOOKS_TOKEN", {
28
+ enumerable: true,
29
+ get: function () { return internal.REALTIME_HOOKS_TOKEN; }
30
+ });
31
+ Object.defineProperty(exports, "REALTIME_INSTANCE_ID_TOKEN", {
32
+ enumerable: true,
33
+ get: function () { return internal.REALTIME_INSTANCE_ID_TOKEN; }
34
+ });
35
+ Object.defineProperty(exports, "REALTIME_OFFLINE_QUEUE_TOKEN", {
36
+ enumerable: true,
37
+ get: function () { return internal.REALTIME_OFFLINE_QUEUE_TOKEN; }
38
+ });
39
+ Object.defineProperty(exports, "REALTIME_OPTIONS_TOKEN", {
40
+ enumerable: true,
41
+ get: function () { return internal.REALTIME_OPTIONS_TOKEN; }
42
+ });
43
+ Object.defineProperty(exports, "REALTIME_PRESENCE_TOKEN", {
44
+ enumerable: true,
45
+ get: function () { return internal.REALTIME_PRESENCE_TOKEN; }
46
+ });
47
+ Object.defineProperty(exports, "REALTIME_PUBSUB_TOKEN", {
48
+ enumerable: true,
49
+ get: function () { return internal.REALTIME_PUBSUB_TOKEN; }
50
+ });
51
+ Object.defineProperty(exports, "REALTIME_TRANSPORT_TOKEN", {
52
+ enumerable: true,
53
+ get: function () { return internal.REALTIME_TRANSPORT_TOKEN; }
54
+ });
55
+ Object.defineProperty(exports, "RESERVED_EVENT_NAMES", {
56
+ enumerable: true,
57
+ get: function () { return internal.RESERVED_EVENT_NAMES; }
58
+ });
59
+ Object.defineProperty(exports, "ROOM_PREFIXES", {
60
+ enumerable: true,
61
+ get: function () { return internal.ROOM_PREFIXES; }
62
+ });
63
+ Object.defineProperty(exports, "RealtimeService", {
64
+ enumerable: true,
65
+ get: function () { return internal.RealtimeService; }
66
+ });
67
+ Object.defineProperty(exports, "RedisOfflineQueue", {
68
+ enumerable: true,
69
+ get: function () { return internal.RedisOfflineQueue; }
70
+ });
71
+ Object.defineProperty(exports, "RedisRealtimePubSub", {
72
+ enumerable: true,
73
+ get: function () { return internal.RedisRealtimePubSub; }
74
+ });
75
+ Object.defineProperty(exports, "composeRoomId", {
76
+ enumerable: true,
77
+ get: function () { return internal.composeRoomId; }
78
+ });