@dammers/use-signalr-react 0.1.0 → 0.5.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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 DammersCode
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DammersCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -161,6 +161,36 @@ It is best-effort and fire-and-forget: it resolves `true` once dispatched, `fals
161
161
 
162
162
  > If your leave already uses `useSignalRInvoke` and only needs to avoid the abort on unmount, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `useSignalRTeardown`.
163
163
 
164
+ ## SSR (Next.js)
165
+
166
+ The import is server-safe. No connection work happens at module scope or during a server render.
167
+
168
+ `SignalRProvider` starts connections inside `useEffect`, which runs only in the browser. Every hub reports `"disconnected"` until that effect runs.
169
+
170
+ Mark the component that mounts the provider with `"use client"`.
171
+
172
+ ## Lazy hubs and `graceMs`
173
+
174
+ Set `lazy: true` on a hub to connect it only when the first hook for that hub mounts. Consumers are ref-counted.
175
+
176
+ After the last consumer unmounts, the connection stays open for `graceMs` milliseconds. If a new consumer mounts inside that window, the connection stays. The default is `0`.
177
+
178
+ ```ts
179
+ createSignalRClient({
180
+ hubs: {
181
+ "/hubs/presence": { lazy: true, graceMs: 5000 },
182
+ },
183
+ });
184
+ ```
185
+
186
+ ## `InvokeError`
187
+
188
+ `useSignalRInvoke` throws `InvokeError` when its retry budget is exhausted. The error carries `cause` (the last underlying error), `attempts` (the total number of attempts), and `retriable` (whether the final failure was classed as retriable).
189
+
190
+ `InvokeError` is thrown only when you set `retries` above `0`. With the default `retries: 0`, the raw server error propagates unchanged.
191
+
192
+ The `timeout` option bounds only the wait for a connected hub before dispatch. SignalR cannot cancel an invocation after dispatch.
193
+
164
194
  ## API
165
195
 
166
196
  | Export | What it does |
@@ -170,13 +200,14 @@ It is best-effort and fire-and-forget: it resolves `true` once dispatched, `fals
170
200
  | `method<Args, Return?>()` | Declares an invocable server method inside a hub's `methods`. `Args` is the argument tuple; `Return` is the resolved return type (default `void`). |
171
201
  | `<SignalRProvider>` | Builds and starts connections, retries, and auto-reconnects. |
172
202
  | `useSignalREffect(hub, event, handler)` | Subscribes to a server event for the component's lifetime. |
173
- | `useSignalRInvoke(hub, method, opts?)` | Typed request/response invoker. Waits for the connection and returns the method's result. Optional retry/backoff/timeout; `keepAliveOnUnmount` skips the unmount abort. |
203
+ | `useSignalRInvoke(hub, method, opts?)` | Typed request/response invoker. Returns the method's result. `timeout` bounds only the wait for a connected hub. `keepAliveOnUnmount` skips the unmount abort. |
174
204
  | `useSignalRSend(hub, method)` | Typed fire-and-forget sender. **Drops** if not connected. For high-frequency signals where loss is acceptable. Safe in unmount cleanups. |
175
205
  | `useSignalRTeardown(hub, method, opts?)` | Reliable teardown sender for a method called in cleanup: survives unmount, **queues** while connecting instead of dropping, and holds a lazy hub open until flushed. |
176
206
  | `useHubStatus(hub)` | Live connection status. Re-renders only when that hub changes. |
177
207
  | `useOnReconnected(hub, cb)` | Runs `cb` after the hub reconnects, for example to refetch. |
178
208
  | `useHubConsumer(hub)` | Keeps a lazy hub connected for the component's lifetime without subscribing. |
179
209
  | `useSignalR()` | Last-resort raw context: `getConnection`, `isHubConnected`, `getStatus`. |
210
+ | `InvokeError` | Thrown by `useSignalRInvoke` once retries are exhausted. Wraps the last failure. |
180
211
 
181
212
  ### Provider props
182
213
 
@@ -1,5 +1,5 @@
1
1
  import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
2
- import type { SignalRContextValue } from "./types";
2
+ import type { SignalRContextValue } from "./types.js";
3
3
  /**
4
4
  * Creates a fully-typed SignalR client. Returns a provider and hooks, typed
5
5
  * against the contract inferred from `config.hubs`: the keys declare the
@@ -12,7 +12,7 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
12
12
  * configured hub. Pass `baseUrl` and `accessTokenFactory`, and gate them
13
13
  * with `enabled`. Mount it once, near the root.
14
14
  */
