@bymax-one/nest-realtime 1.2.7 → 1.2.8

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.
@@ -49,6 +49,21 @@ function applyDefaults(options) {
49
49
  sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
50
50
  });
51
51
  }
52
+
53
+ // src/server/constants/injection-tokens.constants.ts
54
+ var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
55
+ var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
56
+ var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
57
+ var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
58
+ var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
59
+ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
60
+ var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
61
+ var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
62
+ var DEFAULT_HEARTBEAT_MS = 3e4;
63
+ var HEARTBEAT_MIN_MS = 5e3;
64
+ var HEARTBEAT_MAX_MS = 9e4;
65
+
66
+ // src/server/config/validate-options.ts
52
67
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
53
68
  function validateOptions(options) {
54
69
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
@@ -80,9 +95,10 @@ function validateReauthPolicy(options) {
80
95
  }
81
96
  function validateSseOptions(options) {
82
97
  const sse = options.sse;
83
- if (sse?.heartbeatMs !== void 0 && sse.heartbeatMs <= 0) {
98
+ const heartbeatMs = sse?.heartbeatMs;
99
+ if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
84
100
  throw new Error(
85
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be > 0`
101
+ `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
86
102
  );
87
103
  }
88
104
  if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
@@ -97,17 +113,6 @@ function validateSseOptions(options) {
97
113
  }
98
114
  }
99
115
 
100
- // src/server/constants/injection-tokens.constants.ts
101
- var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
102
- var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
103
- var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
104
- var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
105
- var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
106
- var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
107
- var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
108
- var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
109
- var DEFAULT_HEARTBEAT_MS = 3e4;
110
-
111
116
  // src/server/utils/describe-error.ts
112
117
  function describeError(reason) {
113
118
  try {
@@ -140,19 +145,6 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
140
145
  storage;
141
146
  hooks;
142
147
  logger = new common.Logger(exports.OfflineQueueDeliveryService.name);
143
- /**
144
- * Return events for `userId` that arrived after `lastEventId` and are NOT
145
- * already covered by `ringBufferIds` (already replayed from in-memory buffer).
146
- *
147
- * Retrieval does NOT acknowledge: the durable queue is pruned only after the events
148
- * have been emitted to a live subscriber via {@link acknowledge}. This guarantees
149
- * at-least-once delivery — events that never reach the client are never lost.
150
- *
151
- * @param userId - The reconnecting user.
152
- * @param lastEventId - The `Last-Event-ID` header value.
153
- * @param ringBufferIds - Set of event ids already replayed from the ring buffer.
154
- * @returns Gap events, or an empty array when no offline queue is configured.
155
- */
156
148
  async retrieve(userId, lastEventId, ringBufferIds) {
157
149
  if (!this.storage) return [];
158
150
  let events;
@@ -178,17 +170,6 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
178
170
  }
179
171
  return events.filter((e) => !ringBufferIds.has(e.id));
180
172
  }
181
- /**
182
- * Acknowledge delivered offline events so the storage backend can prune them.
183
- *
184
- * At-least-once contract: call this ONLY after the events have been emitted to a
185
- * still-open subscriber. Acknowledging before emission would permanently drop events
186
- * that never reached the client. A failure is swallowed (logged) so a transient
187
- * storage error never disrupts delivery; the events simply redeliver on reconnect.
188
- *
189
- * @param userId - The user whose queue is acknowledged.
190
- * @param events - The delivered gap events; the last id is the prune watermark.
191
- */
192
173
  async acknowledge(userId, events) {
193
174
  if (!this.storage || events.length === 0) return;
194
175
  const lastId = events[events.length - 1].id;
@@ -278,11 +259,6 @@ exports.ConnectionRegistry = class ConnectionRegistry {
278
259
  byId = /* @__PURE__ */ new Map();
279
260
  byUserId = /* @__PURE__ */ new Map();
280
261
  byTenantId = /* @__PURE__ */ new Map();
281
- /**
282
- * Register a connection and index it by user and tenant.
283
- *
284
- * @internal Transport bookkeeping: applications must not call it.
285
- */
286
262
  register(record) {
287
263
  this.byId.set(record.connectionId, record);
288
264
  this.addToSetMap(this.byUserId, record.userId, record.connectionId);
@@ -290,11 +266,6 @@ exports.ConnectionRegistry = class ConnectionRegistry {
290
266
  this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
291
267
  }
292
268
  }
293
- /**
294
- * Remove a connection from every index. Returns the removed record, if any.
295
- *
296
- * @internal Transport bookkeeping: applications must not call it.
297
- */
298
269
  unregister(connectionId) {
299
270
  const record = this.byId.get(connectionId);
300
271
  if (!record) return void 0;
@@ -305,27 +276,21 @@ exports.ConnectionRegistry = class ConnectionRegistry {
305
276
  }
306
277
  return record;
307
278
  }
308
- /** Look up a single connection by id. */
309
279
  get(connectionId) {
310
280
  return this.byId.get(connectionId);
311
281
  }
312
- /** All connections of a user, optionally filtered by transport. */
313
282
  byUser(userId, transport) {
314
283
  return this.resolve(this.byUserId.get(userId), transport);
315
284
  }
316
- /** All connections of a tenant, optionally filtered by transport. */
317
285
  byTenant(tenantId, transport) {
318
286
  return this.resolve(this.byTenantId.get(tenantId), transport);
319
287
  }
320
- /** All connections of a given transport. */
321
288
  allByTransport(transport) {
322
289
  return Array.from(this.byId.values()).filter((record) => record.transport === transport);
323
290
  }
324
- /** Total number of active connections. */
325
291
  count() {
326
292
  return this.byId.size;
327
293
  }
328
- /** Number of distinct users currently connected. */
329
294
  countUsers() {
330
295
  return this.byUserId.size;
331
296
  }
@@ -359,7 +324,6 @@ var COUNTER_WIDTH = 6;
359
324
  exports.EventIdGenerator = class EventIdGenerator {
360
325
  lastMs = 0;
361
326
  counter = 0;
362
- /** Produce the next monotonic event id. */
363
327
  next() {
364
328
  const now = Date.now();
365
329
  if (now === this.lastMs) {
@@ -377,7 +341,6 @@ exports.EventIdGenerator = __decorateClass([
377
341
  exports.RoomRegistry = class RoomRegistry {
378
342
  rooms = /* @__PURE__ */ new Map();
379
343
  connectionRooms = /* @__PURE__ */ new Map();
380
- /** Join a connection to a room (idempotent). */
381
344
  join(connectionId, roomId) {
382
345
  const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
383
346
  room.add(connectionId);
@@ -386,7 +349,6 @@ exports.RoomRegistry = class RoomRegistry {
386
349
  conn.add(roomId);
387
350
  this.connectionRooms.set(connectionId, conn);
388
351
  }
389
- /** Remove a connection from a room (idempotent); prunes empty entries. */
390
352
  leave(connectionId, roomId) {
391
353
  const room = this.rooms.get(roomId);
392
354
  if (room) {
@@ -399,17 +361,14 @@ exports.RoomRegistry = class RoomRegistry {
399
361
  if (conn.size === 0) this.connectionRooms.delete(connectionId);
400
362
  }
401
363
  }
402
- /** Snapshot of a room's members — safe to iterate while membership mutates. */
403
364
  members(roomId) {
404
365
  const set = this.rooms.get(roomId);
405
366
  return set ? Array.from(set) : [];
406
367
  }
407
- /** Snapshot of the rooms a connection currently belongs to. */
408
368
  roomsOf(connectionId) {
409
369
  const set = this.connectionRooms.get(connectionId);
410
370
  return set ? Array.from(set) : [];
411
371
  }
412
- /** Remove a connection from every room (called on disconnect). */
413
372
  leaveAll(connectionId) {
414
373
  const rooms = this.connectionRooms.get(connectionId);
415
374
  if (!rooms) return;
@@ -422,7 +381,6 @@ exports.RoomRegistry = class RoomRegistry {
422
381
  }
423
382
  this.connectionRooms.delete(connectionId);
424
383
  }
425
- /** Total number of distinct rooms. */
426
384
  countRooms() {
427
385
  return this.rooms.size;
428
386
  }
@@ -449,14 +407,6 @@ function unavailableError(code, who, what, cause) {
449
407
  }
450
408
  exports.InMemoryPubSub = class InMemoryPubSub {
451
409
  handlers = /* @__PURE__ */ new Set();
452
- /**
453
- * Publish a message to all subscribed handlers.
454
- *
455
- * Delivery is deferred one microtask so a handler that enqueues further publishes
456
- * does not deepen the current call stack. One handler's failure does not block others.
457
- *
458
- * @param message - The pub/sub message to fan out.
459
- */
460
410
  async publish(message) {
461
411
  await Promise.resolve();
462
412
  for (const handler of this.handlers) {
@@ -466,12 +416,6 @@ exports.InMemoryPubSub = class InMemoryPubSub {
466
416
  }
467
417
  }
468
418
  }
469
- /**
470
- * Subscribe to pub/sub messages.
471
- *
472
- * @param handler - Called for every published message.
473
- * @returns An async unsubscribe function that removes this handler.
474
- */
475
419
  async subscribe(handler) {
476
420
  this.handlers.add(handler);
477
421
  return async () => {
@@ -489,7 +433,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
489
433
  }
490
434
  opts;
491
435
  buffers = /* @__PURE__ */ new Map();
492
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
493
436
  append(userId, event) {
494
437
  const buf = this.buffers.get(userId) ?? [];
495
438
  buf.push(event);
@@ -497,12 +440,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
497
440
  if (buf.length > cap) buf.shift();
498
441
  this.buffers.set(userId, buf);
499
442
  }
500
- /**
501
- * Return the events emitted after `lastEventId`.
502
- *
503
- * Returns an empty array when the user has no buffer, or when `lastEventId` is
504
- * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
505
- */
506
443
  since(userId, lastEventId) {
507
444
  const buf = this.buffers.get(userId);
508
445
  if (!buf) return [];
@@ -510,7 +447,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
510
447
  if (idx === -1) return [];
511
448
  return buf.slice(idx + 1);
512
449
  }
513
- /** Number of events currently buffered for a user (diagnostics). */
514
450
  size(userId) {
515
451
  return this.buffers.get(userId)?.length ?? 0;
516
452
  }
@@ -520,19 +456,8 @@ exports.EventReplayBuffer = __decorateClass([
520
456
  __decorateParam(0, common.Inject(REALTIME_OPTIONS_TOKEN))
521
457
  ], exports.EventReplayBuffer);
522
458
  var KEEPALIVE_COMMENT = ": keepalive\n\n";
523
- var HEARTBEAT_MIN_MS = 5e3;
524
- var HEARTBEAT_MAX_MS = 9e4;
525
459
  exports.HeartbeatService = class HeartbeatService {
526
460
  timers = /* @__PURE__ */ new Map();
527
- /**
528
- * Start writing keepalives for a connection every `intervalMs`.
529
- *
530
- * @param connectionId - Unique connection identifier used to track the timer.
531
- * @param res - The writable response stream (or any object with a `write` method).
532
- * @param intervalMs - Keepalive interval in milliseconds; must be within
533
- * `[5_000, 90_000]`.
534
- * @throws {Error} When `intervalMs` is outside the valid range.
535
- */
536
461
  start(connectionId, res, intervalMs) {
537
462
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
538
463
  throw new Error(
@@ -550,7 +475,6 @@ exports.HeartbeatService = class HeartbeatService {
550
475
  timer.unref();
551
476
  this.timers.set(connectionId, timer);
552
477
  }
553
- /** Stop and clear the keepalive timer for a connection (idempotent). */
554
478
  stop(connectionId) {
555
479
  const timer = this.timers.get(connectionId);
556
480
  if (timer) {
@@ -558,7 +482,6 @@ exports.HeartbeatService = class HeartbeatService {
558
482
  this.timers.delete(connectionId);
559
483
  }
560
484
  }
561
- /** Stop every keepalive timer (used on shutdown). */
562
485
  stopAll() {
563
486
  for (const timer of this.timers.values()) clearInterval(timer);
564
487
  this.timers.clear();
@@ -596,32 +519,21 @@ exports.SseTransport = class SseTransport {
596
519
  offlineQueue;
597
520
  kind = "sse";
598
521
  logger = new common.Logger(exports.SseTransport.name);
599
- /** Tear down every SSE connection and stop heartbeat on process shutdown. */
600
522
  async onApplicationShutdown() {
601
523
  this.heartbeat.stopAll();
602
524
  for (const conn of this.connections.allByTransport("sse")) {
603
525
  await this.disconnectLocal(conn.connectionId);
604
526
  }
605
527
  }
606
- /** The resolved heartbeat interval for this transport. */
607
528
  get heartbeatMs() {
608
529
  return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
609
530
  }
610
- /** Whether the `connection:established` event should be emitted on connect. */
611
531
  get emitConnectionEvent() {
612
532
  return this.options.sse?.emitConnectionEvent !== false;
613
533
  }
614
- /** Authenticate a connection through the consumer-provided authenticator. */
615
534
  authenticate(context) {
616
535
  return this.auth.authenticate(context);
617
536
  }
618
- /**
619
- * Register an authenticated SSE connection and auto-join its user/tenant rooms.
620
- *
621
- * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
622
- * lifecycle hook is fired by the subscription handler after this returns, so that the
623
- * handler can carry a consistent connection record reference.
624
- */
625
537
  async registerConnection(params) {
626
538
  const record = {
627
539
  connectionId: params.connectionId,
@@ -647,7 +559,6 @@ exports.SseTransport = class SseTransport {
647
559
  }
648
560
  await this.evictBeyondLimit(params.auth.userId);
649
561
  }
650
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
651
562
  async unregisterConnection(connectionId, reason) {
652
563
  const record = this.connections.unregister(connectionId);
653
564
  if (!record) return;
@@ -671,39 +582,15 @@ exports.SseTransport = class SseTransport {
671
582
  this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
672
583
  }
673
584
  }
674
- /** Replay the events a user missed after `lastEventId`. */
675
585
  getReplayEvents(userId, lastEventId) {
676
586
  return this.replayBuffer.since(userId, lastEventId);
677
587
  }
678
- /**
679
- * All SSE connections for a user — public accessor so external callers can
680
- * inspect or iterate without reaching into a private registry field.
681
- *
682
- * @param userId - The user whose active connections are returned.
683
- * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
684
- */
685
588
  connectionsForUser(userId) {
686
589
  return this.connections.byUser(userId, "sse");
687
590
  }
688
- /**
689
- * Look up a single connection by id.
690
- *
691
- * @param connectionId - The unique connection identifier.
692
- * @returns The `ConnectionRecord`, or `undefined` when not found.
693
- */
694
591
  getConnection(connectionId) {
695
592
  return this.connections.get(connectionId);
696
593
  }
697
- /**
698
- * Emit to a user: live here, to the other instances over the bus, and into the offline queue
699
- * when the user has no live connection on this instance.
700
- *
701
- * A failed publish or a failed append is reported (log and `onDeliveryFailure`) and the call
702
- * still resolves, since delivery to the other instances is at-most-once. It rejects only when
703
- * the event has no delivery path left: the user is offline here, the queue could not keep it,
704
- * and the bus either failed or cannot reach another instance (the in-memory bus). A rejection
705
- * carries the queue failure as its cause and is not also reported to the hook.
706
- */
707
594
  async emitToUser(userId, event, data) {
708
595
  const id = this.idGen.next();
709
596
  this.emitToUserLocal(userId, event, data, id);
@@ -735,7 +622,6 @@ exports.SseTransport = class SseTransport {
735
622
  );
736
623
  }
737
624
  }
738
- /** Append to the offline queue; resolves with the failure, or `undefined` once it is kept. */
739
625
  async tryAppend(queue, userId, event) {
740
626
  try {
741
627
  await queue.append(userId, event);
@@ -744,7 +630,6 @@ exports.SseTransport = class SseTransport {
744
630
  return { error };
745
631
  }
746
632
  }
747
- /** Whether the bus can carry an event to another instance (the in-memory bus cannot). */
748
633
  busReachesOtherInstances() {
749
634
  return !(this.pubsub instanceof exports.InMemoryPubSub);
750
635
  }
@@ -763,24 +648,14 @@ exports.SseTransport = class SseTransport {
763
648
  this.broadcastLocal(event, data, id);
764
649
  await this.publish({ op: "broadcast", args: { event, data, id } });
765
650
  }
766
- /** Join a connection this instance holds to a room; any other id is left alone. */
767
651
  async joinRoom(connectionId, roomId) {
768
652
  if (this.connections.get(connectionId)?.transport === "sse")
769
653
  this.rooms.join(connectionId, roomId);
770
654
  }
771
- /** Remove a connection this instance holds from a room; any other id is left alone. */
772
655
  async leaveRoom(connectionId, roomId) {
773
656
  if (this.connections.get(connectionId)?.transport === "sse")
774
657
  this.rooms.leave(connectionId, roomId);
775
658
  }
776
- /**
777
- * Disconnect a connection locally if owned here, otherwise revoke cross-instance.
778
- *
779
- * Resolves once the connection is closed here or the revocation has been handed to the bus. A
780
- * connection held here as a WebSocket is left to the WebSocket transport and nothing is
781
- * published. It rejects with `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses it: nothing has reached
782
- * the connection, so the caller must not read the resolution as a revocation.
783
- */
784
659
  async disconnect(connectionId, reason) {
785
660
  const record = this.connections.get(connectionId);
786
661
  if (record) {
@@ -802,37 +677,15 @@ exports.SseTransport = class SseTransport {
802
677
  );
803
678
  }
804
679
  }
805
- /**
806
- * Deliver an event to a user's local SSE connections and update the replay buffer.
807
- *
808
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
809
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
810
- */
811
680
  emitToUserLocal(userId, event, data, id) {
812
681
  const message = this.buildMessage(id, event, data);
813
682
  this.replayBuffer.append(userId, message);
814
683
  for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
815
684
  }
816
- /**
817
- * Deliver an event to all local SSE connections for a tenant.
818
- *
819
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
820
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
821
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
822
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
823
- */
824
685
  emitToTenantLocal(tenantId, event, data, id) {
825
686
  const message = this.buildMessage(id, event, data);
826
687
  for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
827
688
  }
828
- /**
829
- * Deliver an event to all local SSE connections that joined the given room.
830
- *
831
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
832
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
833
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
834
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
835
- */
836
689
  emitToRoomLocal(roomId, event, data, id) {
837
690
  const message = this.buildMessage(id, event, data);
838
691
  for (const connectionId of this.rooms.members(roomId)) {
@@ -840,24 +693,10 @@ exports.SseTransport = class SseTransport {
840
693
  if (conn && conn.transport === "sse") this.deliver(conn, message);
841
694
  }
842
695
  }
843
- /**
844
- * Deliver an event to all local SSE connections.
845
- *
846
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
847
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
848
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
849
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
850
- */
851
696
  broadcastLocal(event, data, id) {
852
697
  const message = this.buildMessage(id, event, data);
853
698
  for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
854
699
  }
855
- /**
856
- * Tear down a locally-owned SSE stream, then clean up (no re-publish).
857
- *
858
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
859
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
860
- */
861
700
  async disconnectLocal(connectionId, reason) {
862
701
  const record = this.connections.get(connectionId);
863
702
  if (!record || record.transport !== "sse") return;
@@ -868,7 +707,6 @@ exports.SseTransport = class SseTransport {
868
707
  buildMessage(id, event, data) {
869
708
  return { id, type: event, data };
870
709
  }
871
- /** Deliver to one connection, isolating failures so others still receive the event. */
872
710
  deliver(conn, message) {
873
711
  try {
874
712
  conn.subject?.next(message);
@@ -876,7 +714,6 @@ exports.SseTransport = class SseTransport {
876
714
  this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
877
715
  }
878
716
  }
879
- /** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
880
717
  async tryPublish(message) {
881
718
  try {
882
719
  await this.pubsub.publish({ ...message, origin: this.instanceId });
@@ -885,7 +722,6 @@ exports.SseTransport = class SseTransport {
885
722
  return { error };
886
723
  }
887
724
  }
888
- /** Publish once to the bus. A failure is reported and never fails the live emit path. */
889
725
  async publish(message) {
890
726
  const failure = await this.tryPublish(message);
891
727
  if (failure !== void 0) this.reportPublishFailure(message.op, failure);
@@ -898,7 +734,6 @@ exports.SseTransport = class SseTransport {
898
734
  "pubsub.publish failed"
899
735
  );
900
736
  }
901
- /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
902
737
  async evictBeyondLimit(userId) {
903
738
  const max = this.options.sse?.maxConnectionsPerUser;
904
739
  if (max === void 0 || max <= 0) return;
@@ -997,29 +832,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
997
832
  offlineDelivery;
998
833
  logger = new common.Logger(exports.SseSubscriptionHandler.name);
999
834
  authenticated = /* @__PURE__ */ new WeakMap();
1000
- /**
1001
- * Resolve the tenant this connection routes on, and refuse a blank identity.
1002
- *
1003
- * Both transports resolve the routing tenant through this one function, so a
1004
- * connection carries the same tenant whichever one opened it. The check runs on
1005
- * the resolved value rather than the raw one — validating what the server does not
1006
- * use would validate nothing.
1007
- *
1008
- * A blank identity is the consumer's configuration rather than the client's
1009
- * credentials, so it is deliberately not a 401: a 401 would tell a client its
1010
- * credentials were rejected when they were accepted, inviting a retry that cannot
1011
- * succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
1012
- * once, not an unhandled crash logging a stack on every reconnect.
1013
- *
1014
- * The reason names the operator's fix, so it goes to the server log and the client
1015
- * receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
1016
- * without a message.
1017
- *
1018
- * @param auth - The result the consumer's authenticator returned.
1019
- * @returns The same result with the routing tenant resolved.
1020
- * @throws InternalServerErrorException with the generic body when a trait is present
1021
- * but blank.
1022
- */
1023
835
  resolveAndValidateIdentity(auth) {
1024
836
  const resolvedAuth = resolveAuthTenant(this.options, auth);
1025
837
  try {
@@ -1030,27 +842,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1030
842
  }
1031
843
  return resolvedAuth;
1032
844
  }
1033
- /**
1034
- * Handle an incoming SSE connection request end-to-end.
1035
- *
1036
- * Sets anti-buffering headers, authenticates the request, captures the offline-gap
1037
- * before exposing the connection, then returns an Observable whose subscriber callback
1038
- * wires the downstream listener BEFORE calling `registerConnection` — so a plain
1039
- * `Subject` suffices and the replay buffer cannot grow unboundedly.
1040
- *
1041
- * @param req - The incoming request (SSE GET).
1042
- * @param res - The response (passthrough for header mutations and heartbeat writes).
1043
- * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
1044
- * @throws UnauthorizedException when authentication returns null — the client's
1045
- * credentials were rejected, which is a 401.
1046
- * @throws InternalServerErrorException when the authenticator, or the configured
1047
- * `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
1048
- * a 401: the credentials were accepted and the fault is the consumer's
1049
- * configuration, so it surfaces as a 500 rather than telling a client to retry
1050
- * something that cannot succeed. The exception carries no message, so the client
1051
- * gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
1052
- * written to the server log.
1053
- */
1054
845
  async handle(req, res) {
1055
846
  res.setHeader("Cache-Control", "no-cache, no-transform");
1056
847
  res.setHeader("X-Accel-Buffering", "no");
@@ -1092,10 +883,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1092
883
  queueEvents
1093
884
  });
1094
885
  }
1095
- /**
1096
- * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
1097
- * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
1098
- */
1099
886
  async authenticateBeforeCommit(req) {
1100
887
  try {
1101
888
  this.authenticated.set(req, await this.authenticateRequest(req));
@@ -1103,7 +890,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1103
890
  throw this.toClientError(err, "SSE authentication failed");
1104
891
  }
1105
892
  }
1106
- // Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
1107
893
  toClientError(err, what) {
1108
894
  return err instanceof common.HttpException ? err : this.serverError(err, what);
1109
895
  }
@@ -1117,15 +903,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1117
903
  if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
1118
904
  return { context, auth: this.resolveAndValidateIdentity(auth) };
1119
905
  }
1120
- /**
1121
- * Build the live Observable using a subscribe-before-register pattern.
1122
- *
1123
- * The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
1124
- * already has a listener when `registerConnection` runs. Any `subject.next()` that
1125
- * occurs during or after registration goes directly to the subscriber — nothing is
1126
- * buffered or retained, nothing is dropped, and ordering (established → replay →
1127
- * queue → live) is preserved.
1128
- */
1129
906
  buildStream(p) {
1130
907
  return new rxjs.Observable((subscriber) => {
1131
908
  const inner = this.subscribePipeline(p, subscriber);
@@ -1136,12 +913,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1136
913
  return () => inner.unsubscribe();
1137
914
  });
1138
915
  }
1139
- /**
1140
- * Wire the merged pipeline to the downstream subscriber with teardown.
1141
- *
1142
- * Subscribing first guarantees `subject` has a listener before registration can emit,
1143
- * so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
1144
- */
1145
916
  subscribePipeline(p, subscriber) {
1146
917
  const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
1147
918
  const queueReplay$ = queueEvents.length > 0 ? rxjs.of(...queueEvents.map(toMessageEvent)) : rxjs.EMPTY;
@@ -1159,12 +930,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1159
930
  })
1160
931
  ).subscribe(subscriber);
1161
932
  }
1162
- /**
1163
- * Register the connection (after the subscriber is wired) and activate it on resolution.
1164
- *
1165
- * A registration failure routes to `onError` and errors the stream; a failure that
1166
- * arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
1167
- */
1168
933
  activateConnection(p, subscriber) {
1169
934
  const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
1170
935
  this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
@@ -1174,15 +939,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1174
939
  subscriber.error(this.serverError(err, "SSE registration failed"));
1175
940
  });
1176
941
  }
1177
- /**
1178
- * Complete the connection handshake once registration resolves.
1179
- *
1180
- * Registration is async and can resolve AFTER the downstream subscriber has already
1181
- * torn down (client disconnected mid-handshake). When that happens `finalize` has
1182
- * already stopped the heartbeat and unregistered, so re-firing onConnect or starting
1183
- * a fresh heartbeat would leak the connection and write after close. Guard on
1184
- * `subscriber.closed`: if closed, undo the late registration idempotently and return.
1185
- */
1186
942
  onRegistered(p, subscriber) {
1187
943
  const { connectionId, res } = p;
1188
944
  if (subscriber.closed) {
@@ -1197,12 +953,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1197
953
  const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
1198
954
  this.heartbeat.start(connectionId, res, heartbeatMs);
1199
955
  }
1200
- /**
1201
- * Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
1202
- * so it never disrupts the connection lifecycle or live event delivery.
1203
- *
1204
- * @param invoke - A zero-arg function that calls the hook (handles optionality).
1205
- */
1206
956
  fireHook(invoke) {
1207
957
  void Promise.resolve(invoke()).catch((err) => {
1208
958
  this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
@@ -1243,9 +993,6 @@ function createSseController(endpoint) {
1243
993
  __decorateParam(0, common.Inject(exports.SseSubscriptionHandler))
1244
994
  ], SseAuthGuard);
1245
995
  let DynamicSseController = class {
1246
- // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
1247
- // not emit `design:paramtypes` decorator metadata, so constructor params must
1248
- // be resolved by token rather than by reflected type.
1249
996
  constructor(handler) {
1250
997
  this.handler = handler;
1251
998
  }
@@ -1273,80 +1020,28 @@ exports.RealtimeService = class RealtimeService {
1273
1020
  }
1274
1021
  transport;
1275
1022
  pubsub;
1276
- /**
1277
- * Whether this instance hears the events and revocations other instances publish. False while
1278
- * the bus is unreachable or its subscriber connection is down, so a readiness probe can take a
1279
- * deaf instance out of rotation. True for a bus that does not report a state, and with
1280
- * `transport: 'websocket'`, which does not subscribe to the bus.
1281
- *
1282
- * @example
1283
- * ```ts
1284
- * // In a health indicator: `isHealthy` is false while the instance cannot hear the others.
1285
- * return indicator.check('realtime', realtime.isPubSubReady())
1286
- * ```
1287
- */
1288
1023
  isPubSubReady() {
1289
1024
  if (this.transport.kind === "websocket") return true;
1290
1025
  return this.pubsub?.isSubscribed?.() ?? true;
1291
1026
  }
1292
- /**
1293
- * Send to all of a user's connections (across devices/tabs).
1294
- *
1295
- * @example
1296
- * ```ts
1297
- * await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
1298
- * ```
1299
- */
1300
1027
  emitToUser(userId, event, data) {
1301
1028
  return this.transport.emitToUser(userId, event, data);
1302
1029
  }
1303
- /** Send to every connection in a tenant. */
1304
1030
  emitToTenant(tenantId, event, data) {
1305
1031
  return this.transport.emitToTenant(tenantId, event, data);
1306
1032
  }
1307
- /**
1308
- * Send to a logical room. Use the prefix convention (`user:{id}`,
1309
- * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
1310
- */
1311
1033
  emitToRoom(roomId, event, data) {
1312
1034
  return this.transport.emitToRoom(roomId, event, data);
1313
1035
  }
1314
- /** Send to every connected client. Use sparingly. */
1315
1036
  broadcast(event, data) {
1316
1037
  return this.transport.broadcast(event, data);
1317
1038
  }
1318
- /**
1319
- * Add a specific connection to a room.
1320
- *
1321
- * The room id is not checked. Never pass client-supplied input that could start
1322
- * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1323
- * receives that tenant's events.
1324
- *
1325
- * Acts on a connection this instance holds; for any other id it resolves and changes
1326
- * nothing. A failure of the transport that holds the connection rejects the call.
1327
- */
1328
1039
  joinRoom(connectionId, roomId) {
1329
1040
  return this.transport.joinRoom(connectionId, roomId);
1330
1041
  }
1331
- /**
1332
- * Remove a specific connection from a room.
1333
- *
1334
- * Acts on a connection this instance holds; for any other id it resolves and changes
1335
- * nothing. A failure of the transport that holds the connection rejects the call.
1336
- */
1337
1042
  leaveRoom(connectionId, roomId) {
1338
1043
  return this.transport.leaveRoom(connectionId, roomId);
1339
1044
  }
1340
- /**
1341
- * Force-disconnect a specific connection (e.g. on auth revocation).
1342
- *
1343
- * Resolves once the connection is closed on this instance or the revocation has been handed
1344
- * to the bus for the instance that holds it.
1345
- *
1346
- * @throws {Error} `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the revocation, or
1347
- * `REALTIME_TRANSPORT_UNAVAILABLE` when the transport that holds the connection fails.
1348
- * The connection may still be connected: retry.
1349
- */
1350
1045
  disconnect(connectionId, reason) {
1351
1046
  return this.transport.disconnect(connectionId, reason);
1352
1047
  }
@@ -1378,16 +1073,8 @@ exports.ReauthenticationService = class ReauthenticationService {
1378
1073
  hooks;
1379
1074
  logger = new common.Logger(exports.ReauthenticationService.name);
1380
1075
  timer = null;
1381
- /** connectionId → epoch-ms timestamp of last successful revalidation. */
1382
1076
  positiveCache = /* @__PURE__ */ new Map();
1383
1077
  policy;
1384
- /**
1385
- * Schedule the periodic revalidation cycle.
1386
- *
1387
- * The timer is unref'd so it never keeps the process alive on its own.
1388
- * When the authenticator does not implement `revalidate`, the service stays
1389
- * idle and emits an informative log.
1390
- */
1391
1078
  onModuleInit() {
1392
1079
  if (!this.auth.revalidate) {
1393
1080
  this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
@@ -1401,11 +1088,6 @@ exports.ReauthenticationService = class ReauthenticationService {
1401
1088
  this.timer.unref();
1402
1089
  this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1403
1090
  }
1404
- /**
1405
- * Clear the timer and the positive cache.
1406
- *
1407
- * Called by NestJS on graceful shutdown to prevent leaks.
1408
- */
1409
1091
  onApplicationShutdown() {
1410
1092
  if (this.timer) {
1411
1093
  clearInterval(this.timer);
@@ -1413,15 +1095,6 @@ exports.ReauthenticationService = class ReauthenticationService {
1413
1095
  }
1414
1096
  this.positiveCache.clear();
1415
1097
  }
1416
- /**
1417
- * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
1418
- *
1419
- * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1420
- * refreshes the cache. A negative result (or a thrown error) invokes the configured
1421
- * `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
1422
- *
1423
- * Exposed as public for test access.
1424
- */
1425
1098
  async runCycle() {
1426
1099
  const now = Date.now();
1427
1100
  const connections = [
@@ -1450,11 +1123,6 @@ exports.ReauthenticationService = class ReauthenticationService {
1450
1123
  }
1451
1124
  }
1452
1125
  }
1453
- /**
1454
- * Revoke a connection whose revalidation failed, and keep the cycle going when the
1455
- * revocation itself is rejected. The positive-cache entry is already gone, so the next
1456
- * cycle revalidates the connection and tries again.
1457
- */
1458
1126
  async revoke(conn) {
1459
1127
  try {
1460
1128
  await this.handleFailure(conn);
@@ -1464,7 +1132,6 @@ exports.ReauthenticationService = class ReauthenticationService {
1464
1132
  );
1465
1133
  }
1466
1134
  }
1467
- /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1468
1135
  async handleFailure(conn) {
1469
1136
  this.positiveCache.delete(conn.connectionId);
1470
1137
  if (this.policy.onFailure === "event") {
@@ -1768,52 +1435,9 @@ var sseWiring = {
1768
1435
  }
1769
1436
  };
1770
1437
  exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1771
- /**
1772
- * Configure the module synchronously.
1773
- *
1774
- * @throws when the options are invalid.
1775
- * @example
1776
- * ```ts
1777
- * BymaxRealtimeModule.forRoot({
1778
- * transport: 'sse',
1779
- * authenticator: new MyAuthenticator(),
1780
- * })
1781
- * ```
1782
- */
1783
1438
  static forRoot(options) {
1784
1439
  return composeForRoot(exports.BymaxRealtimeModule, sseWiring, exports.BymaxRealtimeModule.logger, options);
1785
1440
  }
1786
- /**
1787
- * Configure the module asynchronously so options — and the authenticator —
1788
- * can be resolved through DI: `ConfigService`, a Redis client, and so on.
1789
- *
1790
- * Options are validated inside the resolving factory, so a malformed
1791
- * configuration rejects at bootstrap and the application fails to start with
1792
- * a clear error.
1793
- *
1794
- * Controllers are registered at decoration time, so the SSE route comes from
1795
- * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
1796
- * factory resolves — the factory has not run yet when the controller is
1797
- * built. It defaults to `/events`, and a factory that resolves a disagreeing
1798
- * `sse.endpoint` is rejected at bootstrap rather than silently served on
1799
- * another path.
1800
- *
1801
- * @throws when no factory pattern is given, more than one is, or the factory
1802
- * resolves a transport other than `'sse'`.
1803
- * @example
1804
- * ```ts
1805
- * BymaxRealtimeModule.forRootAsync({
1806
- * transport: 'sse',
1807
- * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
1808
- * imports: [ConfigModule],
1809
- * inject: [ConfigService],
1810
- * useFactory: (cfg: ConfigService) => ({
1811
- * transport: 'sse' as const,
1812
- * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
1813
- * }),
1814
- * })
1815
- * ```
1816
- */
1817
1441
  static forRootAsync(asyncOptions) {
1818
1442
  return composeForRootAsync(
1819
1443
  exports.BymaxRealtimeModule,
@@ -1835,56 +1459,35 @@ function connectionReason(err) {
1835
1459
  return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
1836
1460
  }
1837
1461
  var RedisRealtimePubSub = class _RedisRealtimePubSub {
1838
- /**
1839
- * The publishing Redis client.
1840
- *
1841
- * An ECMAScript private field for the same reason as the subscriber below: an
1842
- * ioredis instance carries `options.password` as a plain field, and a
1843
- * TypeScript `private` one is erased at runtime, leaving it enumerable to
1844
- * anything that serializes this pubsub adapter.
1845
- */
1846
1462
  #pub;
1847
1463
  channel;
1848
- /** The lazily created subscriber connection, which carries the same credentials. */
1849
1464
  #subInit = null;
1850
1465
  handlers = /* @__PURE__ */ new Set();
1851
1466
  logger = new common.Logger(_RedisRealtimePubSub.name);
1852
- /** Payloads dropped as unparsable since the last report, and when that report was made. */
1853
1467
  malformedDropped = 0;
1854
1468
  malformedReportedAt = 0;
1855
- /** Whether the subscriber connection holds a confirmed SUBSCRIBE right now. */
1856
1469
  #subscribed = false;
1857
- /** Whether the current outage has been logged, so a retry loop adds no line. */
1858
- // Stryker disable next-line BooleanLiteral: equivalent — createSubscriber sets it before any use
1859
1470
  #outageLogged = false;
1860
- /** Connections closed on purpose, whose `close` is not an outage and says nothing of a successor. */
1861
1471
  #retired = /* @__PURE__ */ new WeakSet();
1862
1472
  constructor(options) {
1863
1473
  this.#pub = options.client;
1864
1474
  this.channel = options.channel ?? "bymax:realtime";
1865
1475
  }
1866
- /**
1867
- * Whether this instance holds a confirmed subscription to the channel, so the events and
1868
- * revocations other instances publish reach it. False before the first successful subscribe,
1869
- * while the subscriber connection is down, and after the last handler has unsubscribed.
1870
- */
1871
1476
  isSubscribed() {
1872
1477
  return this.#subscribed;
1873
1478
  }
1874
- /** JSON-encodes the message and PUBLISHes it to the configured channel. */
1875
1479
  async publish(message) {
1480
+ const status = this.#pub.status;
1481
+ if (status === "reconnecting" || status === "close" || status === "end") {
1482
+ throw unavailableError(
1483
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1484
+ _RedisRealtimePubSub.name,
1485
+ `cannot publish to "${this.channel}"`,
1486
+ new Error(`the Redis client is ${status}`)
1487
+ );
1488
+ }
1876
1489
  await this.#pub.publish(this.channel, JSON.stringify(message));
1877
1490
  }
1878
- /**
1879
- * Lazily creates the single shared subscribe client on first call; returns an async
1880
- * unsubscribe that quits the client when the last handler is removed. Concurrent
1881
- * subscribe calls are idempotent — only one client is ever created. Malformed
1882
- * payloads are dropped, and reported at most once a minute with their count.
1883
- *
1884
- * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
1885
- * the handler registration is rolled back and the cached init promise is cleared so
1886
- * the next call retries from scratch.
1887
- */
1888
1491
  async subscribe(handler) {
1889
1492
  this.handlers.add(handler);
1890
1493
  let sub;
@@ -1910,14 +1513,13 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1910
1513
  }
1911
1514
  };
1912
1515
  }
1913
- /** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
1914
1516
  ensureSubscriber() {
1915
1517
  if (!this.#subInit) this.#subInit = this.createSubscriber();
1916
1518
  return this.#subInit;
1917
1519
  }
1918
1520
  async createSubscriber() {
1919
1521
  this.#outageLogged = false;
1920
- const sub = this.#pub.duplicate({ autoResubscribe: false });
1522
+ const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
1921
1523
  let attached = false;
1922
1524
  sub.on("message", (_ch, payload) => this.dispatch(payload));
1923
1525
  const unreachableFirst = new Promise((resolve) => {
@@ -1932,10 +1534,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1932
1534
  sub.on("ready", () => {
1933
1535
  if (attached) this.confirm(sub);
1934
1536
  });
1935
- const first = sub.subscribe(this.channel);
1537
+ await this.negotiate(sub, sub.subscribe(this.channel), unreachableFirst);
1538
+ attached = true;
1539
+ return sub;
1540
+ }
1541
+ async negotiate(sub, first, unreachableFirst) {
1936
1542
  try {
1937
1543
  const outcome = await Promise.race([
1938
- first.then(() => "subscribed"),
1544
+ first.then(
1545
+ () => "subscribed",
1546
+ (err) => {
1547
+ if (err.name === "ReplyError") throw err;
1548
+ return { unreachable: err };
1549
+ }
1550
+ ),
1939
1551
  unreachableFirst
1940
1552
  ]);
1941
1553
  if (outcome === "subscribed") {
@@ -1954,8 +1566,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1954
1566
  err
1955
1567
  );
1956
1568
  }
1957
- attached = true;
1958
- return sub;
1959
1569
  }
1960
1570
  confirm(sub) {
1961
1571
  sub.subscribe(this.channel).then(
@@ -1963,7 +1573,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1963
1573
  (err) => this.refused(err)
1964
1574
  );
1965
1575
  }
1966
- /** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
1967
1576
  refused(err) {
1968
1577
  if (err?.name !== "ReplyError") return;
1969
1578
  this.#subscribed = false;
@@ -1987,10 +1596,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1987
1596
  `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: not subscribed to "${this.channel}": ${reason}. Remote events and revocations will not reach this instance until it subscribes again`
1988
1597
  );
1989
1598
  }
1990
- /**
1991
- * Count a payload dropped as unparsable and report the count at most once per minute, so a
1992
- * producer on an incompatible version is visible without flooding the log.
1993
- */
1994
1599
  reportMalformed() {
1995
1600
  this.malformedDropped++;
1996
1601
  const now = Date.now();
@@ -2020,21 +1625,10 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2020
1625
 
2021
1626
  // src/server/offline-queue/redis-offline-queue.ts
2022
1627
  var RedisOfflineQueue = class _RedisOfflineQueue {
2023
- /**
2024
- * The Redis client.
2025
- *
2026
- * An ECMAScript private field rather than a TypeScript `private` one, which
2027
- * is erased at runtime: an ioredis instance carries `options.password` as a
2028
- * plain field, so leaving this enumerable would let anything that serializes
2029
- * this queue — or the module options that reference it — reach the Redis
2030
- * credentials.
2031
- */
2032
1628
  #client;
2033
1629
  maxPerUser;
2034
1630
  ttlSeconds;
2035
- /** Zero-pad width for the epoch-millisecond component of the sort key. */
2036
1631
  static MS_PAD = 16;
2037
- /** Zero-pad width for the intra-millisecond counter component of the sort key. */
2038
1632
  static COUNTER_PAD = 6;
2039
1633
  constructor(options) {
2040
1634
  this.#client = options.client;
@@ -2044,23 +1638,12 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2044
1638
  key(userId) {
2045
1639
  return `bymax:oq:${userId}`;
2046
1640
  }
2047
- /**
2048
- * Build the fixed-width lexicographic sort key for an event id.
2049
- *
2050
- * Handles two id formats:
2051
- * - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
2052
- * - Legacy plain numeric strings: `1700000000000`
2053
- */
2054
1641
  lexKey(id) {
2055
1642
  const dashIdx = id.indexOf("-");
2056
1643
  const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
2057
1644
  const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
2058
1645
  return String(ms).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(counter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
2059
1646
  }
2060
- /**
2061
- * Return the lexicographically next sort key after `id`, used as an
2062
- * inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
2063
- */
2064
1647
  lexKeyNext(id) {
2065
1648
  const dashIdx = id.indexOf("-");
2066
1649
  const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
@@ -2070,7 +1653,6 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2070
1653
  const nextCounter = counter < counterMax ? counter + 1 : 0;
2071
1654
  return String(nextMs).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(nextCounter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
2072
1655
  }
2073
- /** Encode an event into a lexicographically sortable ZSET member string. */
2074
1656
  encodeMember(event) {
2075
1657
  return `${this.lexKey(event.id)}|${JSON.stringify(event)}`;
2076
1658
  }