@dammers/use-signalr-core 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,53 @@
1
1
  import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
2
- import { isRetriableConnectError } from "./config.js";
3
- const CONNECT_RETRY_BASE_MS = 2500;
2
+ import { assertProtocolFitsTransport, isRetriableConnectError, joinHubUrl } from "./config.js";
3
+ const RECOVER_DELAY_STEP_MS = 2500;
4
+ const RECOVER_DELAY_MAX_MS = 30000;
4
5
  function noop() { }
5
- /**
6
- * Owns the HubConnection lifecycle for one provider generation: building,
7
- * starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
8
- * Framework-neutral — driven by the adapter's lifecycle hook and context callbacks.
9
- */
6
+ /** SignalR passes no error on a clean close, and after it gave up its auto-reconnect. */
7
+ function cleanCloseError(afterReconnectAttempts) {
8
+ return new Error(afterReconnectAttempts
9
+ ? "Reconnect retries exhausted"
10
+ : "The server or a proxy closed the connection.");
11
+ }
12
+ function isThenable(value) {
13
+ return typeof value?.then === "function";
14
+ }
15
+ /** Runs a user callback. A throw or a rejection goes to onError. A failure of onError is dropped. */
16
+ export function runUserCallback(hub, callback, onError) {
17
+ const report = (err) => {
18
+ try {
19
+ const result = onError(hub, err);
20
+ if (isThenable(result))
21
+ result.then(undefined, noop);
22
+ }
23
+ catch {
24
+ // Nothing is left to report to.
25
+ }
26
+ };
27
+ try {
28
+ const result = callback();
29
+ if (isThenable(result))
30
+ result.then(undefined, report);
31
+ }
32
+ catch (err) {
33
+ report(err);
34
+ }
35
+ }
36
+ /** Owns the hub connections of one provider generation: build, start with recovery, lazy ref-counted stop. */
10
37
  export function createConnectionManager(deps) {
11
- const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, onStatus, onError, isCurrent, } = deps;
38
+ const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, connectedBefore, dispatch, onStatus, isCurrent, } = deps;
39
+ const report = (hub, error, source) => runUserCallback(hub, () => deps.onError(hub, error, { source }), noop);
40
+ const onError = (hub, error) => report(hub, error, "connection");
41
+ const onCallbackError = (hub, error) => report(hub, error, "callback");
12
42
  const built = new Map();
13
- const retryTimers = new Set();
43
+ const recoverTimers = new Map();
44
+ const attempts = new Map();
45
+ const misconfigured = new Set();
14
46
  let disposing = false;
15
- const setStatus = (hub, status) => {
16
- const e = built.get(hub);
17
- if (e)
18
- e.status = status;
19
- onStatus(hub, status);
47
+ const setStatus = (hub, status, error) => {
48
+ runUserCallback(hub, () => onStatus(hub, status, error), onCallbackError);
20
49
  };
21
- // stop() stays fire-and-forget so the public API remains synchronous, but a
22
- // rejection must surface instead of becoming an unhandled rejection.
50
+ // Fire-and-forget keeps the API synchronous. A rejection still reaches onError.
23
51
  const stopConnection = (hub, connection) => {
24
52
  void connection.stop().catch((err) => onError(hub, err));
25
53
  };
@@ -30,6 +58,14 @@ export function createConnectionManager(deps) {
30
58
  stopTimers.delete(hub);
31
59
  }
32
60
  };
