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