15
- SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types").SignalRProviderProps) => import("react").JSX.Element;
15
+ SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types.js").SignalRProviderProps) => import("react").JSX.Element;
16
16
  /**
17
17
  * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
18
18
  * `isHubConnected`, and more). Prefer the typed hooks below. Use this only
@@ -1,7 +1,7 @@
1
1
  import { createContext } from "react";
2
2
  import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
3
- import { createSignalRProvider } from "./internal/create-provider";
4
- import { createSignalRHooks } from "./internal/create-hooks";
3
+ import { createSignalRProvider } from "./internal/create-provider.js";
4
+ import { createSignalRHooks } from "./internal/create-hooks.js";
5
5
  /**
6
6
  * Creates a fully-typed SignalR client. Returns a provider and hooks, typed
7
7
  * against the contract inferred from `config.hubs`: the keys declare the
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { createSignalRClient } from "./create-signalr-client";
1
+ export { createSignalRClient } from "./create-signalr-client.js";
2
2
  export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
- export type { StatusStore } from "./status-store";
3
+ export type { StatusStore } from "./status-store.js";
4
4
  export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubDef, EventDef, MethodDef, InferContract, ResolvedHubConfig, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
5
- export type { SignalRProviderProps, SignalRContextValue } from "./types";
5
+ export type { SignalRProviderProps, SignalRContextValue } from "./types.js";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { createSignalRClient } from "./create-signalr-client";
1
+ export { createSignalRClient } from "./create-signalr-client.js";
2
2
  export { InvokeError, event, method } from "@dammers/use-signalr-core";
@@ -1,6 +1,6 @@
1
1
  import type { Context } from "react";
2
2
  import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "@dammers/use-signalr-core";
3
- import type { SignalRContextValue } from "../types";
3
+ import type { SignalRContextValue } from "../types.js";
4
4
  /** Builds the hooks bound to one client's context. */
