@dammers/use-signalr-core 0.5.0 → 1.1.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.
package/dist/session.d.ts CHANGED
@@ -1,27 +1,44 @@
1
1
  import type { StatusStore } from "./status-store.js";
2
- import type { HubConnectionStatus, HubString, ResolvedHubConfig, SignalRContract } from "./types.js";
3
- import type { SignalRContextValueBase } from "./context.js";
2
+ import type { HubConnectionStatus, HubString, ResolvedHubConfig, SignalRContract, SignalRErrorInfo } from "./types.js";
3
+ import type { SignalRContextValueBase, SignalRPublicContext } from "./context.js";
4
4
  export interface SignalRSessionDeps<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>> {
5
+ /**
6
+ * The hub paths that the session manages.
7
+ * @remarks `Array<keyof T & HubString>`
8
+ */
5
9
  hubs: Array<keyof T & HubString>;
10
+ /** Returns the resolved config of one hub, the result of `resolveHubConfig`. */
6
11
  resolve: (hub: keyof T & HubString) => ResolvedHubConfig;
12
+ /** The store that receives every status change. */
7
13
  statusStore: TStore;
8
- /** Read at call time so token rotation never rebuilds the connection. */
14
+ /** Read on every negotiate and every auto-reconnect attempt, so a token change needs no rebuild. */
9
15
  getAccessToken: () => string | Promise<string>;
16
+ /** Called after the store changes. */
10
17
  onStatusChange?: (hub: keyof T & HubString, status: HubConnectionStatus) => void;
11
- onError?: (hub: keyof T & HubString, error: unknown) => void;
18
+ /** Called for connection errors and for errors that user callbacks throw. */
19
+ onError?: (hub: keyof T & HubString, error: unknown, info: SignalRErrorInfo) => void;
20
+ }
21
+ /** The values that a provider applies. */
22
+ export interface SignalRSessionValues {
23
+ /** The base URL of the server. An empty value disables the session. */
24
+ baseUrl?: string;
25
+ /**
26
+ * When `false`, the session stops and every hub is `idle`.
27
+ * @default true
28
+ */
29
+ enabled?: boolean;
30
+ /** A different value rebuilds the connections. */
31
+ connectionKey?: string | number;
12
32
  }
13
33
  export interface SignalRSession<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>> {
14
- /** Build/replace the live manager generation for this baseUrl. Disposes the previous one. */
15
- start: (baseUrl: string) => void;
16
- /** Dispose the live generation and mark every hub disconnected. Idempotent. */
34
+ /** Sets every hub to `"idle"`, closes the live connections, and forgets which hubs connected before. A connected hub with a pending teardown call stays open until the send ends. Calling it again leaves the hubs stopped. It also ends the waits of teardown calls that began after the first call. */
17
35
  stop: () => void;
18
- /** The value an adapter puts into its framework context. Stable identity. */
36
+ /** Does nothing if the values equal the last applied values. Otherwise it disposes the live connections and, if `enabled` is true and `baseUrl` is not empty, builds new ones. A rebuild keeps which hubs connected, so their reconnect callbacks run. */
37
+ update: (values: SignalRSessionValues) => void;
38
+ /** The value that an adapter puts into its framework context. Its identity is stable. */
19
39
  context: SignalRContextValueBase<T, TStore>;
40
+ /** The frozen object with `getConnection`, `getStatus`, and `waitForConnection`. Its identity is stable. */
41
+ publicContext: SignalRPublicContext<T>;
20
42
  }
21
- /**
22
- * Owns the adapter-facing half of a provider: the manager generation, lazy
23
- * ref-counts, reconnect listeners, and the context value built on top of
24
- * them. Framework adapters own only reactive translation, context
25
- * propagation, and lifecycle binding — everything else lives here.
26
- */
43
+ /** Owns the live connections, the lazy reference counts, the reconnect listeners, and the context value. Adapters add only framework binding. */
27
44
  export declare function createSignalRSession<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>>(deps: SignalRSessionDeps<T, TStore>): SignalRSession<T, TStore>;
