@dammers/use-signalr-core 0.4.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.
package/README.md CHANGED
@@ -1,45 +1,35 @@
1
1
  # @dammers/use-signalr-core
2
2
 
3
- Framework-free connection lifecycle, contracts, and retry logic for [SignalR](https://learn.microsoft.com/aspnet/core/signalr): the shared engine behind `@dammers/use-signalr-react` and `@dammers/use-signalr-solid`.
3
+ The framework-free core of [use-signalr](https://use-signalr.vercel.app): connection lifecycle, the hub contract, recovery, and call helpers for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr).
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-core.svg)](https://www.npmjs.com/package/@dammers/use-signalr-core)
6
- ![types](https://img.shields.io/badge/types-included-blue.svg)
7
- [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
6
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
8
7
 
9
- ## Who needs this
8
+ This package is for adapter authors. To use SignalR in an app, install the adapter for your framework:
10
9
 
11
- Adapter authors — if you are building bindings for a framework this repo does not already cover. This package has no provider, no hooks, no reactive layer: it owns connection lifecycle, contract types, and retry/backoff math, and leaves rendering to the adapter.
12
-
13
- Building an app? Install `@dammers/use-signalr-react` or `@dammers/use-signalr-solid` instead — this package is a dependency of both, not something you install directly.
10
+ | Package | Framework |
11
+ | --- | --- |
12
+ | [`@dammers/use-signalr-react`](https://use-signalr.vercel.app/docs/react) | React |
13
+ | [`@dammers/use-signalr-vue`](https://use-signalr.vercel.app/docs/vue) | Vue |
14
+ | [`@dammers/use-signalr-angular`](https://use-signalr.vercel.app/docs/angular) | Angular |
15
+ | [`@dammers/use-signalr-svelte`](https://use-signalr.vercel.app/docs/svelte) | Svelte |
16
+ | [`@dammers/use-signalr-preact`](https://use-signalr.vercel.app/docs/preact) | Preact |
17
+ | [`@dammers/use-signalr-solid`](https://use-signalr.vercel.app/docs/solid) | Solid |
18
+ | [`@dammers/use-signalr-lit`](https://use-signalr.vercel.app/docs/lit) | Lit |
14
19
 
15
20
  ## Install
16
21
 
17
22
  ```bash
18
- npm i @dammers/use-signalr-core @microsoft/signalr
23
+ npm install @dammers/use-signalr-core @microsoft/signalr
19
24
  ```
20
25
 
21
- Requires `@microsoft/signalr` ≥ 8.
22
-
23
- ## What it exposes
24
-
25
- | Export | What it does |
26
- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
27
- | `createConnectionManager(deps)` | Owns one provider generation's `HubConnection`s: build, start with retry, lazy ref-counted start/stop, reconnect fan-out. No framework dependency — driven by callbacks. |
28
- | `createInvoker(deps, hub, method, getOptions, onAbort)` | Builds the request/response call function behind an invoke hook: waits for connection, retries idempotent failures, rethrows business errors. |
29
- | `createSender(getConnection, hub, method)` | Builds the fire-and-forget call function behind a send hook: drops if not connected. |
30
- | `createTeardownSender(deps, hub, method, getOptions)` | Builds the reliable teardown call function: survives disposal, queues while connecting, holds a lazy hub open until flushed. |
31
- | `event<Args>()` / `method<Args, Return?>()` | Contract markers used inside `hubs.<path>.events` / `.methods` to declare what a hub pushes and what it accepts. |
32
- | `hubKeys(config)`, `resolveHubConfig(config, hubConfig)` | Resolve per-hub config against global defaults. |
33
- | `isRetriableConnectError`, `isRetriableInvokeError`, `resolveBackoff`, `DEFAULT_BACKOFF`, `sleep`, `InvokeError` | Retry/backoff building blocks and the error type thrown once an invoke's attempts are exhausted. |
34
-
35
- Plus the contract and config types: `HubString`, `HubContract`, `SignalRContract`, `EventDef`, `MethodDef`, `HubDef`, `InferContract`, `EventName`, `MethodName`, `EventArgs`, `MethodArgs`, `MethodReturn`, `HubConnectionStatus`, `ReconnectConfig`, `PerHubConfig`, `SignalRClientConfig`, `ResolvedHubConfig`, `InvokeOptions`, `TeardownOptions`, `StatusStore`, `SignalRProviderPropsBase`, `SignalRContextValueBase`, `ConnectionManager`, `ConnectionManagerDeps`, `HubEntry`, `CallTarget`.
36
-
37
- An adapter wraps `createConnectionManager` in its own reactive provider (context + hooks + a status store built on its framework's primitives), and wraps the three call factories in hooks that supply the framework's own acquire/release and abort/cleanup lifecycle. See `packages/react` and `packages/solid` in this repo for two full implementations.
26
+ It needs `@microsoft/signalr` ^8 || ^9 || ^10 and Node 20.19 or later. It has no runtime dependencies.
38
27
 
39
- ## More
28
+ ## Documentation
40
29
 
41
- Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) live in the [root README](https://github.com/DammersCode/use-signalr#readme).
30
+ - [Build an adapter](https://use-signalr.vercel.app/docs/core/build-an-adapter)
31
+ - [API reference](https://use-signalr.vercel.app/docs/core/reference/api)
42
32
 
43
33
  ## License
44
34
 
45
- MIT © [DammersCode](https://github.com/DammersCode)
35
+ [MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
package/dist/calls.d.ts CHANGED
@@ -1,31 +1,52 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types";
2
+ import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types.js";
3
+ /** One shared signal for all in-flight calls of a consumer. `abort` cancels them and starts a fresh signal. */
4
+ export interface AbortScope {
5
+ /** Returns the current signal. Pass it as `getSignal`. */
6
+ signal: () => AbortSignal;
7
+ /** Aborts the current signal with an `AbortError`, and starts a fresh signal. */
8
+ abort: () => void;
9
+ }
10
+ export declare function createAbortScope(): AbortScope;
11
+ /** The members of the context that the invoker needs. */
3
12
  export interface CallTarget<T extends SignalRContract> {
4
- waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
13
+ /** Resolves when the hub is connected. */
14
+ waitForConnection: (hub: keyof T & HubString, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
15
+ /** The live `HubConnection` of the hub, or `null` when none exists. */
5
16
  getConnection: (hub: keyof T & HubString) => HubConnection | null;
17
+ /** With `keepAliveOnUnmount`, a call holds a lazy hub with `acquire` and `release` until it settles. Pass both or neither. */
18
+ acquire?: (hub: keyof T & HubString) => void;
19
+ /** Lowers the count that `acquire` raised. */
20
+ release?: (hub: keyof T & HubString) => void;
21
+ }
22
+ export interface InvokerOptions<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>> {
23
+ /** The object that provides `waitForConnection` and `getConnection`. Pass the session context. */
24
+ target: CallTarget<T>;
25
+ /** The hub path. */
26
+ hub: H;
27
+ /** The method name. */
28
+ method: M;
29
+ /** Called at call time. Returns the `InvokeOptions` for this call. */
30
+ getOptions: () => InvokeOptions | undefined;
31
+ /** Called at call time. Aborting the returned signal aborts the call. */
32
+ getSignal?: () => AbortSignal | undefined;
6
33
  }
7
- /**
8
- * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
9
- * called at CALL time (not build time), so the adapter can pass a ref/latest
10
- * accessor and preserve latest-options semantics. `setAbort` is called once
11
- * per invocation with the new controller, so the adapter's unmount/cleanup
12
- * handler can abort the in-flight call.
13
- */
14
- export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(target: CallTarget<T>, hub: H, method: M, getOptions: () => InvokeOptions | undefined, setAbort: (ac: AbortController) => void): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
15
- /**
16
- * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
17
- * connection at call time and never depends on render/tracked state, so it
18
- * is safe to capture in an unmount/cleanup handler.
19
- */
20
- export declare function createSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(getConnection: (hub: H) => HubConnection | null, hub: H, method: M): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
21
- /**
22
- * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
23
- * detached from the caller's lifecycle: it acquires the hub itself, waits
24
- * for a connection, sends, then releases — independent of the component
25
- * that created it having already unmounted.
26
- */
27
- export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(deps: {
28
- acquire: (hub: H) => void;
29
- release: (hub: H) => void;
30
- waitForConnection: (hub: H, timeoutMs: number) => Promise<HubConnection>;
31
- }, hub: H, method: M, getOptions: () => TeardownOptions | undefined): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
34
+ /** Builds the stable invoke function for one hub method. */
35
+ export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ target, hub, method, getOptions, getSignal, }: InvokerOptions<T, H, M>): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
36
+ /** Fire-and-forget sender. It reads the connection at call time, so a teardown handler can capture it. */
37
+ export declare function createSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ getConnection, hub, method, }: {
38
+ getConnection: (hub: H) => HubConnection | null;
39
+ hub: H;
40
+ method: M;
41
+ }): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
42
+ /** Teardown sender. It acquires the hub itself, so it still works after its consumer is gone. */
43
+ export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ target: { acquire, release, waitForConnection }, hub, method, getOptions, }: {
44
+ target: {
45
+ acquire: (hub: H) => void;
46
+ release: (hub: H) => void;
47
+ waitForConnection: (hub: H, timeoutMs: number) => Promise<HubConnection>;
48
+ };
49
+ hub: H;
50
+ method: M;
51
+ getOptions: () => TeardownOptions | undefined;
52
+ }): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
package/dist/calls.js CHANGED
@@ -1,67 +1,74 @@
1
1
  import { HubConnectionState } from "@microsoft/signalr";
2
- import { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
2
+ import { isFinalWaitError } from "./errors.js";
3
+ import { DEFAULT_BACKOFF, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
3
4
  const DEFAULT_TIMEOUT = 10000;
4
5
  const DEFAULT_TEARDOWN_TIMEOUT = 10000;
5
- /**
6
- * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
7
- * called at CALL time (not build time), so the adapter can pass a ref/latest
8
- * accessor and preserve latest-options semantics. `setAbort` is called once
9
- * per invocation with the new controller, so the adapter's unmount/cleanup
10
- * handler can abort the in-flight call.
11
- */
12
- export function createInvoker(target, hub, method, getOptions, setAbort) {
13
- const { waitForConnection, getConnection } = target;
14
- return async (...args) => {
15
- const o = getOptions();
6
+ export function createAbortScope() {
7
+ let controller = new AbortController();
8
+ return {
9
+ signal: () => controller.signal,
10
+ abort: () => {
11
+ const stale = controller;
12
+ controller = new AbortController();
13
+ stale.abort(new DOMException("The consumer unmounted, so the call was aborted.", "AbortError"));
14
+ },
15
+ };
16
+ }
17
+ /** Builds the stable invoke function for one hub method. */
18
+ export function createInvoker({ target, hub, method, getOptions, getSignal, }) {
19
+ const { waitForConnection, getConnection, acquire, release } = target;
20
+ const attempts = async (o, args) => {
16
21
  const timeout = o?.timeout ?? DEFAULT_TIMEOUT;
17
22
  const retries = o?.retries ?? 0;
18
- const ac = new AbortController();
19
- setAbort(ac);
23
+ const signal = getSignal?.() ?? new AbortController().signal;
20
24
  let attempt = 0;
21
25
  for (;;) {
22
26
  try {
23
- const connection = await waitForConnection(hub, timeout);
27
+ const connection = await waitForConnection(hub, timeout, signal);
28
+ signal.throwIfAborted();
24
29
  return await connection.invoke(method, ...args);
25
30
  }
26
31
  catch (error) {
32
+ if (signal.aborted)
33
+ throw error; // abort wins: never reclassify or retry
27
34
  const conn = getConnection(hub);
28
35
  const forced = o?.isRetriable?.(error);
29
- const retriable = forced ?? (conn ? isRetriableInvokeError(error, conn) : true);
30
- if (!retriable || attempt >= retries) {
31
- // No retries: rethrow the raw error, so callers see the original.
32
- if (retries === 0)
33
- throw error;
34
- throw new InvokeError(`SignalR invoke ${hub}/${String(method)} failed after ${attempt + 1} attempts`, error, attempt + 1, retriable);
35
- }
36
- await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), ac.signal);
36
+ const retriable = forced ??
37
+ (isFinalWaitError(error) ? false : conn ? isRetriableInvokeError(error, conn) : true);
38
+ if (!retriable || attempt >= retries)
39
+ throw error;
40
+ await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), signal);
37
41
  attempt += 1;
38
42
  }
39
43
  }
40
44
  };
45
+ return async (...args) => {
46
+ const o = getOptions();
47
+ const holdsHub = o?.keepAliveOnUnmount === true && acquire && release;
48
+ if (holdsHub)
49
+ acquire(hub);
50
+ try {
51
+ return await attempts(o, args);
52
+ }
53
+ finally {
54
+ if (holdsHub)
55
+ release(hub);
56
+ }
57
+ };
41
58
  }
42
- /**
43
- * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
44
- * connection at call time and never depends on render/tracked state, so it
45
- * is safe to capture in an unmount/cleanup handler.
46
- */
47
- export function createSender(getConnection, hub, method) {
59
+ /** Fire-and-forget sender. It reads the connection at call time, so a teardown handler can capture it. */
60
+ export function createSender({ getConnection, hub, method, }) {
48
61
  return (...args) => {
49
62
  const connection = getConnection(hub);
50
63
  if (!connection || connection.state !== HubConnectionState.Connected) {
51
64
  return Promise.resolve(false); // dropped: not connected
52
65
  }
53
66
  // send() is variadic and untyped; args are enforced at the call site.
54
- return connection.send(method, ...args).then(() => true);
67
+ return connection.send(method, ...args).then(() => true, () => false);
55
68
  };
56
69
  }
57
- /**
58
- * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
59
- * detached from the caller's lifecycle: it acquires the hub itself, waits
60
- * for a connection, sends, then releases — independent of the component
61
- * that created it having already unmounted.
62
- */
63
- export function createTeardownSender(deps, hub, method, getOptions) {
64
- const { acquire, release, waitForConnection } = deps;
70
+ /** Teardown sender. It acquires the hub itself, so it still works after its consumer is gone. */
71
+ export function createTeardownSender({ target: { acquire, release, waitForConnection }, hub, method, getOptions, }) {
65
72
  return (...args) => {
66
73
  const timeout = getOptions()?.timeout ?? DEFAULT_TEARDOWN_TIMEOUT;
67
74
  acquire(hub); // hold the hub open past our own unmount, until flushed
package/dist/config.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import type { HubDef, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types";
1
+ import type { IHubProtocol } from "@microsoft/signalr";
2
+ import type { HubDef, HttpOptions, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types.js";
2
3
  /** Typed `Object.keys`. Narrows the keys to the declared hubs. */
3
4
  export declare function hubKeys<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): Array<keyof H & HubString>;
5
+ /** Join the base URL and a hub path without a double slash. */
6
+ export declare function joinHubUrl(baseUrl: string, hub: HubString): string;
7
+ /** Throws when a binary protocol meets a transport that only has Server-Sent Events. */
8
+ export declare function assertProtocolFitsTransport(hub: string, protocol: IHubProtocol, httpOptions: HttpOptions): void;
4
9
  /** Merge a hub's per-hub config over the global defaults. */
5
- export declare function resolveHubConfig<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>, perHub: HubDef | undefined): ResolvedHubConfig;
6
- /**
7
- * Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
8
- * negotiate failures (auth, wrong path, bad request) are not — a retry just
9
- * hammers the server. Network, transient, and 5xx failures are worth a retry.
10
- */
10
+ export declare function resolveHubConfig<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>, hub: keyof H & HubString): ResolvedHubConfig;
11
+ /** True for network, timeout, and 5xx failures. Auth, wrong-path, and bad-request negotiate failures are permanent. */
11
12
  export declare function isRetriableConnectError(err: unknown): boolean;
package/dist/config.js CHANGED
@@ -1,32 +1,86 @@
1
- import { HttpError, LogLevel } from "@microsoft/signalr";
1
+ import { HttpError, HttpTransportType, LogLevel, TransferFormat } from "@microsoft/signalr";
2
2
  /** Typed `Object.keys`. Narrows the keys to the declared hubs. */
3
3
  export function hubKeys(config) {
4
4
  return Object.keys(config.hubs);
5
5
  }
6
+ function mergeHttpOptions(global = {}, perHub = {}) {
7
+ const merged = { ...global, ...perHub };
8
+ if (global.headers && perHub.headers) {
9
+ merged.headers = { ...global.headers, ...perHub.headers };
10
+ }
11
+ return merged;
12
+ }
13
+ /** Join the base URL and a hub path without a double slash. */
14
+ export function joinHubUrl(baseUrl, hub) {
15
+ return `${baseUrl.replace(/\/+$/, "")}${hub}`;
16
+ }
17
+ /** Throws when a binary protocol meets a transport that only has Server-Sent Events. */
18
+ export function assertProtocolFitsTransport(hub, protocol, httpOptions) {
19
+ if (protocol.transferFormat === TransferFormat.Binary &&
20
+ httpOptions.transport === HttpTransportType.ServerSentEvents) {
21
+ throw new Error(`Hub "${hub}": the "${protocol.name}" protocol sends binary data. ` +
22
+ "Server-Sent Events cannot carry binary data. " +
23
+ "Use WebSockets or LongPolling in httpOptions.transport, or use a text protocol.");
24
+ }
25
+ }
26
+ /** Throws when skipNegotiation is on and the transport is not WebSockets only. */
27
+ function assertSkipNegotiationFitsTransport(hub, httpOptions) {
28
+ if (httpOptions.skipNegotiation && httpOptions.transport !== HttpTransportType.WebSockets) {
29
+ throw new Error(`Hub "${hub}": skipNegotiation needs httpOptions.transport = HttpTransportType.WebSockets.`);
30
+ }
31
+ }
32
+ const REMOVED_KEYS = {
33
+ transport: "Move it into httpOptions.",
34
+ skipNegotiation: "Move it into httpOptions.",
35
+ maxConnectRetries: "The library retries a failed hub until the hub stops. Delete the option.",
36
+ };
37
+ function assertNoRemovedKeys(where, options) {
38
+ if (!options)
39
+ return;
40
+ for (const [key, advice] of Object.entries(REMOVED_KEYS)) {
41
+ if (key in options)
42
+ throw new Error(`${where}: the "${key}" option does not exist. ${advice}`);
43
+ }
44
+ }
6
45
  /** Merge a hub's per-hub config over the global defaults. */
7
- export function resolveHubConfig(config, perHub) {
46
+ export function resolveHubConfig(config, hub) {
47
+ const perHub = config.hubs[hub];
48
+ assertNoRemovedKeys("SignalR config", config);
49
+ assertNoRemovedKeys(`Hub "${hub}"`, perHub);
50
+ const httpOptions = mergeHttpOptions(config.httpOptions, perHub?.httpOptions);
51
+ assertSkipNegotiationFitsTransport(hub, httpOptions);
52
+ const hubProtocol = perHub?.hubProtocol ?? config.hubProtocol;
53
+ if (hubProtocol && typeof hubProtocol !== "function") {
54
+ assertProtocolFitsTransport(hub, hubProtocol, httpOptions);
55
+ }
56
+ const configureBuilders = [];
57
+ if (config.configureBuilder)
58
+ configureBuilders.push(config.configureBuilder);
59
+ if (perHub?.configureBuilder)
60
+ configureBuilders.push(perHub.configureBuilder);
8
61
  return {
9
62
  lazy: perHub?.lazy ?? config.lazy ?? false,
10
63
  graceMs: perHub?.graceMs ?? 0,
11
64
  reconnect: perHub?.reconnect ?? config.reconnect ?? true,
12
- maxConnectRetries: perHub?.maxConnectRetries ?? config.maxConnectRetries ?? 2,
13
65
  logLevel: perHub?.logLevel ?? config.logLevel ?? LogLevel.Information,
14
- transport: perHub?.transport,
15
- skipNegotiation: perHub?.skipNegotiation,
66
+ httpOptions,
67
+ hubProtocol,
68
+ configureBuilders,
16
69
  events: Object.keys(perHub?.events ?? {}),
17
70
  };
18
71
  }
19
- /**
20
- * Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
21
- * negotiate failures (auth, wrong path, bad request) are not — a retry just
22
- * hammers the server. Network, transient, and 5xx failures are worth a retry.
23
- */
72
+ /** True for network, timeout, and 5xx failures. Auth, wrong-path, and bad-request negotiate failures are permanent. */
24
73
  export function isRetriableConnectError(err) {
25
- if (err instanceof HttpError) {
26
- const s = err.statusCode;
27
- if (s === 400 || s === 401 || s === 403 || s === 404)
28
- return false;
29
- return true; // 0 (network), 408, 429, 5xx, and other transient codes
30
- }
31
- return true; // timeout, transport, or unknown error: retry
74
+ const s = err instanceof HttpError ? err.statusCode : negotiateStatusCode(err);
75
+ // 0 (network), 408, 429, 5xx, timeouts, and unknown errors are transient.
76
+ return !(s === 400 || s === 401 || s === 403 || s === 404);
77
+ }
78
+ // SignalR wraps negotiate HttpErrors and keeps only their message.
79
+ function negotiateStatusCode(err) {
80
+ if (!(err instanceof Error) || !("errorType" in err))
81
+ return undefined;
82
+ if (err.errorType !== "FailedToNegotiateWithServerError")
83
+ return undefined;
84
+ const code = /Status code '(\d{3})'/.exec(err.message)?.[1];
85
+ return code === undefined ? undefined : Number(code);
32
86
  }
@@ -1,5 +1,7 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- import type { HubConnectionStatus, HubString, ResolvedHubConfig } from "./types";
2
+ import type { HubConnectionStatus, SignalRErrorInfo, HubString, ResolvedHubConfig } from "./types.js";
3
+ /** Runs a user callback. A throw or a rejection goes to onError. A failure of onError is dropped. */
4
+ export declare function runUserCallback<Hub extends HubString>(hub: Hub, callback: () => unknown, onError: (hub: Hub, error: unknown) => unknown): void;
3
5
  export interface ConnectionManagerDeps<Hub extends HubString> {
4
6
  baseUrl: string;
5
7
  hubs: Hub[];
@@ -11,8 +13,14 @@ export interface ConnectionManagerDeps<Hub extends HubString> {
11
13
  /** Pending lazy-stop timers, shared across rebuilds. */
12
14
  stopTimers: Map<Hub, ReturnType<typeof setTimeout>>;
13
15
  reconnectListeners: Map<Hub, Set<() => void>>;
14
- onStatus: (hub: Hub, status: HubConnectionStatus) => void;
15
- onError: (hub: Hub, error: unknown) => void;
16
+ /** Hubs that connected before, shared across rebuilds. A later connect of one runs the reconnect listeners. */
17
+ connectedBefore: Set<Hub>;
18
+ /** Delivers a server push to the session's handler registry. */
19
+ dispatch: (hub: Hub, event: string, args: unknown[]) => void;
20
+ /** `error` is set when the status is "disconnected" after a failure. */
21
+ onStatus: (hub: Hub, status: HubConnectionStatus, error?: unknown) => void;
22
+ /** Reports once per outage: the first failed attempt of a retriable outage, or a non-retriable error. */
23
+ onError: (hub: Hub, error: unknown, info: SignalRErrorInfo) => void;
16
24
  /** True while this manager's generation is the live one. Guards stale rebuilds. */
17
25
  isCurrent: () => boolean;
18
26
  }
@@ -20,14 +28,8 @@ export interface ConnectionManager<Hub extends HubString> {
20
28
  /** Builds/starts desired hubs and stops undesired ones. Safe to call repeatedly. */
21
29
  reconcile: () => void;
22
30
  getConnection: (hub: Hub) => HubConnection | null;
23
- /** Resolves once the hub is connected. Rejects after timeoutMs otherwise. */
24
- waitForConnection: (hub: Hub, timeoutMs: number) => Promise<HubConnection>;
25
31
  /** Stops all connections and cancels timers. */
26
32
  dispose: () => void;
27
33
  }
28
- /**
29
- * Owns the HubConnection lifecycle for one provider generation: building,
30
- * starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
31
- * Has no React dependency — driven by the provider's effect and context callbacks.
32
- */
34
+ /** Owns the hub connections of one provider generation: build, start with recovery, lazy ref-counted stop. */
33
35
  export declare function createConnectionManager<Hub extends HubString>(deps: ConnectionManagerDeps<Hub>): ConnectionManager<Hub>;