@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/README.md CHANGED
@@ -1,84 +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). Core owns all connection behavior. Every adapter in this repository is a thin reactive layer on top of it.
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. This package has no provider, no hooks, and no reactive layer.
12
-
13
- If you build an application, install an adapter instead of core. Core is a dependency of every adapter:
14
-
15
- - [`@dammers/use-signalr-react`](https://github.com/DammersCode/use-signalr/blob/main/packages/react/README.md)
16
- - [`@dammers/use-signalr-solid`](https://github.com/DammersCode/use-signalr/blob/main/packages/solid/README.md)
17
- - [`@dammers/use-signalr-svelte`](https://github.com/DammersCode/use-signalr/blob/main/packages/svelte/README.md)
18
- - [`@dammers/use-signalr-angular`](https://github.com/DammersCode/use-signalr/blob/main/packages/angular/README.md)
19
- - [`@dammers/use-signalr-vue`](https://github.com/DammersCode/use-signalr/blob/main/packages/vue/README.md)
20
- - [`@dammers/use-signalr-preact`](https://github.com/DammersCode/use-signalr/blob/main/packages/preact/README.md)
21
- - [`@dammers/use-signalr-lit`](https://github.com/DammersCode/use-signalr/blob/main/packages/lit/README.md)
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 |
22
19
 
23
20
  ## Install
24
21
 
25
22
  ```bash
26
- npm i @dammers/use-signalr-core @microsoft/signalr
23
+ npm install @dammers/use-signalr-core @microsoft/signalr
27
24
  ```
28
25
 
29
- Core requires `@microsoft/signalr` ≥ 8.
30
-
31
- ## The adapter entry point
32
-
33
- `createSignalRSession(deps)` is the one call an adapter builds its provider around. It owns the connection generation, lazy ref counts, grace periods, reconnect fan-out, and the context value.
34
-
35
- ```ts
36
- import { createSignalRSession } from "@dammers/use-signalr-core";
37
-
38
- const session = createSignalRSession({
39
- hubs, // the hub paths from the config
40
- resolve, // (hub) => ResolvedHubConfig
41
- statusStore, // the adapter's own reactive StatusStore
42
- getAccessToken, // read at call time, so token rotation causes no rebuild
43
- onStatusChange, // optional
44
- onError, // optional
45
- });
46
- ```
47
-
48
- The session returns three members:
49
-
50
- | Member | What it does |
51
- | --- | --- |
52
- | `start(baseUrl)` | Builds the live connection generation and disposes the previous one. |
53
- | `stop()` | Disposes the live generation and marks every hub disconnected. Idempotent. |
54
- | `context` | The value the adapter puts into its framework context. Stable identity. |
55
-
56
- Call `start` only from a client-only lifecycle hook. `createSignalRSession` does no I/O when you construct it.
57
-
58
- ## Call helpers
59
-
60
- An adapter maps its invoke, send, and teardown surface onto these three factories. Do not reimplement their semantics.
61
-
62
- | Helper | What it does |
63
- | --- | --- |
64
- | `createInvoker(target, hub, method, getOptions, setAbort, clearAbort?)` | Request/response call: waits for a connection, retries retriable failures, rethrows business errors. |
65
- | `createSender(getConnection, hub, method)` | Fire-and-forget call. Drops the call when the hub is not connected. |
66
- | `createTeardownSender(deps, hub, method, getOptions)` | Reliable cleanup call: survives disposal, queues while connecting, and holds a lazy hub open until it flushes. |
67
-
68
- `createAbortScope()` tracks every in-flight invoke `AbortController` for one consumer. Pass its `track` and `untrack` as `setAbort` and `clearAbort`. Call `abortAll` from the adapter's cleanup to abort all in-flight calls at once.
69
-
70
- ## Also exported
71
-
72
- `event<Args>()` and `method<Args, Return?>()` declare a hub contract. `hubKeys(config)` and `resolveHubConfig(config, hubConfig)` resolve per-hub configuration against the global defaults. `isRetriableConnectError`, `isRetriableInvokeError`, `resolveBackoff`, `DEFAULT_BACKOFF`, `sleep`, and `InvokeError` are the retry building blocks.
73
-
74
- The contract and configuration types ship with the package: `HubString`, `HubContract`, `SignalRContract`, `EventDef`, `MethodDef`, `HubDef`, `InferContract`, `EventName`, `MethodName`, `EventArgs`, `MethodArgs`, `MethodReturn`, `HubConnectionStatus`, `ReconnectConfig`, `PerHubConfig`, `SignalRClientConfig`, `ResolvedHubConfig`, `InvokeOptions`, `TeardownOptions`, `StatusStore`, `SignalRSession`, `SignalRSessionDeps`, `SignalRProviderPropsBase`, `SignalRContextValueBase`, `ConnectionManager`, `ConnectionManagerDeps`, `HubEntry`, `CallTarget`, `AbortScope`.
75
-
76
- ## More
26
+ It needs `@microsoft/signalr` ^8 || ^9 || ^10 || ^11 and Node 20.19 or later. It has no runtime dependencies.
77
27
 
78
- [ARCHITECTURE.md](https://github.com/DammersCode/use-signalr/blob/main/ARCHITECTURE.md) has the full new-adapter checklist, the core/adapter split, and the naming conventions.
28
+ ## Documentation
79
29
 
80
- Shared concepts (the contract, per-hub configuration, invoke retry, send versus invoke versus 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)
81
32
 
82
33
  ## License
83
34
 
84
- 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,43 +1,58 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
2
  import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types.js";
3
- /**
4
- * Tracks every in-flight invocation of one consumer, so its cleanup aborts
5
- * ALL of them — not just the most recent. Adapters pass `track`/`untrack`
6
- * straight to `createInvoker` and call `abortAll` from their teardown hook.
7
- */
3
+ /** One shared signal for all in-flight calls of a consumer. `abort` cancels them and starts a fresh signal. */
8
4
  export interface AbortScope {
9
- track: (ac: AbortController) => void;
10
- untrack: (ac: AbortController) => void;
11
- abortAll: () => void;
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;
12
9
  }
13
10
  export declare function createAbortScope(): AbortScope;
11
+ /** The members of the context that the invoker needs. */
14
12
  export interface CallTarget<T extends SignalRContract> {
15
- 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. */
16
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;
17
21
  }
18
- /**
19
- * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
20
- * called at CALL time (not build time), so the adapter can pass a ref/latest
21
- * accessor and preserve latest-options semantics. `setAbort` is called once
22
- * per invocation with the new controller, so the adapter's unmount/cleanup
23
- * handler can abort the in-flight call. `clearAbort` runs when that call
24
- * settles, so adapters can retain only active controllers.
25
- */
26
- 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, clearAbort?: (ac: AbortController) => void): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
27
- /**
28
- * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
29
- * connection at call time and never depends on the adapter's tracked state,
30
- * so it is safe to capture in a teardown handler.
31
- */
32
- 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>;
33
- /**
34
- * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
35
- * detached from the caller's lifecycle: it acquires the hub itself, waits
36
- * for a connection, sends, then releases — independent of the consumer
37
- * that created it having already torn down.
38
- */
39
- export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(deps: {
40
- acquire: (hub: H) => void;
41
- release: (hub: H) => void;
42
- waitForConnection: (hub: H, timeoutMs: number) => Promise<HubConnection>;
43
- }, hub: H, method: M, getOptions: () => TeardownOptions | undefined): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
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 a call that still waits. A call that is already sent finishes. */
32
+ getSignal?: () => AbortSignal | undefined;
33
+ }
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, beginSend }, hub, method, getOptions, }: {
44
+ target: {
45
+ acquire: (hub: H) => void;
46
+ release: (hub: H) => void;
47
+ waitForConnection: (hub: H, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
48
+ /** Tells the session that a send is pending, so `stop()` can let it finish. Pass the one from the session context. */
49
+ beginSend?: (hub: H) => {
50
+ signal: AbortSignal;
51
+ use: (connection: HubConnection) => void;
52
+ end: () => void;
53
+ };
54
+ };
55
+ hub: H;
56
+ method: M;
57
+ getOptions: () => TeardownOptions | undefined;
58
+ }): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
package/dist/calls.js CHANGED
@@ -1,101 +1,114 @@
1
1
  import { HubConnectionState } from "@microsoft/signalr";
2
- import { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
2
+ import { isFinalWaitError } from "./errors.js";
3
+ import { MAX_TIMER_MS } from "./timers.js";
4
+ import { DEFAULT_BACKOFF, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
3
5
  const DEFAULT_TIMEOUT = 10000;
4
6
  const DEFAULT_TEARDOWN_TIMEOUT = 10000;
5
7
  export function createAbortScope() {
6
- const active = new Set();
8
+ let controller = new AbortController();
7
9
  return {
8
- track: (ac) => active.add(ac),
9
- untrack: (ac) => active.delete(ac),
10
- abortAll: () => {
11
- active.forEach((ac) => ac.abort());
12
- active.clear();
10
+ signal: () => controller.signal,
11
+ abort: () => {
12
+ const stale = controller;
13
+ controller = new AbortController();
14
+ stale.abort(new DOMException("The consumer unmounted, so the call was aborted.", "AbortError"));
13
15
  },
14
16
  };
15
17
  }
16
- /**
17
- * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
18
- * called at CALL time (not build time), so the adapter can pass a ref/latest
19
- * accessor and preserve latest-options semantics. `setAbort` is called once
20
- * per invocation with the new controller, so the adapter's unmount/cleanup
21
- * handler can abort the in-flight call. `clearAbort` runs when that call
22
- * settles, so adapters can retain only active controllers.
23
- */
24
- export function createInvoker(target, hub, method, getOptions, setAbort, clearAbort) {
25
- const { waitForConnection, getConnection } = target;
26
- return async (...args) => {
27
- const o = getOptions();
18
+ /** Builds the stable invoke function for one hub method. */
19
+ export function createInvoker({ target, hub, method, getOptions, getSignal, }) {
20
+ const { waitForConnection, getConnection, acquire, release } = target;
21
+ const attempts = async (o, args) => {
28
22
  const timeout = o?.timeout ?? DEFAULT_TIMEOUT;
29
23
  const retries = o?.retries ?? 0;
30
- const ac = new AbortController();
31
- setAbort(ac);
32
- try {
33
- let attempt = 0;
34
- for (;;) {
35
- try {
36
- const connection = await waitForConnection(hub, timeout);
37
- return await connection.invoke(method, ...args);
38
- }
39
- catch (error) {
40
- if (ac.signal.aborted)
41
- throw error; // abort wins: never reclassify or retry
42
- const conn = getConnection(hub);
43
- const forced = o?.isRetriable?.(error);
44
- const retriable = forced ?? (conn ? isRetriableInvokeError(error, conn) : true);
45
- if (!retriable || attempt >= retries) {
46
- // No retries: rethrow the raw error, so callers see the original.
47
- if (retries === 0)
48
- throw error;
49
- throw new InvokeError(`SignalR invoke ${hub}/${String(method)} failed after ${attempt + 1} attempts`, error, attempt + 1, retriable);
50
- }
51
- await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), ac.signal);
52
- attempt += 1;
53
- }
24
+ const signal = getSignal?.() ?? new AbortController().signal;
25
+ let attempt = 0;
26
+ for (;;) {
27
+ try {
28
+ const connection = await waitForConnection(hub, timeout, signal);
29
+ signal.throwIfAborted();
30
+ return await connection.invoke(method, ...args);
31
+ }
32
+ catch (error) {
33
+ if (signal.aborted)
34
+ throw error; // abort wins: never reclassify or retry
35
+ const conn = getConnection(hub);
36
+ const forced = o?.isRetriable?.(error);
37
+ const retriable = forced ??
38
+ (isFinalWaitError(error) ? false : conn ? isRetriableInvokeError(error, conn) : true);
39
+ if (!retriable || attempt >= retries)
40
+ throw error;
41
+ await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), signal);
42
+ attempt += 1;
54
43
  }
55
44
  }
45
+ };
46
+ return async (...args) => {
47
+ const o = getOptions();
48
+ const holdsHub = o?.keepAliveOnUnmount === true && acquire && release;
49
+ if (holdsHub)
50
+ acquire(hub);
51
+ try {
52
+ return await attempts(o, args);
53
+ }
56
54
  finally {
57
- clearAbort?.(ac);
55
+ if (holdsHub)
56
+ release(hub);
58
57
  }
59
58
  };
60
59
  }
61
- /**
62
- * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
63
- * connection at call time and never depends on the adapter's tracked state,
64
- * so it is safe to capture in a teardown handler.
65
- */
66
- export function createSender(getConnection, hub, method) {
60
+ /** Fire-and-forget sender. It reads the connection at call time, so a teardown handler can capture it. */
61
+ export function createSender({ getConnection, hub, method, }) {
67
62
  return (...args) => {
68
63
  const connection = getConnection(hub);
69
64
  if (!connection || connection.state !== HubConnectionState.Connected) {
70
65
  return Promise.resolve(false); // dropped: not connected
71
66
  }
72
67
  // send() is variadic and untyped; args are enforced at the call site.
73
- return connection.send(method, ...args).then(() => true);
68
+ return connection.send(method, ...args).then(() => true, () => false);
74
69
  };
75
70
  }
76
- /**
77
- * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
78
- * detached from the caller's lifecycle: it acquires the hub itself, waits
79
- * for a connection, sends, then releases — independent of the consumer
80
- * that created it having already torn down.
81
- */
82
- export function createTeardownSender(deps, hub, method, getOptions) {
83
- const { acquire, release, waitForConnection } = deps;
71
+ function ignoreErrors(fn) {
72
+ try {
73
+ fn();
74
+ }
75
+ catch {
76
+ // Nothing is left to report to.
77
+ }
78
+ }
79
+ /** Teardown sender. It acquires the hub itself, so it still works after its consumer is gone. */
80
+ export function createTeardownSender({ target: { acquire, release, waitForConnection, beginSend }, hub, method, getOptions, }) {
84
81
  return (...args) => {
85
82
  const timeout = getOptions()?.timeout ?? DEFAULT_TEARDOWN_TIMEOUT;
83
+ const inFlight = beginSend?.(hub); // registered before any await, so a later stop() sees it
86
84
  acquire(hub); // hold the hub open past our own unmount, until flushed
87
- return (async () => {
88
- try {
89
- const connection = await waitForConnection(hub, timeout);
90
- await connection.send(method, ...args);
91
- return true;
92
- }
93
- catch {
94
- return false; // never connected in time, or the send failed: best-effort
95
- }
96
- finally {
97
- release(hub);
98
- }
99
- })();
85
+ return new Promise((resolve) => {
86
+ let finished = false;
87
+ const finish = (sent) => {
88
+ if (finished)
89
+ return;
90
+ finished = true;
91
+ clearTimeout(timer);
92
+ resolve(sent);
93
+ // A failing cleanup must not leave the call pending or throw from a timer.
94
+ ignoreErrors(() => release(hub));
95
+ ignoreErrors(() => inFlight?.end());
96
+ };
97
+ // The timeout also covers the send, so a stuck send cannot hold a stopped connection open.
98
+ const timer = Number.isFinite(timeout)
99
+ ? setTimeout(() => finish(false), Math.min(timeout, MAX_TIMER_MS))
100
+ : undefined;
101
+ void (async () => {
102
+ try {
103
+ const connection = await waitForConnection(hub, timeout, inFlight?.signal);
104
+ inFlight?.use(connection);
105
+ await connection.send(method, ...args);
106
+ finish(true);
107
+ }
108
+ catch {
109
+ finish(false); // never connected in time, the session stopped, or the send failed: best-effort
110
+ }
111
+ })();
112
+ });
100
113
  };
101
114
  }
package/dist/config.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import type { HubDef, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types.js";
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.js";
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,23 +13,23 @@ 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
- /** True while this manager's generation is the live one. Guards stale rebuilds. */
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;
24
+ /** True while this manager is the live one. Guards stale rebuilds. */
17
25
  isCurrent: () => boolean;
18
26
  }
19
27
  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
- /** Stops all connections and cancels timers. */
26
- dispose: () => void;
31
+ /** Stops all connections and cancels timers. A connected hub in `keep` stays open and is returned, so the caller closes it. */
32
+ dispose: (keep?: ReadonlySet<Hub>) => Map<Hub, HubConnection>;
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
- * Framework-neutral — driven by the adapter's lifecycle hook and context callbacks.
32
- */
34
+ /** Owns the hub connections of one provider: build, start with recovery, lazy ref-counted stop. */
33
35
  export declare function createConnectionManager<Hub extends HubString>(deps: ConnectionManagerDeps<Hub>): ConnectionManager<Hub>;