@bymax-one/nest-realtime 1.2.19 → 1.2.21

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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,40 @@ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.21] - 2026-11-20
11
+
12
+ ### Fixed
13
+
14
+ - **A proxy whose trap throws on `then`, or one that was revoked, returned by a factory is refused with the typed error.** `await` reads `then` on what a synchronous `useFactory` or `createRealtimeOptions` returns, which ran the trap inside the library before the options were read; a revoked proxy given to `forRoot` or returned by a factory raised the engine's `TypeError`. Both now raise `REALTIME_INVALID_OPTIONS` with the error as the `cause`.
15
+ - **`REALTIME_REDIS_ADAPTER_FAILED` no longer carries the text of the error underneath in its message.** The message names what could not be installed and the remedy; the error that was thrown is the `cause`.
16
+ - **A field named `event`, `message` or `err` cannot replace the event, the message or the error of a log line.** The library's own values are written after the fields.
17
+ - **A logger that throws no longer turns a reported failure into another one.** `logEvent` writes every `warn` and `error` line the library emits, often from a `catch` block or a promise handler; when the host's logger threw there, the error left the handler, and in the timer of the re-authentication service it was an unhandled rejection, which ends a Node process by default. The throw is now absorbed and the line is lost.
18
+
19
+ #### Apply to a derived backend
20
+
21
+ Code that read the reason from the message of a `REALTIME_REDIS_ADAPTER_FAILED` error reads `error.cause` instead.
22
+
23
+ ### Documentation
24
+
25
+ - **The README says what a logger that rejects does and what a proxy that throws on its type keeps.** A logger whose method returns a rejected promise is not absorbed, because Nest's `Logger` discards the return value, so the rejection is an unhandled rejection of the host's process, which ends a Node process with exit code 1 unless the application handles `unhandledRejection`. A proxy that throws on every read, its type tag included, is refused as a built-in object without its error as the `cause`.
26
+ - **The README says that an `async` factory's object is read as the factory's own failure, and how a library refusal is recognised.** A factory written as an `async` function that returns a proxy whose trap throws rejects its own promise with that error, which the library cannot tell from the factory failing. A refusal the library raised is recognised by its stable code, so an error of the host's own that carries a `REALTIME_` code is not wrapped.
27
+
28
+ ## [1.2.20] - 2026-11-20
29
+
30
+ ### Fixed
31
+
32
+ - **A getter or a proxy that throws, in an object the host hands over, is refused with the library's typed error.** A proxy or a getter returned as the options by a `useFactory` or by `createRealtimeOptions`, one on the provider `useExisting` names, and one as the `authenticator` raised the host's own error at registration; they now raise `REALTIME_INVALID_OPTIONS` with the error that was thrown as the `cause`. An `extraProviders` that is not an array of providers raised a raw `TypeError` or was accepted until the container reached it; it is now refused at registration, naming the entry.
33
+ - **An `onConnect` that fails under `onConnectFailure: 'close'` is no longer counted as a refused handshake on WebSocket.** The connection was admitted first, as on SSE, where nothing was counted; `bymax_realtime_connections_refused_total{reason="error"}` now means a handshake that failed with an unexpected error on both transports.
34
+ - **A `*_UNAVAILABLE` error no longer carries the text of the error underneath in its message.** The message names what could not be reached; the error that was thrown is the `cause`, as it already was. The `Subscribed to` line of `RedisRealtimePubSub` no longer names the channel.
35
+
36
+ #### Apply to a derived backend
37
+
38
+ Code that read the text of the underlying failure from the `message` of a `REALTIME_PUBSUB_UNAVAILABLE` or `REALTIME_TRANSPORT_UNAVAILABLE` error must read `error.cause` instead. A dashboard that summed `reason="error"` and counted WebSocket connections that `onConnect` closed will see those no longer counted. A log filter that matched `Subscribed to "<channel>"` matches `Subscribed to the realtime channel`.
39
+
40
+ ### Documentation
41
+
42
+ - **The README names `createRealtimeOptions` and `ConnectionAuthContext.userAgent`.**
43
+
10
44
  ## [1.2.19] - 2026-11-20
11
45
 
12
46
  ### Added
@@ -1203,7 +1237,9 @@ First published release.
1203
1237
  rather than by the manual sweep that raised the NestJS floors — that sweep
1204
1238
  asked about NestJS and never put the same question to the other ten peers.