package/dist/session.js CHANGED
@@ -1,57 +1,202 @@
1
- import { createConnectionManager } from "./connection-manager.js";
2
- /**
3
- * Owns the adapter-facing half of a provider: the manager generation, lazy
4
- * ref-counts, reconnect listeners, and the context value built on top of
5
- * them. Framework adapters own only reactive translation, context
6
- * propagation, and lifecycle binding — everything else lives here.
7
- */
1
+ import { HubConnectionState } from "@microsoft/signalr";
2
+ import { createConnectionManager, runUserCallback } from "./connection-manager.js";
3
+ import { SIGNALR_ERROR_NAMES, namedError } from "./errors.js";
4
+ import { MAX_TIMER_MS } from "./timers.js";
5
+ /** Owns the live connections, the lazy reference counts, the reconnect listeners, and the context value. Adapters add only framework binding. */
8
6
  export function createSignalRSession(deps) {
9
7
  const { hubs, resolve, statusStore, getAccessToken, onStatusChange, onError } = deps;
10
- // Lazy ref-counts, pending stop timers, and reconnect listeners persist
8
+ const reportCallbackError = (hub, err) => onError?.(hub, err, { source: "callback" });
9
+ // Lazy ref-counts, stop timers, reconnect listeners, connect history, and event handlers persist
11
10
  // across rebuilds. The live manager is swapped per generation.
12
11
  const refCounts = new Map();
13
12
  const stopTimers = new Map();
14
13
  const reconnectListeners = new Map();
14
+ const connectedBefore = new Set();
15
+ const handlers = new Map();
16
+ const waiters = new Map();
17
+ // Hubs that stopped after a non-retriable error, with the error. A wait on one can never succeed.
18
+ const failed = new Map();
19
+ const pendingSends = new Map();
20
+ const heldConnections = new Set();
21
+ let disabled = false;
15
22
  let current = null;
23
+ let applied = null;
24
+ const dispatch = (hub, event, args) => {
25
+ const set = handlers.get(hub)?.get(event);
26
+ if (!set)
27
+ return;
28
+ [...set].forEach((handler) => runUserCallback(hub, () => handler(...args), reportCallbackError));
29
+ };
30
+ const flushWaiters = (hub) => {
31
+ const connection = current?.getConnection(hub);
32
+ const set = waiters.get(hub);
33
+ if (!connection || !set)
34
+ return;
35
+ [...set].forEach((waiter) => waiter.resolve(connection));
36
+ };
37
+ const rejectWaiters = (hub, error) => {
38
+ const set = waiters.get(hub);
39
+ if (set)
40
+ [...set].forEach((waiter) => waiter.reject(error));
41
+ };
42
+ const disabledError = (hub) => namedError(SIGNALR_ERROR_NAMES.disabled, `SignalR is disabled: ${hub}`);
43
+ const failHub = (hub, cause) => {
44
+ const reason = cause instanceof Error ? cause.message : String(cause);
45
+ const error = namedError(SIGNALR_ERROR_NAMES.disconnected, `SignalR hub ${hub} is disconnected: ${reason}`);
46
+ failed.set(hub, error);
47
+ rejectWaiters(hub, error);
48
+ };
49
+ const waitForConnection = (hub, timeoutMs, signal) => new Promise((resolvePromise, reject) => {
50
+ if (signal?.aborted)
51
+ return reject(signal.reason);
52
+ const live = current?.getConnection(hub);
53
+ if (live?.state === HubConnectionState.Connected)
54
+ return resolvePromise(live);
55
+ if (disabled)
56
+ return reject(disabledError(hub));
57
+ const failure = failed.get(hub);
58
+ if (failure)
59
+ return reject(failure);
60
+ let set = waiters.get(hub);
61
+ if (!set)
62
+ waiters.set(hub, (set = new Set()));
63
+ const settle = () => {
64
+ if (timer !== undefined)
65
+ clearTimeout(timer);
66
+ signal?.removeEventListener("abort", onAbort);
67
+ set.delete(waiter);
68
+ };
69
+ const waiter = {
70
+ resolve: (connection) => {
71
+ settle();
72
+ resolvePromise(connection);
73
+ },
74
+ reject: (error) => {
75
+ settle();
76
+ reject(error);
77
+ },
78
+ };
79
+ const onAbort = () => {
80
+ settle();
81
+ reject(signal?.reason);
82
+ };
83
+ const timer = Number.isFinite(timeoutMs)
84
+ ? setTimeout(() => {
85
+ settle();
86
+ reject(namedError(SIGNALR_ERROR_NAMES.timeout, `Timeout waiting for SignalR connection to ${hub} (${timeoutMs}ms)`));
87
+ }, Math.min(timeoutMs, MAX_TIMER_MS))
88
+ : undefined;
89
+ set.add(waiter);
90
+ signal?.addEventListener("abort", onAbort, { once: true });
91
+ });
16
92
  const start = (baseUrl) => {
17
- current?.dispose();
18
- current = null;
93
+ if (current)
94
+ teardown();
19
95
  const manager = createConnectionManager({
20
96
  baseUrl,
21
97
  hubs,
22
98
  resolve,
23
- getAccessToken: () => getAccessToken(),
99
+ getAccessToken,
24
100
  refCounts,
25
101
  stopTimers,
26
102
  reconnectListeners,
27
- onStatus: (hub, status) => {
28
- statusStore.set(hub, status);
29
- onStatusChange?.(hub, status);
103
+ connectedBefore,
104
+ dispatch,
105
+ onStatus: (hub, status, error) => {
106
+ if (current === manager) {
107
+ if (status === "connected")
108
+ flushWaiters(hub);
109
+ if (status === "disconnected")
110
+ failHub(hub, error);
111
+ else
112
+ failed.delete(hub);
113
+ }
114
+ runUserCallback(hub, () => statusStore.set(hub, status), reportCallbackError);
115
+ runUserCallback(hub, () => onStatusChange?.(hub, status), reportCallbackError);
30
116
  },
31
- onError: (hub, err) => onError?.(hub, err),
117
+ onError: (hub, err, info) => onError?.(hub, err, info),
32
118
  isCurrent: () => current === manager,
33
119
  });
34
120
  current = manager;
35
121
  manager.reconcile(); // build eager hubs plus already-referenced lazy hubs
36
122
  };
37
- const stop = () => {
38
- // Notify synchronous adapter stores while the live connections are still
39
- // available, so they can detach event handlers deterministically.
40
- hubs.forEach((h) => statusStore.set(h, "disconnected"));
41
- current?.dispose();
123
+ const closeHeldWithout = (send) => {
124
+ heldConnections.forEach((held) => {
125
+ held.sends.delete(send);
126
+ if (held.sends.size > 0)
127
+ return;
128
+ heldConnections.delete(held);
129
+ void held.connection.stop().catch((err) => runUserCallback(held.hub, () => onError?.(held.hub, err, { source: "connection" }), () => { }));
130
+ });
131
+ };
132
+ // A send that is not bound yet counts as bound to a connected hub: its wait has resolved, and `use()` runs a microtask later.
133
+ const sendsOnLiveConnections = () => {
134
+ const keep = new Map();
135
+ hubs.forEach((h) => {
136
+ const connection = current?.getConnection(h);
137
+ if (connection?.state !== HubConnectionState.Connected)
138
+ return;
139
+ const live = [...(pendingSends.get(h) ?? [])].filter((send) => send.connection === connection || send.connection === undefined);
140
+ if (live.length > 0)
141
+ keep.set(h, new Set(live));
142
+ });
143
+ return keep;
144
+ };
145
+ const teardown = (keepPendingSends = false) => {
146
+ // Publish before dispose, so listeners still see the live connection.
147
+ hubs.forEach((h) => {
148
+ const wasIdle = statusStore.get(h) === "idle";
149
+ runUserCallback(h, () => statusStore.set(h, "idle"), reportCallbackError);
150
+ if (wasIdle)
151
+ return;
152
+ runUserCallback(h, () => onStatusChange?.(h, "idle"), reportCallbackError);
153
+ });
154
+ // Read after the publish: a listener may begin a teardown during it.
155
+ const keep = keepPendingSends ? sendsOnLiveConnections() : undefined;
156
+ current
157
+ ?.dispose(keep && new Set(keep.keys()))
158
+ .forEach((connection, hub) => heldConnections.add({ hub, connection, sends: new Set(keep?.get(hub)) }));
159
+ hubs.forEach((h) => {
160
+ if (resolve(h).lazy && !refCounts.get(h))
161
+ connectedBefore.delete(h); // a lazy hub with no consumer starts fresh
162
+ });
42
163
  current = null;
164
+ applied = null;
165
+ failed.clear();
166
+ };
167
+ const stop = () => {
168
+ teardown(true);
169
+ connectedBefore.clear();
170
+ pendingSends.forEach((set) => set.forEach((send) => send.controller.abort()));
171
+ };
172
+ const update = ({ baseUrl, enabled, connectionKey }) => {
173
+ const next = { baseUrl, enabled: enabled !== false, connectionKey };
174
+ if (applied &&
175
+ Object.is(applied.baseUrl, next.baseUrl) &&
176
+ applied.enabled === next.enabled &&
177
+ Object.is(applied.connectionKey, next.connectionKey))
178
+ return;
179
+ teardown();
180
+ applied = next; // before start(), so a nested update() from a status callback wins
181
+ disabled = !(next.enabled && baseUrl);
182
+ if (disabled)
183
+ hubs.forEach((hub) => rejectWaiters(hub, disabledError(hub)));
184
+ else
185
+ start(baseUrl);
43
186
  };
187
+ const getConnection = (hub) => current?.getConnection(hub) ?? null;
188
+ const getStatus = (hub) => statusStore.get(hub);
189
+ const publicContext = Object.freeze({
190
+ getConnection,
191
+ getStatus,
192
+ waitForConnection,
193
+ });
44
194
  const context = {
45
- getConnection: (hub) => current?.getConnection(hub) ?? null,
46
- isHubConnected: (hub) => statusStore.get(hub) === "connected",
47
- getStatus: (hub) => statusStore.get(hub),
195
+ getConnection,
196
+ getStatus,
197
+ publicContext,
48
198
  statusStore,
49
- waitForConnection: (hub, timeoutMs) => {
50
- if (!current) {
51
- return Promise.reject(new Error(`SignalR not connected: ${String(hub)}`));
52
- }
53
- return current.waitForConnection(hub, timeoutMs);
54
- },
199
+ waitForConnection,
55
200
  acquire: (hub) => {
56
201
  const next = (refCounts.get(hub) ?? 0) + 1;
57
202
  refCounts.set(hub, next);
@@ -64,6 +209,31 @@ export function createSignalRSession(deps) {
64
209
  if (next === 0)
65
210
  current?.reconcile();
66
211
  },
212
+ beginSend: (hub) => {
213
+ const live = current?.getConnection(hub);
214
+ const send = {
215
+ controller: new AbortController(),
216
+ connection: live?.state === HubConnectionState.Connected ? live : undefined,
217
+ };
218
+ let set = pendingSends.get(hub);
219
+ if (!set)
220
+ pendingSends.set(hub, (set = new Set()));
221
+ set.add(send);
222
+ let ended = false;
223
+ return {
224
+ signal: send.controller.signal,
225
+ use: (connection) => {
226
+ send.connection = connection;
227
+ },
228
+ end: () => {
229
+ if (ended)
230
+ return;
231
+ ended = true;
232
+ set.delete(send);
233
+ closeHeldWithout(send);
234
+ },
235
+ };
236
+ },
67
237
  registerReconnect: (hub, cb) => {
68
238
  let set = reconnectListeners.get(hub);
69
239
  if (!set)
@@ -71,6 +241,16 @@ export function createSignalRSession(deps) {
71
241
  set.add(cb);
72
242
  return () => set.delete(cb);
73
243
  },
244
+ subscribe: (hub, event, handler) => {
245
+ let byEvent = handlers.get(hub);
246
+ if (!byEvent)
247
+ handlers.set(hub, (byEvent = new Map()));
248
+ let set = byEvent.get(event);
249
+ if (!set)
250
+ byEvent.set(event, (set = new Set()));
251
+ set.add(handler);
252
+ return () => set.delete(handler);
253
+ },
74
254
  };
75
- return { start, stop, context };
255
+ return { stop, update, context, publicContext };
76
256
  }
@@ -1,6 +1,8 @@
1
1
  import type { HubConnectionStatus } from "./types.js";
2
- /** Per-hub status store: point reads and writes keyed by hub. */
2
+ /** Per-hub status store: one-time reads and writes keyed by hub. */
3
3
  export interface StatusStore<H extends string> {
4
+ /** Returns the status of a hub. Must return `"idle"` for a hub without a value. */
4
5
  get: (hub: H) => HubConnectionStatus;
6
+ /** Stores the status of a hub. */
5
7
  set: (hub: H, status: HubConnectionStatus) => void;
6
8
  }
@@ -0,0 +1,2 @@
1
+ /** The longest delay that `setTimeout` accepts. A larger value fires at once. */
2
+ export declare const MAX_TIMER_MS: number;
package/dist/timers.js ADDED
@@ -0,0 +1,2 @@
1
+ /** The longest delay that `setTimeout` accepts. A larger value fires at once. */
2
+ export const MAX_TIMER_MS = 2 ** 31 - 1;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { HttpTransportType, IRetryPolicy, LogLevel } from "@microsoft/signalr";
1
+ import type { HubConnectionBuilder, IHttpConnectionOptions, IHubProtocol, IRetryPolicy, LogLevel } from "@microsoft/signalr";
2
2
  /** A hub path, for example `/hubs/chat`. */
3
3
  export type HubString = `/${string}`;
4
4
  /**
@@ -58,86 +58,147 @@ export type MethodName<T, H extends keyof T> = keyof Methods<T, H> & string;
58
58
  export type EventArgs<T, H extends keyof T, E extends EventName<T, H>> = Events<T, H>[E] extends (...args: infer A) => any ? A : never;
59
59
  export type MethodArgs<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: infer A) => any ? A : never;
60
60
  export type MethodReturn<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: any[]) => Promise<infer R> ? R : unknown;
61
- export type HubConnectionStatus = "disconnected" | "connecting" | "connected" | "reconnecting"
62
- /** Transient: fires once after a successful reconnect (not on the first connect). */
63
- | "reconnected";
61
+ export type HubConnectionStatus =
62
+ /** No connection is wanted: not started, disabled, stopped, or a lazy hub with no consumer. */
63
+ "idle" | "connecting" | "connected" | "reconnecting"
64
+ /** The connection is wanted but down after a non-retriable error. */
65
+ | "disconnected";
66
+ /** Says where an `onError` error came from. */
67
+ export interface SignalRErrorInfo {
68
+ /** `"connection"`: connect, negotiate, build, close, or protocol errors.
69
+ * `"callback"`: an error that your event handler, reconnect callback, or
70
+ * `onStatusChange` throws or rejects with. */
71
+ source: "connection" | "callback";
72
+ }
64
73
  /** Reconnect strategy: `true` for the library default, `false` for none, an
65
- * array of retry delays in ms, or a custom policy. */
74
+ * array of retry delays in ms, or a custom policy. `false` turns off SignalR
75
+ * auto-reconnect only. The library still rebuilds a lost connection with its own delays. */
66
76
  export type ReconnectConfig = boolean | number[] | IRetryPolicy;
67
- /** Per-hub overrides. Anything omitted falls back to the global config. */
77
+ /** Options for the SignalR HTTP connection. The library owns `accessTokenFactory`. */
78
+ export type HttpOptions = Omit<IHttpConnectionOptions, "accessTokenFactory">;
79
+ /** A hub protocol, or a factory that the library calls once per connection build. */
80
+ export type HubProtocolConfig = IHubProtocol | (() => IHubProtocol);
81
+ /** Context for {@link ConfigureBuilder}. */
82
+ export interface BuilderContext {
83
+ hub: HubString;
84
+ baseUrl: string;
85
+ }
86
+ /** Changes the connection builder. It must return the builder to use. */
87
+ export type ConfigureBuilder = (builder: HubConnectionBuilder, ctx: BuilderContext) => HubConnectionBuilder;
88
+ /** Per-hub overrides. The global value is the fallback for each option that you omit. */
68
89
  export interface PerHubConfig {
69
- /** Connect this hub only when first consumed; disconnect when the last
70
- * consumer unmounts. Default: the global `lazy` (false). */
90
+ /**
91
+ * Connect this hub when its first consumer appears, and disconnect when the last consumer leaves. Falls back to the global `lazy`.
92
+ */
71
93
  lazy?: boolean;
72
- /** Grace period in ms before a lazy hub disconnects after its last consumer
73
- * leaves. Avoids churn on quick remounts. Default 0. */
94
+ /**
95
+ * Time in ms that a lazy hub stays connected after its last consumer leaves. This option exists only per hub.
96
+ * @default 0
97
+ */
74
98
  graceMs?: number;
75
- /** Reconnect strategy. Default: the global value, else `true`. */
99
+ /**
100
+ * The reconnect strategy of SignalR. `true` uses the SignalR default delays of 0, 2, 10, and 30 seconds. `false` turns off SignalR auto-reconnect only. The library still rebuilds a lost connection. Falls back to the global `reconnect`, else `true`.
101
+ */
76
102
  reconnect?: ReconnectConfig;
77
- /** Connect retries before giving up. Default: the global value (2). */
78
- maxConnectRetries?: number;
103
+ /**
104
+ * The log level of the SignalR client for this hub. Falls back to the global `logLevel`, else `LogLevel.Information`.
105
+ */
79
106
  logLevel?: LogLevel;
80
- transport?: HttpTransportType;
81
- skipNegotiation?: boolean;
107
+ /**
108
+ * Merged over the global `httpOptions`. The per-hub key wins. `headers` merge by name.
109
+ */
110
+ httpOptions?: HttpOptions;
111
+ /**
112
+ * The hub protocol, for example `() => new MessagePackHubProtocol()`. The per-hub value wins. Falls back to the global `hubProtocol`, else JSON.
113
+ */
114
+ hubProtocol?: HubProtocolConfig;
115
+ /** Runs on every connection build, after the library's own builder calls. The global hook runs first, then this hook. */
116
+ configureBuilder?: ConfigureBuilder;
82
117
  }
83
- /** Config passed to `createSignalRClient(config)`. The keys of `hubs` are the
84
- * hubs; each value's `events`/`methods` (declared with {@link event}/{@link method})
85
- * are that hub's contract. */
118
+ /** Maps every key that a hub definition does not declare to `never`. */
119
+ type NoUnknownHubKeys<H> = {
120
+ [P in keyof H]: {
121
+ [K in Exclude<keyof H[P], keyof HubDef>]: never;
122
+ };
123
+ };
124
+ /** Config that you pass to `createSignalRClient`. These are the global defaults for all hubs. */
86
125
  export interface SignalRClientConfig<H extends Record<HubString, HubDef>> {
87
- /** One entry per hub. Each value is a {@link HubDef}: per-hub config plus
88
- * its event/method declarations. */
89
- hubs: H;
90
- /** Global default: connect hubs only on demand. Default false — all
91
- * configured hubs connect upfront. */
126
+ /**
127
+ * One entry per hub. The key is the hub path, such as `/hubs/rooms`. The value holds the hub config and its `events` and `methods`. Unknown keys are a type error.
128
+ * @remarks `Record<HubString, HubDef>`
129
+ */
130
+ hubs: H & NoUnknownHubKeys<H>;
131
+ /**
132
+ * Connect hubs only when a consumer first uses them. By default, all configured hubs connect at the start.
133
+ * @default false
134
+ */
92
135
  lazy?: boolean;
93
- /** Global reconnect strategy. Default true. */
136
+ /**
137
+ * The reconnect strategy of SignalR. `true` uses the SignalR default delays of 0, 2, 10, and 30 seconds. `false` turns off SignalR auto-reconnect only. The library still rebuilds a lost connection.
138
+ * @default true
139
+ */
94
140
  reconnect?: ReconnectConfig;
95
- /** Global connect-retry budget. Default 2. */
96
- maxConnectRetries?: number;
141
+ /**
142
+ * The log level of the SignalR client.
143
+ * @default LogLevel.Information
144
+ */
97
145
  logLevel?: LogLevel;
146
+ /**
147
+ * Options for the HTTP connection, such as `headers` and `transport`. The library sets `accessTokenFactory`, so it is not part of the type.
148
+ * @default {}
149
+ */
150
+ httpOptions?: HttpOptions;
151
+ /**
152
+ * The hub protocol, for example `() => new MessagePackHubProtocol()`. A factory runs once for each connection build.
153
+ * @default new JsonHubProtocol()
154
+ */
155
+ hubProtocol?: HubProtocolConfig;
156
+ /** Runs on every connection build, after the library's own builder calls. Return the builder to use. */
157
+ configureBuilder?: ConfigureBuilder;
98
158
  }
99
- /** Per-hub config with all defaults resolved. */
159
+ /** Per-hub config with all defaults resolved. `resolve` returns the result of `resolveHubConfig`. The shape can grow. */
100
160
  export interface ResolvedHubConfig {
101
161
  lazy: boolean;
102
162
  graceMs: number;
103
163
  reconnect: ReconnectConfig;
104
- maxConnectRetries: number;
105
164
  logLevel: LogLevel;
106
- transport?: HttpTransportType;
107
- skipNegotiation?: boolean;
165
+ httpOptions: HttpOptions;
166
+ hubProtocol: HubProtocolConfig | undefined;
167
+ /** The global hook first, then the per-hub hook. */
168
+ configureBuilders: ConfigureBuilder[];
108
169
  events: string[];
109
170
  }
110
171
  /** Options for an invoke call. */
111
172
  export interface InvokeOptions {
112
173
  /**
113
- * Auto-retry count for RETRIABLE failures. Default 0 (fail fast).
114
- * Warning: invoke is at-least-once. A drop after the server processed the
115
- * call, but before its completion reaches the client, re-runs the call.
116
- * Set this above 0 only for IDEMPOTENT methods.
174
+ * Number of retries for retriable failures. A retry can run the call twice, so use it only for idempotent methods.
175
+ * @default 0
117
176
  */
118
177
  retries?: number;
119
- /** Per-attempt wait-for-connection plus invoke deadline in ms. Default 10_000. */
178
+ /**
179
+ * Maximum wait in ms for the connection, for each attempt. It does not limit the invoke itself. `Infinity` waits without a limit. A value above 2^31-1 is clamped to 2^31-1.
180
+ * @default 10000
181
+ */
120
182
  timeout?: number;
121
- /** Backoff: fixed delays per attempt, or a fn(attempt) => ms. Capped at 30s
122
- * and jittered. Default [250, 1000, 3000, 5000]. */
183
+ /**
184
+ * The delay in ms before each retry. The last array value repeats. A function gets the attempt number, starting at 0. The cap is 30 seconds, and the delay has a jitter of 50 to 100 percent.
185
+ * @default [250, 1000, 3000, 5000]
186
+ */
123
187
  backoff?: number[] | ((attempt: number) => number);
124
- /** Forces retriable or not. true = retry, false = throw now, undefined =
125
- * the default rule. */
188
+ /** `true` retries, `false` throws at once, `undefined` uses the default rule. */
126
189
  isRetriable?: (error: unknown) => boolean | undefined;
127
190
  /**
128
- * Keeps an in-flight call alive when the calling consumer tears down.
129
- * Default false: in-flight invokes are aborted on teardown, which is
130
- * correct for query-like reads. Set true for a method invoked in a
131
- * cleanup handler, so it still reaches the server. The detached call
132
- * survives teardown, but a still-pending retry loop is NOT cancelled. For
133
- * the connecting-race and lazy-hub case, use `useSignalRTeardown` instead.
191
+ * If `true`, ending the consumer does not abort the wait or the retry delays, and the call holds a lazy hub open until it settles. If `false`, ending the consumer aborts them with an `AbortError`. A call that was already sent finishes in both cases.
192
+ * @default false
134
193
  */
135
194
  keepAliveOnUnmount?: boolean;
136
195
  }
137
- /** Options for a `useSignalRTeardown` call. */
196
+ /** Options for a teardown send. */
138
197
  export interface TeardownOptions {
139
- /** Max time in ms to wait for the hub to (re)connect before giving up the
140
- * flush. Default 10_000. */
198
+ /**
199
+ * Maximum time in ms for the whole call: the wait for the hub to connect and the send. After that the library gives up and the call resolves `false`. A timeout above 2^31-1 ms counts as 2^31-1 ms. With a timeout that is not finite, the call has no time limit, and a send that never ends keeps its connection open.
200
+ * @default 10000
201
+ */
141
202
  timeout?: number;
142
203
  }
143
204
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dammers/use-signalr-core",
3
- "version": "0.5.0",
3
+ "version": "1.1.0",
4
4
  "description": "Framework-free typed multi-hub SignalR core: connection lifecycle, contracts, retry.",
5
5
  "author": "Dammers",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/DammersCode/use-signalr.git",
10
10
  "directory": "packages/core"
11
11
  },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/core#readme",
12
+ "homepage": "https://use-signalr.vercel.app/docs/core",
13
13
  "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
14
  "keywords": [
15
15
  "signalr",
@@ -18,7 +18,7 @@
18
18
  "websocket"
19
19
  ],
20
20
  "engines": {
21
- "node": ">=18"
21
+ "node": ">=20.19"
22
22
  },
23
23
  "type": "module",
24
24
  "sideEffects": false,
@@ -27,8 +27,10 @@
27
27
  "exports": {
28
28
  ".": {
29
29
  "types": "./dist/index.d.ts",
30
- "import": "./dist/index.js"
31
- }
30
+ "import": "./dist/index.js",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./package.json": "./package.json"
32
34
  },
33
35
  "files": [
34
36
  "dist"
@@ -43,9 +45,9 @@
43
45
  "test": "vitest run"
44
46
  },
45
47
  "peerDependencies": {
46
- "@microsoft/signalr": ">=8"
48
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0"
47
49
  },
48
50
  "devDependencies": {
49
- "@microsoft/signalr": ">=8"
51
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0"
50
52
  }
51
53
  }