61
+ const clearRecoverTimer = (hub) => {
62
+ const id = recoverTimers.get(hub);
63
+ if (id !== undefined) {
64
+ clearTimeout(id);
65
+ recoverTimers.delete(hub);
66
+ }
67
+ attempts.delete(hub);
68
+ };
33
69
  const applyReconnect = (builder, reconnect) => {
34
70
  if (reconnect === true)
35
71
  builder.withAutomaticReconnect();
@@ -38,93 +74,132 @@ export function createConnectionManager(deps) {
38
74
  else if (reconnect !== false)
39
75
  builder.withAutomaticReconnect(reconnect);
40
76
  };
77
+ const buildConnection = (hub, rc) => {
78
+ const protocol = typeof rc.hubProtocol === "function" ? rc.hubProtocol() : rc.hubProtocol;
79
+ if (protocol)
80
+ assertProtocolFitsTransport(hub, protocol, rc.httpOptions);
81
+ let builder = new HubConnectionBuilder().withUrl(joinHubUrl(baseUrl, hub), {
82
+ ...rc.httpOptions,
83
+ accessTokenFactory: () => Promise.resolve(getAccessToken()),
84
+ });
85
+ if (protocol)
86
+ builder = builder.withHubProtocol(protocol);
87
+ builder = builder.configureLogging(rc.logLevel);
88
+ applyReconnect(builder, rc.reconnect);
89
+ for (const configure of rc.configureBuilders)
90
+ builder = configure(builder, { hub, baseUrl });
91
+ return builder.build();
92
+ };
93
+ const runReconnectListeners = (hub) => {
94
+ [...(reconnectListeners.get(hub) ?? [])].forEach((cb) => runUserCallback(hub, cb, onCallbackError));
95
+ };
41
96
  const buildAndStart = (hub) => {
42
- if (disposing || built.has(hub))
97
+ if (disposing || built.has(hub) || misconfigured.has(hub))
43
98
  return;
44
99
  clearStopTimer(hub);
45
100
  const rc = resolve(hub);
46
- const builder = new HubConnectionBuilder()
47
- .withUrl(`${baseUrl}${hub}`, {
48
- accessTokenFactory: () => Promise.resolve(getAccessToken()),
49
- transport: rc.transport,
50
- skipNegotiation: rc.skipNegotiation,
51
- })
52
- .configureLogging(rc.logLevel);
53
- applyReconnect(builder, rc.reconnect);
54
- const conn = builder.build();
55
- // Pre-bind declared client events, so a server push never hits zero handlers.
56
- // Tests must count `.on` deltas: this adds one call per declared event.
57
- for (const ev of rc.events)
58
- conn.on(ev, noop);
59
- let resolveReady;
60
- const ready = new Promise((res) => {
61
- resolveReady = res;
62
- });
63
- const entry = {
64
- connection: conn,
65
- status: "connecting",
66
- ready,
67
- resolveReady,
68
- stopping: false,
69
- };
101
+ let conn;
102
+ try {
103
+ conn = buildConnection(hub, rc);
104
+ }
105
+ catch (err) {
106
+ // A build error comes from the app config, so a retry cannot fix it.
107
+ attempts.delete(hub);
108
+ misconfigured.add(hub);
109
+ setStatus(hub, "disconnected", err);
110
+ onError(hub, err);
111
+ return;
112
+ }
113
+ const entry = { connection: conn, stopping: false, reconnecting: false };
70
114
  built.set(hub, entry);
71
- // Attach lifecycle handlers ONCE — SignalR has no removal API.
115
+ // Bind before start() so early pushes arrive.
116
+ for (const ev of rc.events) {
117
+ conn.on(ev, (...args) => {
118
+ if (!isCurrent() || built.get(hub) !== entry)
119
+ return;
120
+ dispatch(hub, ev, args);
121
+ });
122
+ }
123
+ const fail = (err, republishStatus) => {
124
+ if (built.get(hub) !== entry)
125
+ return;
126
+ if (!isRetriableConnectError(err)) {
127
+ attempts.delete(hub);
128
+ setStatus(hub, "disconnected", err);
129
+ onError(hub, err);
130
+ return;
131
+ }
132
+ built.delete(hub);
133
+ if (!desired().has(hub)) {
134
+ attempts.delete(hub);
135
+ connectedBefore.delete(hub);
136
+ setStatus(hub, "idle");
137
+ return;
138
+ }
139
+ const attempt = (attempts.get(hub) ?? 0) + 1;
140
+ attempts.set(hub, attempt);
141
+ if (attempt === 1)
142
+ onError(hub, err);
143
+ if (republishStatus)
144
+ setStatus(hub, "connecting");
145
+ const delay = Math.min(RECOVER_DELAY_STEP_MS * attempt, RECOVER_DELAY_MAX_MS);
146
+ const id = setTimeout(() => {
147
+ recoverTimers.delete(hub);
148
+ if (!isCurrent() || !desired().has(hub))
149
+ return;
150
+ buildAndStart(hub);
151
+ }, delay);
152
+ recoverTimers.set(hub, id);
153
+ };
154
+ // SignalR has no removal API, so attach lifecycle handlers once.
72
155
  conn.onclose((err) => {
73
156
  // A stale generation's late callback must never overwrite the live one's status.
74
- if (!isCurrent())
157
+ if (!isCurrent() || built.get(hub) !== entry)
75
158
  return;
76
- // A deliberate stop() (logout, rebuild, lazy stop) leaves err undefined: stay silent.
77
- if (disposing || err === undefined) {
78
- setStatus(hub, "disconnected");
159
+ if (disposing)
79
160
  return;
80
- }
81
- setStatus(hub, "disconnected");
82
- onError(hub, err);
161
+ fail(err ?? cleanCloseError(entry.reconnecting), true);
83
162
  });
84
163
  conn.onreconnecting(() => {
85
- if (isCurrent())
86
- setStatus(hub, "reconnecting");
164
+ if (!isCurrent() || built.get(hub) !== entry)
165
+ return;
166
+ entry.reconnecting = true;
167
+ setStatus(hub, "reconnecting");
87
168
  });
88
169
  conn.onreconnected(() => {
89
- entry.resolveReady();
90
- if (!isCurrent())
170
+ if (!isCurrent() || built.get(hub) !== entry)
91
171
  return;
92
- if (!disposing) {
93
- onStatus(hub, "reconnected");
94
- reconnectListeners.get(hub)?.forEach((cb) => cb());
95
- }
172
+ entry.reconnecting = false;
96
173
  setStatus(hub, "connected");
174
+ if (disposing)
175
+ return;
176
+ runReconnectListeners(hub);
97
177
  });
98
- let retries = 0;
99
178
  const start = async () => {
100
- if (disposing || entry.stopping)
101
- return;
102
179
  if (conn.state !== HubConnectionState.Disconnected)
103
180
  return;
181
+ if (disposing || entry.stopping)
182
+ return;
104
183
  try {
105
184
  await conn.start();
106
- if (disposing || entry.stopping)
107
- return;
108
- entry.resolveReady();
109
- setStatus(hub, "connected");
110
185
  }
111
186
  catch (err) {
112
- if (disposing || entry.stopping)
187
+ if (disposing || entry.stopping || !isCurrent())
113
188
  return;
114
- if (!isRetriableConnectError(err) || retries >= rc.maxConnectRetries) {
115
- setStatus(hub, "disconnected");
116
- onError(hub, err);
117
- return;
118
- }
119
- retries += 1;
120
- setStatus(hub, "disconnected");
121
- const id = setTimeout(() => {
122
- retryTimers.delete(id);
123
- void start();
124
- }, CONNECT_RETRY_BASE_MS * retries);
125
- retryTimers.add(id);
189
+ fail(err, false);
190
+ return;
126
191
  }
192
+ if (disposing || entry.stopping)
193
+ return;
194
+ attempts.delete(hub);
195
+ const recovered = connectedBefore.has(hub);
196
+ connectedBefore.add(hub);
197
+ setStatus(hub, "connected");
198
+ if (recovered && !disposing)
199
+ runReconnectListeners(hub);
127
200
  };
201
+ if (!attempts.has(hub))
202
+ setStatus(hub, "connecting");
128
203
  void start();
129
204
  };
130
205
  const scheduleStop = (hub) => {
@@ -134,6 +209,8 @@ export function createConnectionManager(deps) {
134
209
  const { graceMs } = resolve(hub);
135
210
  clearStopTimer(hub);
136
211
  const stopNow = () => {
212
+ if (disposing)
213
+ return;
137
214
  stopTimers.delete(hub);
138
215
  if ((refCounts.get(hub) ?? 0) > 0)
139
216
  return; // re-acquired during the grace period
@@ -142,7 +219,9 @@ export function createConnectionManager(deps) {
142
219
  return;
143
220
  e.stopping = true;
144
221
  built.delete(hub);
145
- setStatus(hub, "disconnected");
222
+ attempts.delete(hub);
223
+ connectedBefore.delete(hub);
224
+ setStatus(hub, "idle");
146
225
  stopConnection(hub, e.connection);
147
226
  };
148
227
  if (graceMs <= 0)
@@ -165,46 +244,39 @@ export function createConnectionManager(deps) {
165
244
  if (disposing)
166
245
  return;
167
246
  const want = desired();
168
- for (const hub of want)
169
- if (!built.has(hub))
247
+ for (const hub of want) {
248
+ if (!built.has(hub) && !recoverTimers.has(hub))
170
249
  buildAndStart(hub);
250
+ }
171
251
  for (const hub of built.keys())
172
252
  if (!want.has(hub))
173
253
  scheduleStop(hub);
174
- };
175
- const getConnection = (hub) => built.get(hub)?.connection ?? null;
176
- const waitForConnection = async (hub, timeoutMs) => {
177
- const sync = built.get(hub);
178
- if (sync && sync.connection.state === HubConnectionState.Connected) {
179
- return sync.connection;
254
+ for (const hub of [...misconfigured]) {
255
+ if (want.has(hub))
256
+ continue;
257
+ misconfigured.delete(hub);
258
+ connectedBefore.delete(hub);
259
+ setStatus(hub, "idle");
180
260
  }
181
- const deadline = Date.now() + timeoutMs;
182
- while (Date.now() < deadline) {
183
- const entry = built.get(hub);
184
- if (entry?.connection.state === HubConnectionState.Connected) {
185
- return entry.connection;
186
- }
187
- let timeoutId;
188
- const timeout = new Promise((res) => {
189
- timeoutId = setTimeout(() => res("timeout"), deadline - Date.now());
190
- });
191
- const result = await Promise.race([
192
- entry?.ready.then(() => "ready") ?? timeout,
193
- timeout,
194
- ]).finally(() => clearTimeout(timeoutId));
195
- if (result === "timeout")
196
- break;
261
+ for (const hub of [...recoverTimers.keys()]) {
262
+ if (want.has(hub))
263
+ continue;
264
+ clearRecoverTimer(hub);
265
+ connectedBefore.delete(hub);
266
+ setStatus(hub, "idle");
197
267
  }
198
- throw new Error(`Timeout waiting for SignalR connection to ${hub} (${timeoutMs}ms)`);
199
268
  };
269
+ const getConnection = (hub) => built.get(hub)?.connection ?? null;
200
270
  const dispose = () => {
201
271
  disposing = true;
202
272
  stopTimers.forEach((id) => clearTimeout(id));
203
273
  stopTimers.clear();
204
- retryTimers.forEach((id) => clearTimeout(id));
205
- retryTimers.clear();
274
+ recoverTimers.forEach((id) => clearTimeout(id));
275
+ recoverTimers.clear();
276
+ attempts.clear();
277
+ misconfigured.clear();
206
278
  built.forEach((e, hub) => stopConnection(hub, e.connection));
207
279
  // refCounts are kept across rebuilds on purpose.
208
280
  };
209
- return { reconcile, getConnection, waitForConnection, dispose };
281
+ return { reconcile, getConnection, dispose };
210
282
  }
package/dist/context.d.ts CHANGED
@@ -1,32 +1,48 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- import type { HubConnectionStatus, HubString, SignalRContract } from "./types.js";
3
- export interface SignalRProviderPropsBase<TChildren> {
4
- children: TChildren;
5
- /** Base URL of the SignalR server. Connections rebuild when this changes. */
2
+ import type { HubConnectionStatus, HubString, SignalRContract, SignalRErrorInfo } from "./types.js";
3
+ export interface SignalRProviderPropsBase<THub extends string = HubString> {
4
+ /** Base URL of the SignalR server. The library adds the hub paths from the contract and removes a trailing slash. A new value rebuilds all connections. `undefined` or `""` disables the session. Use `"/"` for the same origin. */
6
5
  baseUrl: string | undefined;
7
- /** Returns the bearer token. Read on every (re)negotiate, so token rotation
8
- * needs no connection rebuild. */
6
+ /** Returns the bearer token. The library calls it on each negotiate and on each auto-reconnect attempt. A token change needs no rebuild. */
9
7
  accessTokenFactory: () => string | Promise<string>;
10
- /** When false, all connections stop and clear. Default true. */
8
+ /**
9
+ * When `false`, all hubs stop and the status is `idle`. An invoke that waits for the connection rejects at once with an error named `SignalRDisabledError`.
10
+ * @default true
11
+ */
11
12
  enabled?: boolean;
12
- /** Optional rebuild trigger. Pass the access token (or any value) to force a
13
- * reconnect when it changes, for example on a re-login. */
13
+ /** A new value rebuilds all connections. Use it to recover from `disconnected`. Pass a user ID or a login counter, not the token. */
14
14
  connectionKey?: string | number;
15
- onStatusChange?: (hub: HubString, status: HubConnectionStatus) => void;
16
- onError?: (hub: HubString, error: unknown) => void;
15
+ /** Runs when the status of a hub changes. */
16
+ onStatusChange?: (hub: THub, status: HubConnectionStatus) => void;
17
+ /** Runs on a connection error and on an error that your callback throws. `info.source` is `"connection"` or `"callback"`. */
18
+ onError?: (hub: THub, error: unknown, info: SignalRErrorInfo) => void;
17
19
  }
18
- export interface SignalRContextValueBase<T extends SignalRContract, TStore> {
20
+ /** The small context the public accessor of each adapter returns. */
21
+ export interface SignalRPublicContext<T extends SignalRContract> {
22
+ /** The live `HubConnection` of the hub, or `null` when none exists. */
19
23
  getConnection: (hub: keyof T & HubString) => HubConnection | null;
20
- /** Point read of the hub's current status. Use `useHubStatus` for a subscribed read. */
21
- isHubConnected: (hub: keyof T & HubString) => boolean;
22
- /** Point read of the hub's current status. Use `useHubStatus` for a subscribed read. */
24
+ /** Point read of the hub's current status. In a reactive scope of a signal-based framework (Solid, Vue, Angular), the read tracks. */
23
25
  getStatus: (hub: keyof T & HubString) => HubConnectionStatus;
24
- waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
25
- /** Status store backing `useHubStatus`. */
26
+ /**
27
+ * Resolves once the hub is connected. Waits across stop, start, and rebuilds.
28
+ * Rejects after `timeoutMs`, or with `signal.reason` (an `AbortError` for a plain `abort()`) when `signal` aborts.
29
+ * Rejects at once when the last update disabled the session, or when the hub stopped after a non-retriable error.
30
+ * On the server no connection starts. The wait rejects at once if the adapter disables the session there, and ends with the timeout otherwise.
31
+ */
32
+ waitForConnection: (hub: keyof T & HubString, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
33
+ }
34
+ /** The full context that adapters use inside their own hooks. Not public API. */
35
+ export interface SignalRContextValueBase<T extends SignalRContract, TStore> extends SignalRPublicContext<T> {
36
+ /** The frozen object that the public accessor returns. */
37
+ publicContext: SignalRPublicContext<T>;
38
+ /** The store that you passed to the session. */
26
39
  statusStore: TStore;
27
- /** Lazy ref-count: keeps a hub alive while a consumer is mounted. */
40
+ /** Raises the lazy reference count of a hub. A lazy hub stays connected while the count is above 0. */
28
41
  acquire: (hub: keyof T & HubString) => void;
42
+ /** Lowers the lazy reference count of a hub. */
29
43
  release: (hub: keyof T & HubString) => void;
30
- /** Registers a reconnect callback for a hub. Returns an unsubscribe fn. */
44
+ /** Registers a callback that runs after each reconnect, not after the first connect. Returns an unsubscribe function. */
31
45
  registerReconnect: (hub: keyof T & HubString, cb: () => void) => () => void;
46
+ /** Registers an event handler. The handler survives rebuilds. Returns an unsubscribe function. */
47
+ subscribe: (hub: keyof T & HubString, event: string, handler: (...args: unknown[]) => void) => () => void;
32
48
  }
@@ -0,0 +1,9 @@
1
+ /** The `name` values of the errors that `waitForConnection` rejects with. */
2
+ export declare const SIGNALR_ERROR_NAMES: {
3
+ readonly disabled: "SignalRDisabledError";
4
+ readonly disconnected: "SignalRDisconnectedError";
5
+ readonly timeout: "SignalRTimeoutError";
6
+ };
7
+ export declare function namedError(name: (typeof SIGNALR_ERROR_NAMES)[keyof typeof SIGNALR_ERROR_NAMES], message: string): Error;
8
+ /** A wait on a disabled or failed hub cannot succeed by waiting longer. */
9
+ export declare function isFinalWaitError(error: unknown): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,16 @@
1
+ /** The `name` values of the errors that `waitForConnection` rejects with. */
2
+ export const SIGNALR_ERROR_NAMES = {
3
+ disabled: "SignalRDisabledError",
4
+ disconnected: "SignalRDisconnectedError",
5
+ timeout: "SignalRTimeoutError",
6
+ };
7
+ export function namedError(name, message) {
8
+ const error = new Error(message);
9
+ error.name = name;
10
+ return error;
11
+ }
12
+ /** A wait on a disabled or failed hub cannot succeed by waiting longer. */
13
+ export function isFinalWaitError(error) {
14
+ return (error instanceof Error &&
15
+ (error.name === SIGNALR_ERROR_NAMES.disabled || error.name === SIGNALR_ERROR_NAMES.disconnected));
16
+ }
@@ -1,12 +1,9 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- import type { HubConnectionStatus } from "./types.js";
3
2
  /** Live state for one hub connection, owned by the connection manager. */
4
3
  export interface HubEntry {
5
4
  connection: HubConnection;
6
- status: HubConnectionStatus;
7
- /** Resolves once Connected. Replaced on each rebuild. */
8
- ready: Promise<void>;
9
- resolveReady: () => void;
10
5
  /** Set before stop(), so the start() catch never reconnects a stopped hub. */
11
6
  stopping: boolean;
7
+ /** True from onreconnecting to onreconnected. A close in between means SignalR gave up. */
8
+ reconnecting: boolean;
12
9
  }
package/dist/index.d.ts CHANGED
@@ -1,14 +1,9 @@
1
1
  export { event, method } from "./types.js";
2
- export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, ReconnectConfig, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types.js";
3
- export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config.js";
4
- export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
5
- export type { HubEntry } from "./hub-entry.js";
6
- export { createConnectionManager } from "./connection-manager.js";
7
- export type { ConnectionManager, ConnectionManagerDeps } from "./connection-manager.js";
2
+ export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, SignalRErrorInfo, ReconnectConfig, HubProtocolConfig, HttpOptions, ConfigureBuilder, BuilderContext, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types.js";
3
+ export { hubKeys, resolveHubConfig } from "./config.js";
8
4
  export type { StatusStore } from "./status-store.js";
9
- export type { SignalRProviderPropsBase, SignalRContextValueBase } from "./context.js";
5
+ export type { SignalRProviderPropsBase, SignalRContextValueBase, SignalRPublicContext, } from "./context.js";
10
6
  export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
11
- export type { AbortScope } from "./calls.js";
12
- export type { CallTarget } from "./calls.js";
7
+ export type { AbortScope, CallTarget, InvokerOptions } from "./calls.js";
13
8
  export { createSignalRSession } from "./session.js";
14
- export type { SignalRSession, SignalRSessionDeps } from "./session.js";
9
+ export type { SignalRSession, SignalRSessionDeps, SignalRSessionValues } from "./session.js";
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
1
  export { event, method } from "./types.js";
2
- export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config.js";
3
- export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
4
- export { createConnectionManager } from "./connection-manager.js";
2
+ export { hubKeys, resolveHubConfig } from "./config.js";
5
3
  export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
6
4
  export { createSignalRSession } from "./session.js";
package/dist/retry.d.ts CHANGED
@@ -1,34 +1,8 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- export declare const DEFAULT_BACKOFF: number[];
3
- /**
4
- * Thrown by `useSignalRInvoke` when a retried call exhausts its retry budget.
5
- * Used only when `retries > 0`. With `retries === 0`, the raw server error is
6
- * rethrown unwrapped, so this error appears only if you opted into retries.
7
- */
8
- export declare class InvokeError extends Error {
9
- /** The last underlying error that caused the final attempt to fail. */
10
- readonly cause: unknown;
11
- /** Total number of attempts made, including the first, before giving up. */
12
- readonly attempts: number;
13
- /** Whether the final failure was classed as retriable (budget ran out) or not. */
14
- readonly retriable: boolean;
15
- constructor(message: string,
16
- /** The last underlying error that caused the final attempt to fail. */
17
- cause: unknown,
18
- /** Total number of attempts made, including the first, before giving up. */
19
- attempts: number,
20
- /** Whether the final failure was classed as retriable (budget ran out) or not. */
21
- retriable: boolean);
22
- }
23
- /**
24
- * Checks whether a failed invoke is worth a retry. This is keyed on
25
- * CONNECTION STATE, not the error message: a transport drop leaves the
26
- * connection not-Connected, so it is worth a retry. An error thrown while
27
- * still Connected is a genuine server or business error (HubException) and
28
- * must NOT be retried.
29
- */
2
+ export declare const DEFAULT_BACKOFF: readonly number[];
3
+ /** Keyed on connection state: a drop retries, a server error thrown while connected does not. */
30
4
  export declare function isRetriableInvokeError(error: unknown, connection: HubConnection): boolean;
31
5
  /** Resolves the backoff delay for an attempt, capped and jittered. */
32
- export declare function resolveBackoff(backoff: number[] | ((attempt: number) => number), attempt: number): number;
6
+ export declare function resolveBackoff(backoff: readonly number[] | ((attempt: number) => number), attempt: number): number;
33
7
  /** setTimeout wrapped as a cancellable promise. */
34
8
  export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/retry.js CHANGED
@@ -1,33 +1,7 @@
1
1
  import { AbortError, HttpError, HubConnectionState, TimeoutError, } from "@microsoft/signalr";
2
- export const DEFAULT_BACKOFF = [250, 1000, 3000, 5000];
2
+ export const DEFAULT_BACKOFF = Object.freeze([250, 1000, 3000, 5000]);
3
3
  const MAX_BACKOFF = 30000;
4
- /**
5
- * Thrown by `useSignalRInvoke` when a retried call exhausts its retry budget.
6
- * Used only when `retries > 0`. With `retries === 0`, the raw server error is
7
- * rethrown unwrapped, so this error appears only if you opted into retries.
8
- */
9
- export class InvokeError extends Error {
10
- constructor(message,
11
- /** The last underlying error that caused the final attempt to fail. */
12
- cause,
13
- /** Total number of attempts made, including the first, before giving up. */
14
- attempts,
15
- /** Whether the final failure was classed as retriable (budget ran out) or not. */
16
- retriable) {
17
- super(message);
18
- this.cause = cause;
19
- this.attempts = attempts;
20
- this.retriable = retriable;
21
- this.name = "InvokeError";
22
- }
23
- }
24
- /**
25
- * Checks whether a failed invoke is worth a retry. This is keyed on
26
- * CONNECTION STATE, not the error message: a transport drop leaves the
27
- * connection not-Connected, so it is worth a retry. An error thrown while
28
- * still Connected is a genuine server or business error (HubException) and
29
- * must NOT be retried.
30
- */
4
+ /** Keyed on connection state: a drop retries, a server error thrown while connected does not. */
31
5
  export function isRetriableInvokeError(error, connection) {
32
6
  if (connection.state !== HubConnectionState.Connected)
33
7
  return true;
@@ -39,7 +13,7 @@ export function isRetriableInvokeError(error, connection) {
39
13
  const s = error.statusCode;
40
14
  return s === 0 || s === 408 || s === 429 || s >= 500;
41
15
  }
42
- return false; // Connected + plain Error: a server business error, no retry
16
+ return false;
43
17
  }
44
18
  /** Resolves the backoff delay for an attempt, capped and jittered. */
45
19
  export function resolveBackoff(backoff, attempt) {
@@ -53,11 +27,11 @@ export function resolveBackoff(backoff, attempt) {
53
27
  export function sleep(ms, signal) {
54
28
  // An already-aborted signal never fires "abort", so check before listening.
55
29
  if (signal?.aborted)
56
- return Promise.reject(new AbortError("aborted"));
30
+ return Promise.reject(signal.reason);
57
31
  return new Promise((resolve, reject) => {
58
32
  const onAbort = () => {
59
33
  clearTimeout(t);
60
- reject(new AbortError("aborted"));
34
+ reject(signal?.reason);
61
35
  };
62
36
  const t = setTimeout(() => {
63
37
  signal?.removeEventListener("abort", onAbort);