1205
1239
 
1206
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.19...HEAD
1240
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.21...HEAD
1241
+ [1.2.21]: https://github.com/bymaxone/nest-realtime/compare/v1.2.20...v1.2.21
1242
+ [1.2.20]: https://github.com/bymaxone/nest-realtime/compare/v1.2.19...v1.2.20
1207
1243
  [1.2.19]: https://github.com/bymaxone/nest-realtime/compare/v1.2.18...v1.2.19
1208
1244
  [1.2.18]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...v1.2.18
1209
1245
  [1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
package/README.md CHANGED
@@ -412,7 +412,7 @@ An option that holds `undefined` or `null` is read as unset: it takes its defaul
412
412
 
413
413
  The shape of what you pass is checked at start-up too, and refused with `REALTIME_INVALID_OPTIONS`: `sse`, `websocket`, `reauthenticationPolicy` and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must have every function of their interface (`IRealtimePubSub`, `IOfflineQueueStorage`, `IPresenceStorage`), on the object or its prototype; each hook that is set and `tenantResolver` must be a function; `sse.emitConnectionEvent` and `websocket.emitConnectionEvent` must be booleans; `sse.endpoint` must be a non-blank string, with or without a leading slash. An endpoint holds no whitespace, because no request can reach it, and the `sseEndpoint` of `forRootAsync` gets the same check. The options argument must be an object, and so must what a `forRootAsync` factory returns; an array, a `Date` or a `Map` is refused there and where a group is expected, while an instance of your own class is read by its keys. `new RedisOfflineQueue(options)` refuses options that are not an object and a `client` that is not one.
414
414
 
415
- The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`.
415
+ The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`. A `useClass` or `useExisting` provider implements `createRealtimeOptions()`, which returns the options or a promise of them; a provider that does not is refused with `REALTIME_INVALID_OPTIONS`, as is an `extraProviders` that is not an array of providers (a class, or an object with `provide`). An options object, a group, a pluggable piece or a provider whose read throws, such as a getter or a proxy, is refused the same way, with the error it threw as the `cause`. The exception is an object that throws when its type is read, such as a proxy whose every read throws: it is refused as a built-in object and its error is not kept. A factory that returns the object itself is covered, including a proxy that throws on `then` or was revoked; one written as an `async` function rejects its own promise with the object's error, which reaches the application as that factory's failure. A refusal is recognised by its stable code, so an error of your own that carries a `REALTIME_` code is not wrapped.
416
416
 
417
417
  > [!IMPORTANT]
418
418
  > **`forRootAsync` takes the SSE route on the registration, not from the factory.** NestJS
@@ -500,7 +500,7 @@ export class ObservabilityModule {}
500
500
  | Metric | Type | Labels | Meaning |
501
501
  | ------------------------------------------ | ------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
502
502
  | `bymax_realtime_connections` | gauge | `transport` = `sse`, `websocket` | Connections open on this instance now. |
503
- | `bymax_realtime_connections_refused_total` | counter | `reason` = `limit`, `unauthorized`, `unavailable`, `error` | Handshakes refused since start; `error` is one that failed with an unexpected error (a 500). |
503
+ | `bymax_realtime_connections_refused_total` | counter | `reason` = `limit`, `unauthorized`, `unavailable`, `error` | Handshakes refused since start; `error` is one that failed with an unexpected error (a 500); a connection that `onConnectFailure: 'close'` closes was admitted first, and is not counted. |
504
504
  | `bymax_realtime_evictions_total` | counter | `reason` = `per_user_cap`, `slow_consumer`, `revoked` | Connections closed by the library or by a revocation. |
505
505
  | `bymax_realtime_events_emitted_total` | counter | `transport` = `sse`, `websocket` | Emit calls handled on this instance, not deliveries: a call with no recipient counts, and under `'both'` each transport counts it. |
506
506
  | `bymax_realtime_slow_consumer_drops_total` | counter | none | Connections cut for not reading what they were sent. |
@@ -511,7 +511,7 @@ A label is one of the values listed and never an id, a tenant or a user. A revoc
511
511
 
512
512
  **Traces.** With `@opentelemetry/api` installed the library starts `realtime.handshake` around the admission and authentication of each connection (attribute `bymax.realtime.transport`, `sse` or `websocket`) and `realtime.reauthenticate` around each re-authentication cycle. A refused handshake ends its span with status ERROR and the library error code, never the message. With no SDK registered the API is a no-op, and without the package nothing is started.
513
513
 
514
- **Log events.** Every `warn` and `error` line the library writes is an object, `{ event, message, ...fields }`, with the error that caused a failure, when there is one, under `err` as the error itself and never as text in `message`; so a structured logger writes each as a JSON field and Nest's default logger prints the object. The fields are counts, sizes, configured limits, transport names and a library-made connection id; a user id, a tenant id or a room is never in a message or a field, because the logger's own context carries identity. Lines that report that the library started stay plain strings.
514
+ **Log events.** Every `warn` and `error` line the library writes is an object, `{ event, message, ...fields }`, with the error that caused a failure, when there is one, under `err` as the error itself and never as text in `message`; so a structured logger writes each as a JSON field and Nest's default logger prints the object. The fields are counts, sizes, configured limits, transport names and a library-made connection id; a user id, a tenant id or a room is never in a message or a field, because the logger's own context carries identity. Lines that report that the library started stay plain strings. A logger that throws while the library writes an event is absorbed: the line is lost and the call that was logging goes on. A logger whose method returns a rejected promise is not, because Nest's `Logger` discards what the method returns, so the rejection is an unhandled rejection of your process, which ends a Node process with exit code 1 unless the application handles `unhandledRejection`; such a logger has to catch its own failures.
515
515
 
516
516
  | Event | Level | When | Fields |
517
517
  | -------------------------------------- | ----------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
@@ -857,6 +857,9 @@ proxy it is the proxy's address. Use it to decide whether a forwarded header suc
857
857
  `undefined` when the socket reports no address, and an IPv4 peer can arrive in its IPv4-mapped form
858
858
  (`::ffff:10.0.0.1`), which is passed through as reported.
859
859
 
860
+ `userAgent` is the raw `User-Agent` header, or `undefined` when the client sent none. Any client can
861
+ set it to anything, so it suits a log line and not a decision about who may connect.
862
+
860
863
  ### Rooms
861
864
 
862
865
  | Room ID | Used for | Auto-joined |
@@ -143,6 +143,34 @@ function applyDefaults(raw) {
143
143
  });