5
5
  export declare function createSignalRHooks<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>): {
6
6
  useSignalR: () => SignalRContextValue<T>;
@@ -1,6 +1,6 @@
1
1
  import { use, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
2
- import { useLatest } from "../internal-hooks";
3
- import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
2
+ import { useLatest } from "../internal-hooks.js";
3
+ import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
4
4
  /** Builds the hooks bound to one client's context. */
5
5
  export function createSignalRHooks(ReactContext) {
6
6
  /**
@@ -45,7 +45,8 @@ export function createSignalRHooks(ReactContext) {
45
45
  function useHubStatus(hub) {
46
46
  const { statusStore } = useSignalR();
47
47
  useHubConsumer(hub);
48
- return useSyncExternalStore(statusStore.subscribe, () => statusStore.get(hub), () => statusStore.get(hub));
48
+ const subscribe = useMemo(() => (listener) => statusStore.subscribe(hub, listener), [statusStore, hub]);
49
+ return useSyncExternalStore(subscribe, () => statusStore.get(hub), () => statusStore.get(hub));
49
50
  }
50
51
  /**
51
52
  * Runs a callback every time a hub reconnects, after a dropped connection
@@ -118,14 +119,14 @@ export function createSignalRHooks(ReactContext) {
118
119
  const { waitForConnection, getConnection } = useSignalR();
119
120
  useHubConsumer(hub);
120
121
  const optsRef = useLatest(options);
121
- const abortRef = useRef(null);
122
+ const scopeRef = useRef(null);
123
+ scopeRef.current ?? (scopeRef.current = createAbortScope());
124
+ const scope = scopeRef.current;
122
125
  useEffect(() => () => {
123
126
  if (!optsRef.current?.keepAliveOnUnmount)
124
- abortRef.current?.abort();
125
- }, [optsRef]);
126
- return useMemo(() => createInvoker({ waitForConnection, getConnection }, hub, method, () => optsRef.current, (ac) => {
127
- abortRef.current = ac;
128
- }), [waitForConnection, getConnection, hub, method, optsRef]);
127
+ scope.abortAll();
128
+ }, [optsRef, scope]);
129
+ return useMemo(() => createInvoker({ waitForConnection, getConnection }, hub, method, () => optsRef.current, scope.track, scope.untrack), [waitForConnection, getConnection, hub, method, optsRef, scope]);
129
130
  }
130
131
  /**
131
132
  * Returns a stable, typed fire-and-forget sender. Unlike {@link useSignalRInvoke},
@@ -1,5 +1,5 @@
1
1
  import type { Context } from "react";
2
2
  import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
3
- import type { SignalRContextValue, SignalRProviderProps } from "../types";
3
+ import type { SignalRContextValue, SignalRProviderProps } from "../types.js";
4
4
  /** Builds the `SignalRProvider` component bound to one client's context. */
5
5
  export declare function createSignalRProvider<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: SignalRProviderProps) => import("react").JSX.Element;
@@ -1,87 +1,36 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useMemo, useRef } from "react";
3
- import { useLatest } from "../internal-hooks";
4
- import { createStatusStore } from "../status-store";
5
- import { createConnectionManager } from "@dammers/use-signalr-core";
3
+ import { useLatest } from "../internal-hooks.js";
4
+ import { createStatusStore } from "../status-store.js";
5
+ import { createSignalRSession } from "@dammers/use-signalr-core";
6
6
  /** Builds the `SignalRProvider` component bound to one client's context. */
7
7
  export function createSignalRProvider(ReactContext, hubs, resolve) {
8
8
  return function SignalRProvider({ children, baseUrl, accessTokenFactory, enabled = true, connectionKey, onStatusChange, onError, }) {
9
9
  const statusStore = useRef(createStatusStore()).current;
10
- // Lazy ref-counts, pending stop timers, and reconnect listeners persist
11
- // across rebuilds. The live manager is swapped per generation.
12
- const refCounts = useRef(new Map()).current;
13
- const stopTimers = useRef(new Map()).current;
14
- const reconnectListeners = useRef(new Map()).current;
15
- const managerRef = useRef(null);
16
10
  // Latest props via refs, so once-attached handlers call the current props.
17
11
  const tokenFactoryRef = useLatest(accessTokenFactory);
18
12
  const onStatusChangeRef = useLatest(onStatusChange);
19
13
  const onErrorRef = useLatest(onError);
14
+ const session = useRef(createSignalRSession({
15
+ hubs,
16
+ resolve,
17
+ statusStore,
18
+ getAccessToken: () => tokenFactoryRef.current(),
19
+ onStatusChange: (hub, status) => onStatusChangeRef.current?.(hub, status),
20
+ onError: (hub, err) => onErrorRef.current?.(hub, err),
21
+ })).current;
20
22
  useEffect(() => {
21
23
  if (!enabled || !baseUrl) {
22
- managerRef.current?.dispose();
23
- managerRef.current = null;
24
- hubs.forEach((h) => statusStore.set(h, "disconnected"));
24
+ session.stop();
25
25
  return;
26
26
  }
27
- const manager = createConnectionManager({
28
- baseUrl,
29
- hubs,
30
- resolve,
31
- getAccessToken: () => tokenFactoryRef.current(),
32
- refCounts,
33
- stopTimers,
34
- reconnectListeners,
35
- onStatus: (hub, status) => {
36
- statusStore.set(hub, status);
37
- onStatusChangeRef.current?.(hub, status);
38
- },
39
- onError: (hub, err) => onErrorRef.current?.(hub, err),
40
- isCurrent: () => managerRef.current === manager,
41
- });
42
- managerRef.current = manager;
43
- manager.reconcile(); // build eager hubs plus already-referenced lazy hubs
44
- return () => {
45
- manager.dispose();
46
- if (managerRef.current === manager)
47
- managerRef.current = null;
48
- };
27
+ session.start(baseUrl);
28
+ return () => session.stop();
49
29
  // Rebuild only when the connection identity changes. tokenFactoryRef and
50
30
  // on*Ref are stable; props are read through .current.
51
31
  // eslint-disable-next-line react-hooks/exhaustive-deps
52
32
  }, [baseUrl, enabled, connectionKey]);
53
- const value = useMemo(() => ({
54
- getConnection: (hub) => managerRef.current?.getConnection(hub) ?? null,
55
- isHubConnected: (hub) => statusStore.get(hub) === "connected",
56
- getStatus: (hub) => statusStore.get(hub),
57
- statusStore,
58
- waitForConnection: (hub, timeoutMs) => {
59
- const manager = managerRef.current;
60
- if (!manager) {
61
- return Promise.reject(new Error(`SignalR not connected: ${String(hub)}`));
62
- }
63
- return manager.waitForConnection(hub, timeoutMs);
64
- },
65
- acquire: (hub) => {
66
- const next = (refCounts.get(hub) ?? 0) + 1;
67
- refCounts.set(hub, next);
68
- if (next === 1)
69
- managerRef.current?.reconcile();
70
- },
71
- release: (hub) => {
72
- const next = Math.max(0, (refCounts.get(hub) ?? 0) - 1);
73
- refCounts.set(hub, next);
74
- if (next === 0)
75
- managerRef.current?.reconcile();
76
- },
77
- registerReconnect: (hub, cb) => {
78
- let set = reconnectListeners.get(hub);
79
- if (!set)
80
- reconnectListeners.set(hub, (set = new Set()));
81
- set.add(cb);
82
- return () => set.delete(cb);
83
- },
84
- }), [statusStore, refCounts, reconnectListeners]);
33
+ const value = useMemo(() => session.context, [session]);
85
34
  return _jsx(ReactContext, { value: value, children: children });
86
35
  };
87
36
  }
@@ -6,6 +6,7 @@ import type { StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
6
6
  * status changes.
7
7
  */
8
8
  export interface StatusStore<H extends string> extends StatusStoreBase<H> {
9
- subscribe: (listener: () => void) => () => void;
9
+ subscribe: (hub: H, listener: () => void) => () => void;
10
10
  }
11
+ /** Separate listener sets keep status updates granular per hub. */
11
12
  export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -1,17 +1,21 @@
1
+ /** Separate listener sets keep status updates granular per hub. */
1
2
  export function createStatusStore() {
2
3
  const snapshot = new Map();
3
- const listeners = new Set();
4
+ const listeners = new Map();
4
5
  return {
5
- subscribe: (listener) => {
6
- listeners.add(listener);
7
- return () => listeners.delete(listener);
6
+ subscribe: (hub, listener) => {
7
+ let set = listeners.get(hub);
8
+ if (!set)
9
+ listeners.set(hub, (set = new Set()));
10
+ set.add(listener);
11
+ return () => set.delete(listener);
8
12
  },
9
13
  get: (hub) => snapshot.get(hub) ?? "disconnected",
10
14
  set: (hub, status) => {
11
15
  if (snapshot.get(hub) === status)
12
16
  return; // dedupe: skip a spurious notify
13
17
  snapshot.set(hub, status);
14
- listeners.forEach((l) => l());
18
+ listeners.get(hub)?.forEach((l) => l());
15
19
  },
16
20
  };
17
21
  }
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ReactNode } from "react";
2
2
  import type { HubString, SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase } from "@dammers/use-signalr-core";
3
- import type { StatusStore } from "./status-store";
3
+ import type { StatusStore } from "./status-store.js";
4
4
  export type SignalRProviderProps = SignalRProviderPropsBase<ReactNode>;
5
5
  export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/package.json CHANGED
@@ -1,12 +1,27 @@
1
1
  {
2
2
  "name": "@dammers/use-signalr-react",
3
- "version": "0.1.0",
3
+ "version": "0.5.0",
4
4
  "description": "Fully-typed multi-hub SignalR provider + hooks for React: auto-reconnect, invoke retry, lazy hubs, live status.",
5
5
  "author": "Dammers",
6
6
  "license": "MIT",
7
- "repository": "github:DammersCode/use-signalr",
8
- "homepage": "https://github.com/DammersCode/use-signalr#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DammersCode/use-signalr.git",
10
+ "directory": "packages/react"
11
+ },
12
+ "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/react#readme",
9
13
  "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
+ "keywords": [
15
+ "signalr",
16
+ "typescript",
17
+ "realtime",
18
+ "websocket",
19
+ "react",
20
+ "hooks"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
10
25
  "type": "module",
11
26
  "sideEffects": false,
12
27
  "main": "./dist/index.js",
@@ -24,17 +39,17 @@
24
39
  "access": "public"
25
40
  },
26
41
  "scripts": {
42
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
27
43
  "build": "tsc -p tsconfig.build.json",
28
44
  "typecheck": "tsc --noEmit",
29
45
  "test": "vitest run"
30
46
  },
31
47
  "dependencies": {
32
- "@dammers/use-signalr-core": "0.1.0"
48
+ "@dammers/use-signalr-core": "0.5.0"
33
49
  },
34
50
  "peerDependencies": {
35
51
  "@microsoft/signalr": ">=8",
36
- "react": ">=19",
37
- "react-dom": ">=19"
52
+ "react": ">=19"
38
53
  },
39
54
  "devDependencies": {
40
55
  "@microsoft/signalr": ">=8",