@bymax-one/nest-realtime 1.0.2 → 1.0.4

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