144
144
  }
145
145
 
146
+ // src/server/utils/realtime-error.ts
147
+ function realtimeError(code, detail, options = {}) {
148
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
149
+ const message = `${lead}: ${detail}`;
150
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
151
+ return Object.assign(error, { code });
152
+ }
153
+
154
+ // src/server/config/guard-host-reads.ts
155
+ var LIBRARY_CODES = new Set(Object.values(REALTIME_ERROR_CODES));
156
+ var isLibraryError = (error) => error instanceof Error && LIBRARY_CODES.has(error.code);
157
+ function guardHostReads(what, read) {
158
+ try {
159
+ return read();
160
+ } catch (error) {
161
+ if (isLibraryError(error)) throw error;
162
+ throw realtimeError(
163
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
164
+ `${what} could not be read: a getter or a proxy on it throws`,
165
+ { who: "BymaxRealtimeModule", cause: error }
166
+ );
167
+ }
168
+ }
169
+ async function awaitHostResult(returned, what = "the options") {
170
+ guardHostReads(what, () => returned?.then);
171
+ return returned;
172
+ }
173
+
146
174
  // src/server/constants/injection-tokens.constants.ts
147
175
  var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
148
176
  var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
@@ -166,24 +194,23 @@ var KIND_OF_TYPE = {
166
194
  function: "a function",
167
195
  undefined: "undefined"
168
196
  };
197
+ function isArray(value) {
198
+ try {
199
+ return Array.isArray(value);
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
169
204
  function describeReceived(value) {
170
205
  if (typeof value === "number") {
171
206
  return Number.isFinite(value) ? String(value) : "a number that is not finite";
172
207
  }
173
208
  if (value === null) return "null";
174
- if (Array.isArray(value)) return "an array";
209
+ if (isArray(value)) return "an array";
175
210
  if (typeof value === "object" && !isPlainObject(value)) return "a built-in object";
176
211
  return KIND_OF_TYPE[typeof value] ?? "an object";
177
212
  }
178
213
 
179
- // src/server/utils/realtime-error.ts
180
- function realtimeError(code, detail, options = {}) {
181
- const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
182
- const message = `${lead}: ${detail}`;
183
- const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
184
- return Object.assign(error, { code });
185
- }
186
-
187
214
  // src/server/utils/refuse-object.ts
188
215
  function refuseObject(who, path, value) {
189
216
  throw realtimeError(
@@ -261,10 +288,34 @@ function validateShapes(options) {
261
288
  assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
262
289
  assertSseEndpoint("sse.endpoint", options.sse?.endpoint);
263
290
  }
291
+ function assertExtraProviders(value) {
292
+ if (value === void 0 || value === null) return;
293
+ if (!Array.isArray(value)) {
294
+ throw realtimeError(
295
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
296
+ `extraProviders must be an array of providers, received ${describeReceived(value)}`,
297
+ { who: "BymaxRealtimeModule" }
298
+ );
299
+ }
300
+ value.forEach((entry, index) => {
301
+ const isClass = typeof entry === "function";
302
+ const hasProvide = isPlainObject(entry) && "provide" in entry;
303
+ if (isClass || hasProvide) return;
304
+ const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
305
+ throw realtimeError(
306
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
307
+ `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
308
+ { who: "BymaxRealtimeModule" }
309
+ );
310
+ });
311
+ }
264
312
 
265
313
  // src/server/config/validate-options.ts
266
314
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
267
315
  function validateOptions(raw) {
316
+ guardHostReads("the options", () => validateReadOptions(raw));
317
+ }
318
+ function validateReadOptions(raw) {
268
319
  assertOptionsObject(raw);
269
320
  const options = dropUnset(raw);
270
321
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
@@ -517,7 +568,10 @@ var REALTIME_LOG_EVENTS = [
517
568
  "REALTIME_SERVER_NOT_ATTACHED"
518
569
  ];
519
570
  function logEvent(logger, level, event, message, fields = {}, error) {
520
- logger[level]({ event, message, ...fields, ...error === void 0 ? {} : { err: error } });
571
+ try {
572
+ logger[level]({ ...fields, event, message, ...error === void 0 ? {} : { err: error } });
573
+ } catch {
574
+ }
521
575
  }
522
576
 
523
577
  // src/server/utils/describe-error.ts
@@ -1175,7 +1229,7 @@ function composeRoomId(prefix, ...parts) {
1175
1229
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
1176
1230
  }
1177
1231
  function unavailableError(code, who, what, cause) {
1178
- const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
1232
+ const { message } = realtimeError(code, what, { who });
1179
1233
  const error = Object.assign(new common.ServiceUnavailableException(), { code });
1180
1234
  Object.defineProperties(error, {
1181
1235
  message: { value: message, enumerable: false, writable: true, configurable: true },
@@ -2555,7 +2609,7 @@ function buildCommonProviders(resolved, instanceId) {
2555
2609
  }
2556
2610
  function composeForRoot(moduleClass, wiring, logger, raw) {
2557
2611
  assertOptionsObject(raw, moduleClass.name);
2558
- const options = dropUnset(raw);
2612
+ const options = guardHostReads("the options", () => dropUnset(raw));
2559
2613
  validateOptions(options);
2560
2614
  assertModeSupported(wiring, options.transport, moduleClass.name);
2561
2615
  const resolved = applyDefaults(options);
@@ -2593,7 +2647,7 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2593
2647
  throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
2594
2648
  }
2595
2649
  assertOptionsObject(raw, moduleName);
2596
- const options = dropUnset(raw);
2650
+ const options = guardHostReads("the options", () => dropUnset(raw));
2597
2651
  validateOptions(options);
2598
2652
  if (options.transport !== declaredMode) {
2599
2653
  throw realtimeError(
@@ -2626,21 +2680,25 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2626
2680
  if (isSet(asyncOptions.useFactory)) {
2627
2681
  return {
2628
2682
  provide: REALTIME_OPTIONS_TOKEN,
2629
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2683
+ useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
2630
2684
  inject: [...asyncOptions.inject ?? []]
2631
2685
  };
2632
2686
  }
2633
2687
  return {
2634
2688
  provide: REALTIME_OPTIONS_TOKEN,
2635
2689
  useFactory: async (factory) => {
2636
- if (typeof factory?.createRealtimeOptions !== "function") {
2690
+ const create = guardHostReads(
2691
+ "the provider named by useExisting or useClass",
2692
+ () => factory?.createRealtimeOptions
2693
+ );
2694
+ if (typeof create !== "function") {
2637
2695
  throw realtimeError(
2638
2696
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2639
2697
  "the provider named by useExisting or useClass must implement createRealtimeOptions"
2640
2698
  );
2641
2699
  }
2642
2700
  return resolve(
2643
- await factory.createRealtimeOptions(),
2701
+ await awaitHostResult(create.call(factory)),
2644
2702
  "createRealtimeOptions"
2645
2703
  );
2646
2704
  },
@@ -2684,6 +2742,7 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2684
2742
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
2685
2743
  assertSseEndpoint("sseEndpoint", asyncOptions.sseEndpoint);
2686
2744
  assertSseEndpointApplies(asyncOptions, moduleName);
2745
+ assertExtraProviders(asyncOptions.extraProviders);
2687
2746
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2688
2747
  const instanceId = crypto.randomUUID();
2689
2748
  const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
@@ -2953,7 +3012,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2953
3012
  return unavailableError(
2954
3013
  REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
2955
3014
  _RedisRealtimePubSub.name,
2956
- `cannot publish to "${this.channel}"`,
3015
+ `cannot publish to "${this.channel}" (${reason})`,
2957
3016
  new Error(reason)
2958
3017
  );
2959
3018
  }
@@ -3070,7 +3129,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
3070
3129
  this.#outageLogged = false;
3071
3130
  this.#lastRefusal = void 0;
3072
3131
  this.logger.log(
3073
- `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
3132
+ `Subscribed to the realtime channel; remote events and revocations reach this instance`
3074
3133
  );
3075
3134
  }
3076
3135
  markDown(wording, error) {
@@ -2309,6 +2309,10 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2309
2309
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2310
2310
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
2311
2311
  * carry a user or a tenant, and the library's own line must not.
2312
+ *
2313
+ * A logger that throws while writing is absorbed, since the report of a failure must not become another one. A
2314
+ * logger whose method returns a rejected promise is not: Nest's `Logger` discards what the method returns, so the
2315
+ * rejection is an unhandled rejection of the host's process, and the logger has to catch its own.
2312
2316
  */
2313
2317
  declare function logEvent(logger: Pick<Logger, 'warn' | 'error'>, level: 'warn' | 'error', event: RealtimeLogEvent, message: string, fields?: LogFields, error?: unknown): void;
2314
2318
 
@@ -2374,7 +2378,8 @@ type UnavailableError = ServiceUnavailableException & {
2374
2378
  /**
2375
2379
  * Builds the rejection for a call whose effect did not happen, such as a revocation that never
2376
2380
  * reached its connection. The stable code leads the message, as it does in the other errors this
2377
- * library raises, is also the `code` property, and the original failure travels as `cause`.
2381
+ * library raises, is also the `code` property, and the original failure travels as `cause` alone: its
2382
+ * text, which is a driver's or a host's, is not in the message.
2378
2383
  *
2379
2384
  * It is Nest's `ServiceUnavailableException`, so a consumer's controller that lets it escape
2380
2385
  * answers 503 with the generic body, and the library's own text never reaches a client: the
@@ -2309,6 +2309,10 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2309
2309
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2310
2310
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
2311
2311
  * carry a user or a tenant, and the library's own line must not.
2312
+ *
2313
+ * A logger that throws while writing is absorbed, since the report of a failure must not become another one. A
2314
+ * logger whose method returns a rejected promise is not: Nest's `Logger` discards what the method returns, so the
2315
+ * rejection is an unhandled rejection of the host's process, and the logger has to catch its own.
2312
2316
  */
2313
2317
  declare function logEvent(logger: Pick<Logger, 'warn' | 'error'>, level: 'warn' | 'error', event: RealtimeLogEvent, message: string, fields?: LogFields, error?: unknown): void;
2314
2318
 
@@ -2374,7 +2378,8 @@ type UnavailableError = ServiceUnavailableException & {
2374
2378
  /**
2375
2379
  * Builds the rejection for a call whose effect did not happen, such as a revocation that never
2376
2380
  * reached its connection. The stable code leads the message, as it does in the other errors this
2377
- * library raises, is also the `code` property, and the original failure travels as `cause`.
2381
+ * library raises, is also the `code` property, and the original failure travels as `cause` alone: its
2382
+ * text, which is a driver's or a host's, is not in the message.
2378
2383
  *
2379
2384
  * It is Nest's `ServiceUnavailableException`, so a consumer's controller that lets it escape
2380
2385
  * answers 503 with the generic body, and the library's own text never reaches a client: the
@@ -141,6 +141,34 @@ function applyDefaults(raw) {
141
141
  });
142
142
  }
143
143
 
144
+ // src/server/utils/realtime-error.ts
145
+ function realtimeError(code, detail, options = {}) {
146
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
147
+ const message = `${lead}: ${detail}`;
148
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
149
+ return Object.assign(error, { code });
150
+ }
151
+
152
+ // src/server/config/guard-host-reads.ts
153
+ var LIBRARY_CODES = new Set(Object.values(REALTIME_ERROR_CODES));
154
+ var isLibraryError = (error) => error instanceof Error && LIBRARY_CODES.has(error.code);
155
+ function guardHostReads(what, read) {
156
+ try {
157
+ return read();
158
+ } catch (error) {
159
+ if (isLibraryError(error)) throw error;
160
+ throw realtimeError(
161
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
162
+ `${what} could not be read: a getter or a proxy on it throws`,
163
+ { who: "BymaxRealtimeModule", cause: error }
164
+ );
165
+ }
166
+ }
167
+ async function awaitHostResult(returned, what = "the options") {
168
+ guardHostReads(what, () => returned?.then);
169
+ return returned;
170
+ }
171
+
144
172
  // src/server/constants/injection-tokens.constants.ts
145
173
  var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
146
174
  var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
@@ -164,24 +192,23 @@ var KIND_OF_TYPE = {
164
192
  function: "a function",
165
193
  undefined: "undefined"
166
194
  };
195
+ function isArray(value) {
196
+ try {
197
+ return Array.isArray(value);
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
167
202
  function describeReceived(value) {
168
203
  if (typeof value === "number") {
169
204
  return Number.isFinite(value) ? String(value) : "a number that is not finite";
170
205
  }
171
206
  if (value === null) return "null";
172
- if (Array.isArray(value)) return "an array";
207
+ if (isArray(value)) return "an array";
173
208
  if (typeof value === "object" && !isPlainObject(value)) return "a built-in object";
174
209
  return KIND_OF_TYPE[typeof value] ?? "an object";
175
210
  }
176
211
 
177
- // src/server/utils/realtime-error.ts
178
- function realtimeError(code, detail, options = {}) {
179
- const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
180
- const message = `${lead}: ${detail}`;
181
- const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
182
- return Object.assign(error, { code });
183
- }
184
-
185
212
  // src/server/utils/refuse-object.ts
186
213
  function refuseObject(who, path, value) {
187
214
  throw realtimeError(
@@ -259,10 +286,34 @@ function validateShapes(options) {
259
286
  assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
260
287
  assertSseEndpoint("sse.endpoint", options.sse?.endpoint);
261
288
  }
289
+ function assertExtraProviders(value) {
290
+ if (value === void 0 || value === null) return;
291
+ if (!Array.isArray(value)) {
292
+ throw realtimeError(
293
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
294
+ `extraProviders must be an array of providers, received ${describeReceived(value)}`,
295
+ { who: "BymaxRealtimeModule" }
296
+ );
297
+ }
298
+ value.forEach((entry, index) => {
299
+ const isClass = typeof entry === "function";
300
+ const hasProvide = isPlainObject(entry) && "provide" in entry;
301
+ if (isClass || hasProvide) return;
302
+ const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
303
+ throw realtimeError(
304
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
305
+ `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
306
+ { who: "BymaxRealtimeModule" }
307
+ );
308
+ });
309
+ }
262
310
 
263
311
  // src/server/config/validate-options.ts
264
312
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
265
313
  function validateOptions(raw) {
314
+ guardHostReads("the options", () => validateReadOptions(raw));
315
+ }
316
+ function validateReadOptions(raw) {
266
317
  assertOptionsObject(raw);
267
318
  const options = dropUnset(raw);
268
319
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
@@ -515,7 +566,10 @@ var REALTIME_LOG_EVENTS = [
515
566
  "REALTIME_SERVER_NOT_ATTACHED"
516
567
  ];
517
568
  function logEvent(logger, level, event, message, fields = {}, error) {
518
- logger[level]({ event, message, ...fields, ...error === void 0 ? {} : { err: error } });
569
+ try {
570
+ logger[level]({ ...fields, event, message, ...error === void 0 ? {} : { err: error } });
571
+ } catch {
572
+ }
519
573
  }
520
574
 
521
575
  // src/server/utils/describe-error.ts
@@ -1173,7 +1227,7 @@ function composeRoomId(prefix, ...parts) {
1173
1227
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
1174
1228
  }
1175
1229
  function unavailableError(code, who, what, cause) {
1176
- const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
1230
+ const { message } = realtimeError(code, what, { who });
1177
1231
  const error = Object.assign(new ServiceUnavailableException(), { code });
1178
1232
  Object.defineProperties(error, {
1179
1233
  message: { value: message, enumerable: false, writable: true, configurable: true },
@@ -2553,7 +2607,7 @@ function buildCommonProviders(resolved, instanceId) {
2553
2607
  }
2554
2608
  function composeForRoot(moduleClass, wiring, logger, raw) {
2555
2609
  assertOptionsObject(raw, moduleClass.name);
2556
- const options = dropUnset(raw);
2610
+ const options = guardHostReads("the options", () => dropUnset(raw));
2557
2611
  validateOptions(options);
2558
2612
  assertModeSupported(wiring, options.transport, moduleClass.name);
2559
2613
  const resolved = applyDefaults(options);
@@ -2591,7 +2645,7 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2591
2645
  throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
2592
2646
  }
2593
2647
  assertOptionsObject(raw, moduleName);
2594
- const options = dropUnset(raw);
2648
+ const options = guardHostReads("the options", () => dropUnset(raw));
2595
2649
  validateOptions(options);
2596
2650
  if (options.transport !== declaredMode) {
2597
2651
  throw realtimeError(
@@ -2624,21 +2678,25 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2624
2678
  if (isSet(asyncOptions.useFactory)) {
2625
2679
  return {
2626
2680
  provide: REALTIME_OPTIONS_TOKEN,
2627
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2681
+ useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
2628
2682
  inject: [...asyncOptions.inject ?? []]
2629
2683
  };
2630
2684
  }
2631
2685
  return {
2632
2686
  provide: REALTIME_OPTIONS_TOKEN,
2633
2687
  useFactory: async (factory) => {
2634
- if (typeof factory?.createRealtimeOptions !== "function") {
2688
+ const create = guardHostReads(
2689
+ "the provider named by useExisting or useClass",
2690
+ () => factory?.createRealtimeOptions
2691
+ );
2692
+ if (typeof create !== "function") {
2635
2693
  throw realtimeError(
2636
2694
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2637
2695
  "the provider named by useExisting or useClass must implement createRealtimeOptions"
2638
2696
  );
2639
2697
  }
2640
2698
  return resolve(
2641
- await factory.createRealtimeOptions(),
2699
+ await awaitHostResult(create.call(factory)),
2642
2700
  "createRealtimeOptions"
2643
2701
  );
2644
2702
  },
@@ -2682,6 +2740,7 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2682
2740
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
2683
2741
  assertSseEndpoint("sseEndpoint", asyncOptions.sseEndpoint);
2684
2742
  assertSseEndpointApplies(asyncOptions, moduleName);
2743
+ assertExtraProviders(asyncOptions.extraProviders);
2685
2744
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2686
2745
  const instanceId = randomUUID();
2687
2746
  const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
@@ -2951,7 +3010,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2951
3010
  return unavailableError(
2952
3011
  REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
2953
3012
  _RedisRealtimePubSub.name,
2954
- `cannot publish to "${this.channel}"`,
3013
+ `cannot publish to "${this.channel}" (${reason})`,
2955
3014
  new Error(reason)
2956
3015
  );
2957
3016
  }
@@ -3068,7 +3127,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
3068
3127
  this.#outageLogged = false;
3069
3128
  this.#lastRefusal = void 0;
3070
3129
  this.logger.log(
3071
- `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
3130
+ `Subscribed to the realtime channel; remote events and revocations reach this instance`
3072
3131
  );
3073
3132
  }
3074
3133
  markDown(wording, error) {
@@ -31,6 +31,16 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
31
31
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
32
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
33
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
34
+
35
+ // src/websocket/transports/websocket/connect-hook-failure.ts
36
+ var ConnectHookFailure = class extends Error {
37
+ constructor(cause) {
38
+ super("onConnect hook failed", { cause });
39
+ this.name = "ConnectHookFailure";
40
+ }
41
+ };
42
+
43
+ // src/websocket/transports/websocket/websocket.transport.ts
34
44
  var CONNECTION_ROOM_PREFIX = "connection";
35
45
  var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
36
46
  var _shuttingDown;
@@ -116,7 +126,7 @@ exports.WebSocketTransport = class WebSocketTransport {
116
126
  const failed = await this.runOnConnect(socket, auth, connectedAt);
117
127
  if (!failed) return;
118
128
  if (this.options.onConnectFailure === "close") {
119
- throw new Error("onConnect hook failed", { cause: failed.error });
129
+ throw new ConnectHookFailure(failed.error);
120
130
  }
121
131
  internal.logEvent(
122
132
  this.logger,
@@ -225,7 +235,7 @@ exports.WebSocketTransport = class WebSocketTransport {
225
235
  throw internal.unavailableError(
226
236
  internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
227
237
  exports.WebSocketTransport.name,
228
- `the WebSocket server is not attached, so ${connectionId} cannot be revoked`,
238
+ `the WebSocket server is not attached, so ${connectionId} cannot be revoked (server not attached)`,
229
239
  new Error("server not attached")
230
240
  );
231
241
  }
@@ -457,10 +467,9 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
457
467
  } catch {
458
468
  }
459
469
  }
460
- const reason = internal.describeError(err);
461
470
  throw internal.realtimeError(
462
471
  internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
463
- `websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
472
+ "websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed. Install @socket.io/redis-adapter and pass an ioredis client as pubClient.",
464
473
  { who: _RealtimeIoAdapter.name, cause: err }
465
474
  );
466
475
  }
@@ -622,7 +631,7 @@ exports.RealtimeGateway = class RealtimeGateway {
622
631
  } else if (err instanceof internal.AuthenticationUnavailableError) {
623
632
  this.tally?.refused("unavailable");
624
633
  } else {
625
- this.tally?.refused("error");
634
+ if (!(err instanceof ConnectHookFailure)) this.tally?.refused("error");
626
635
  internal.logEvent(
627
636
  this.logger,
628
637
  "error",
@@ -31,6 +31,16 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
31
31
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
32
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
33
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
34
+
35
+ // src/websocket/transports/websocket/connect-hook-failure.ts
36
+ var ConnectHookFailure = class extends Error {
37
+ constructor(cause) {
38
+ super("onConnect hook failed", { cause });
39
+ this.name = "ConnectHookFailure";
40
+ }
41
+ };
42
+
43
+ // src/websocket/transports/websocket/websocket.transport.ts
34
44
  var CONNECTION_ROOM_PREFIX = "connection";
35
45
  var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
36
46
  var _shuttingDown;
@@ -116,7 +126,7 @@ var WebSocketTransport = class {
116
126
  const failed = await this.runOnConnect(socket, auth, connectedAt);
117
127
  if (!failed) return;
118
128
  if (this.options.onConnectFailure === "close") {
119
- throw new Error("onConnect hook failed", { cause: failed.error });
129
+ throw new ConnectHookFailure(failed.error);
120
130
  }
121
131
  logEvent(
122
132
  this.logger,
@@ -225,7 +235,7 @@ var WebSocketTransport = class {
225
235
  throw unavailableError(
226
236
  REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
227
237
  WebSocketTransport.name,
228
- `the WebSocket server is not attached, so ${connectionId} cannot be revoked`,
238
+ `the WebSocket server is not attached, so ${connectionId} cannot be revoked (server not attached)`,
229
239
  new Error("server not attached")
230
240
  );
231
241
  }
@@ -457,10 +467,9 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
457
467
  } catch {
458
468
  }
459
469
  }
460
- const reason = describeError(err);
461
470
  throw realtimeError(
462
471
  REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
463
- `websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
472
+ "websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed. Install @socket.io/redis-adapter and pass an ioredis client as pubClient.",
464
473
  { who: _RealtimeIoAdapter.name, cause: err }
465
474
  );
466
475
  }
@@ -622,7 +631,7 @@ var RealtimeGateway = class {
622
631
  } else if (err instanceof AuthenticationUnavailableError) {
623
632
  this.tally?.refused("unavailable");
624
633
  } else {
625
- this.tally?.refused("error");
634
+ if (!(err instanceof ConnectHookFailure)) this.tally?.refused("error");
626
635
  logEvent(
627
636
  this.logger,
628
637
  "error",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.19",
3
+ "version": "1.2.21",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",